@contractspec/module.ai-chat 4.3.16 → 4.3.18
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/dist/browser/context/index.js +3 -415
- package/dist/browser/core/index.js +55 -1600
- package/dist/browser/index.js +58 -5251
- package/dist/browser/presentation/components/index.js +56 -4382
- package/dist/browser/presentation/hooks/index.js +32 -1638
- package/dist/browser/presentation/index.js +56 -4430
- package/dist/browser/providers/index.js +1 -51
- package/dist/context/index.js +3 -409
- package/dist/core/index.js +55 -1594
- package/dist/index.js +58 -5245
- package/dist/node/context/index.js +3 -410
- package/dist/node/core/index.js +55 -1595
- package/dist/node/index.js +58 -5246
- package/dist/node/presentation/components/index.js +56 -4377
- package/dist/node/presentation/hooks/index.js +32 -1633
- package/dist/node/presentation/index.js +56 -4425
- package/dist/node/providers/index.js +1 -46
- package/dist/presentation/components/index.js +56 -4376
- package/dist/presentation/hooks/index.js +32 -1632
- package/dist/presentation/index.js +56 -4424
- package/dist/providers/index.js +1 -45
- package/package.json +19 -19
|
@@ -1,692 +1,40 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
})
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
text: result.text,
|
|
16
|
-
toolCalls: result.toolCalls,
|
|
17
|
-
toolResults: result.toolResults,
|
|
18
|
-
usage: result.usage
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
// src/core/agent-tools-adapter.ts
|
|
24
|
-
import { tool } from "ai";
|
|
25
|
-
import { z } from "zod";
|
|
26
|
-
function getInputSchema(_schema) {
|
|
27
|
-
return z.object({}).passthrough();
|
|
28
|
-
}
|
|
29
|
-
function agentToolConfigsToToolSet(configs, handlers) {
|
|
30
|
-
const result = {};
|
|
31
|
-
for (const config of configs) {
|
|
32
|
-
const handler = handlers?.[config.name];
|
|
33
|
-
const inputSchema = getInputSchema(config.schema);
|
|
34
|
-
result[config.name] = tool({
|
|
35
|
-
description: config.description ?? config.name,
|
|
36
|
-
inputSchema,
|
|
37
|
-
execute: async (input) => {
|
|
38
|
-
if (!handler) {
|
|
39
|
-
return {
|
|
40
|
-
status: "unimplemented",
|
|
41
|
-
message: "Wire handler in host",
|
|
42
|
-
toolName: config.name
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
try {
|
|
46
|
-
const output = await Promise.resolve(handler(input));
|
|
47
|
-
return typeof output === "string" ? output : output;
|
|
48
|
-
} catch (err) {
|
|
49
|
-
return {
|
|
50
|
-
status: "error",
|
|
51
|
-
error: err instanceof Error ? err.message : String(err),
|
|
52
|
-
toolName: config.name
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
return result;
|
|
59
|
-
}
|
|
60
|
-
// src/core/chat-service.ts
|
|
61
|
-
import { generateText, streamText } from "ai";
|
|
62
|
-
import { compilePlannerPrompt } from "@contractspec/lib.surface-runtime/runtime/planner-prompt";
|
|
63
|
-
|
|
64
|
-
// src/core/contracts-context.ts
|
|
65
|
-
function buildContractsContextPrompt(config) {
|
|
66
|
-
const parts = [];
|
|
67
|
-
if (!config.agentSpecs?.length && !config.dataViewSpecs?.length && !config.formSpecs?.length && !config.presentationSpecs?.length && !config.operationRefs?.length) {
|
|
68
|
-
return "";
|
|
69
|
-
}
|
|
70
|
-
parts.push(`
|
|
71
|
-
|
|
72
|
-
## Available resources`);
|
|
73
|
-
if (config.agentSpecs?.length) {
|
|
74
|
-
parts.push(`
|
|
75
|
-
### Agent tools`);
|
|
76
|
-
for (const agent of config.agentSpecs) {
|
|
77
|
-
const toolNames = agent.tools?.map((t) => t.name).join(", ") ?? "none";
|
|
78
|
-
parts.push(`- **${agent.key}**: tools: ${toolNames}`);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
if (config.dataViewSpecs?.length) {
|
|
82
|
-
parts.push(`
|
|
83
|
-
### Data views`);
|
|
84
|
-
for (const dv of config.dataViewSpecs) {
|
|
85
|
-
parts.push(`- **${dv.key}**: ${dv.meta.title ?? dv.key}`);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
if (config.formSpecs?.length) {
|
|
89
|
-
parts.push(`
|
|
90
|
-
### Forms`);
|
|
91
|
-
for (const form of config.formSpecs) {
|
|
92
|
-
parts.push(`- **${form.key}**: ${form.meta.title ?? form.key}`);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
if (config.presentationSpecs?.length) {
|
|
96
|
-
parts.push(`
|
|
97
|
-
### Presentations`);
|
|
98
|
-
for (const pres of config.presentationSpecs) {
|
|
99
|
-
parts.push(`- **${pres.key}**: ${pres.meta.title ?? pres.key} (targets: ${pres.targets?.join(", ") ?? "react"})`);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
if (config.operationRefs?.length) {
|
|
103
|
-
parts.push(`
|
|
104
|
-
### Operations`);
|
|
105
|
-
for (const op of config.operationRefs) {
|
|
106
|
-
parts.push(`- **${op.key}@${op.version}**`);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
parts.push(`
|
|
110
|
-
Use the available tools to invoke operations, query data views, or propose surface changes when appropriate.`);
|
|
111
|
-
return parts.join(`
|
|
112
|
-
`);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// src/core/conversation-store.ts
|
|
116
|
-
function generateId(prefix) {
|
|
117
|
-
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
class InMemoryConversationStore {
|
|
121
|
-
conversations = new Map;
|
|
122
|
-
async get(conversationId) {
|
|
123
|
-
return this.conversations.get(conversationId) ?? null;
|
|
124
|
-
}
|
|
125
|
-
async create(conversation) {
|
|
126
|
-
const now = new Date;
|
|
127
|
-
const fullConversation = {
|
|
128
|
-
...conversation,
|
|
129
|
-
id: generateId("conv"),
|
|
130
|
-
createdAt: now,
|
|
131
|
-
updatedAt: now
|
|
132
|
-
};
|
|
133
|
-
this.conversations.set(fullConversation.id, fullConversation);
|
|
134
|
-
return fullConversation;
|
|
135
|
-
}
|
|
136
|
-
async update(conversationId, updates) {
|
|
137
|
-
const conversation = this.conversations.get(conversationId);
|
|
138
|
-
if (!conversation)
|
|
139
|
-
return null;
|
|
140
|
-
const updated = {
|
|
141
|
-
...conversation,
|
|
142
|
-
...updates,
|
|
143
|
-
updatedAt: new Date
|
|
144
|
-
};
|
|
145
|
-
this.conversations.set(conversationId, updated);
|
|
146
|
-
return updated;
|
|
147
|
-
}
|
|
148
|
-
async appendMessage(conversationId, message) {
|
|
149
|
-
const conversation = this.conversations.get(conversationId);
|
|
150
|
-
if (!conversation) {
|
|
151
|
-
throw new Error(`Conversation ${conversationId} not found`);
|
|
152
|
-
}
|
|
153
|
-
const now = new Date;
|
|
154
|
-
const fullMessage = {
|
|
155
|
-
...message,
|
|
156
|
-
id: generateId("msg"),
|
|
157
|
-
conversationId,
|
|
158
|
-
createdAt: now,
|
|
159
|
-
updatedAt: now
|
|
160
|
-
};
|
|
161
|
-
conversation.messages.push(fullMessage);
|
|
162
|
-
conversation.updatedAt = now;
|
|
163
|
-
return fullMessage;
|
|
164
|
-
}
|
|
165
|
-
async updateMessage(conversationId, messageId, updates) {
|
|
166
|
-
const conversation = this.conversations.get(conversationId);
|
|
167
|
-
if (!conversation)
|
|
168
|
-
return null;
|
|
169
|
-
const messageIndex = conversation.messages.findIndex((m) => m.id === messageId);
|
|
170
|
-
if (messageIndex === -1)
|
|
171
|
-
return null;
|
|
172
|
-
const message = conversation.messages[messageIndex];
|
|
173
|
-
if (!message)
|
|
174
|
-
return null;
|
|
175
|
-
const updated = {
|
|
176
|
-
...message,
|
|
177
|
-
...updates,
|
|
178
|
-
updatedAt: new Date
|
|
179
|
-
};
|
|
180
|
-
conversation.messages[messageIndex] = updated;
|
|
181
|
-
conversation.updatedAt = new Date;
|
|
182
|
-
return updated;
|
|
183
|
-
}
|
|
184
|
-
async delete(conversationId) {
|
|
185
|
-
return this.conversations.delete(conversationId);
|
|
186
|
-
}
|
|
187
|
-
async list(options) {
|
|
188
|
-
let results = Array.from(this.conversations.values());
|
|
189
|
-
if (options?.status) {
|
|
190
|
-
results = results.filter((c) => c.status === options.status);
|
|
191
|
-
}
|
|
192
|
-
if (options?.projectId) {
|
|
193
|
-
results = results.filter((c) => c.projectId === options.projectId);
|
|
194
|
-
}
|
|
195
|
-
if (options?.tags && options.tags.length > 0) {
|
|
196
|
-
const tagSet = new Set(options.tags);
|
|
197
|
-
results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
|
|
198
|
-
}
|
|
199
|
-
results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
200
|
-
const offset = options?.offset ?? 0;
|
|
201
|
-
const limit = options?.limit ?? 100;
|
|
202
|
-
return results.slice(offset, offset + limit);
|
|
203
|
-
}
|
|
204
|
-
async fork(conversationId, upToMessageId) {
|
|
205
|
-
const source = this.conversations.get(conversationId);
|
|
206
|
-
if (!source) {
|
|
207
|
-
throw new Error(`Conversation ${conversationId} not found`);
|
|
208
|
-
}
|
|
209
|
-
let messagesToCopy = source.messages;
|
|
210
|
-
if (upToMessageId) {
|
|
211
|
-
const idx = source.messages.findIndex((m) => m.id === upToMessageId);
|
|
212
|
-
if (idx === -1) {
|
|
213
|
-
throw new Error(`Message ${upToMessageId} not found`);
|
|
214
|
-
}
|
|
215
|
-
messagesToCopy = source.messages.slice(0, idx + 1);
|
|
216
|
-
}
|
|
217
|
-
const now = new Date;
|
|
218
|
-
const forkedMessages = messagesToCopy.map((m) => ({
|
|
219
|
-
...m,
|
|
220
|
-
id: generateId("msg"),
|
|
221
|
-
conversationId: "",
|
|
222
|
-
createdAt: new Date(m.createdAt),
|
|
223
|
-
updatedAt: new Date(m.updatedAt)
|
|
224
|
-
}));
|
|
225
|
-
const forked = {
|
|
226
|
-
...source,
|
|
227
|
-
id: generateId("conv"),
|
|
228
|
-
title: source.title ? `${source.title} (fork)` : undefined,
|
|
229
|
-
forkedFromId: source.id,
|
|
230
|
-
createdAt: now,
|
|
231
|
-
updatedAt: now,
|
|
232
|
-
messages: forkedMessages
|
|
233
|
-
};
|
|
234
|
-
for (const m of forked.messages) {
|
|
235
|
-
m.conversationId = forked.id;
|
|
236
|
-
}
|
|
237
|
-
this.conversations.set(forked.id, forked);
|
|
238
|
-
return forked;
|
|
239
|
-
}
|
|
240
|
-
async truncateAfter(conversationId, messageId) {
|
|
241
|
-
const conv = this.conversations.get(conversationId);
|
|
242
|
-
if (!conv)
|
|
243
|
-
return null;
|
|
244
|
-
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
245
|
-
if (idx === -1)
|
|
246
|
-
return null;
|
|
247
|
-
conv.messages = conv.messages.slice(0, idx + 1);
|
|
248
|
-
conv.updatedAt = new Date;
|
|
249
|
-
return conv;
|
|
250
|
-
}
|
|
251
|
-
async search(query, limit = 20) {
|
|
252
|
-
const lowerQuery = query.toLowerCase();
|
|
253
|
-
const results = [];
|
|
254
|
-
for (const conversation of this.conversations.values()) {
|
|
255
|
-
if (conversation.title?.toLowerCase().includes(lowerQuery)) {
|
|
256
|
-
results.push(conversation);
|
|
257
|
-
continue;
|
|
258
|
-
}
|
|
259
|
-
const hasMatch = conversation.messages.some((m) => m.content.toLowerCase().includes(lowerQuery));
|
|
260
|
-
if (hasMatch) {
|
|
261
|
-
results.push(conversation);
|
|
262
|
-
}
|
|
263
|
-
if (results.length >= limit)
|
|
264
|
-
break;
|
|
265
|
-
}
|
|
266
|
-
return results;
|
|
267
|
-
}
|
|
268
|
-
clear() {
|
|
269
|
-
this.conversations.clear();
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
function createInMemoryConversationStore() {
|
|
273
|
-
return new InMemoryConversationStore;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// src/core/surface-planner-tools.ts
|
|
277
|
-
import { buildSurfacePatchProposal } from "@contractspec/lib.surface-runtime/runtime/planner-tools";
|
|
278
|
-
import {
|
|
279
|
-
validatePatchProposal
|
|
280
|
-
} from "@contractspec/lib.surface-runtime/spec/validate-surface-patch";
|
|
281
|
-
import { tool as tool2 } from "ai";
|
|
282
|
-
import { z as z2 } from "zod";
|
|
283
|
-
var VALID_OPS = [
|
|
284
|
-
"insert-node",
|
|
285
|
-
"replace-node",
|
|
286
|
-
"remove-node",
|
|
287
|
-
"move-node",
|
|
288
|
-
"resize-panel",
|
|
289
|
-
"set-layout",
|
|
290
|
-
"reveal-field",
|
|
291
|
-
"hide-field",
|
|
292
|
-
"promote-action",
|
|
293
|
-
"set-focus"
|
|
294
|
-
];
|
|
295
|
-
var DEFAULT_NODE_KINDS = [
|
|
296
|
-
"entity-section",
|
|
297
|
-
"entity-card",
|
|
298
|
-
"data-view",
|
|
299
|
-
"assistant-panel",
|
|
300
|
-
"chat-thread",
|
|
301
|
-
"action-bar",
|
|
302
|
-
"timeline",
|
|
303
|
-
"table",
|
|
304
|
-
"rich-doc",
|
|
305
|
-
"form",
|
|
306
|
-
"chart",
|
|
307
|
-
"custom-widget"
|
|
308
|
-
];
|
|
309
|
-
function collectSlotIdsFromRegion(node) {
|
|
310
|
-
const ids = [];
|
|
311
|
-
if (node.type === "slot") {
|
|
312
|
-
ids.push(node.slotId);
|
|
313
|
-
}
|
|
314
|
-
if (node.type === "panel-group" || node.type === "stack") {
|
|
315
|
-
for (const child of node.children) {
|
|
316
|
-
ids.push(...collectSlotIdsFromRegion(child));
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
if (node.type === "tabs") {
|
|
320
|
-
for (const tab of node.tabs) {
|
|
321
|
-
ids.push(...collectSlotIdsFromRegion(tab.child));
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (node.type === "floating") {
|
|
325
|
-
ids.push(node.anchorSlotId);
|
|
326
|
-
ids.push(...collectSlotIdsFromRegion(node.child));
|
|
327
|
-
}
|
|
328
|
-
return ids;
|
|
329
|
-
}
|
|
330
|
-
function deriveConstraints(plan) {
|
|
331
|
-
const slotIds = collectSlotIdsFromRegion(plan.layoutRoot);
|
|
332
|
-
const uniqueSlots = [...new Set(slotIds)];
|
|
333
|
-
return {
|
|
334
|
-
allowedOps: VALID_OPS,
|
|
335
|
-
allowedSlots: uniqueSlots.length > 0 ? uniqueSlots : ["assistant", "primary"],
|
|
336
|
-
allowedNodeKinds: DEFAULT_NODE_KINDS
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
var ProposePatchInputSchema = z2.object({
|
|
340
|
-
proposalId: z2.string().describe("Unique proposal identifier"),
|
|
341
|
-
ops: z2.array(z2.object({
|
|
342
|
-
op: z2.enum([
|
|
343
|
-
"insert-node",
|
|
344
|
-
"replace-node",
|
|
345
|
-
"remove-node",
|
|
346
|
-
"move-node",
|
|
347
|
-
"resize-panel",
|
|
348
|
-
"set-layout",
|
|
349
|
-
"reveal-field",
|
|
350
|
-
"hide-field",
|
|
351
|
-
"promote-action",
|
|
352
|
-
"set-focus"
|
|
353
|
-
]),
|
|
354
|
-
slotId: z2.string().optional(),
|
|
355
|
-
nodeId: z2.string().optional(),
|
|
356
|
-
toSlotId: z2.string().optional(),
|
|
357
|
-
index: z2.number().optional(),
|
|
358
|
-
node: z2.object({
|
|
359
|
-
nodeId: z2.string(),
|
|
360
|
-
kind: z2.string(),
|
|
361
|
-
title: z2.string().optional(),
|
|
362
|
-
props: z2.record(z2.string(), z2.unknown()).optional(),
|
|
363
|
-
children: z2.array(z2.unknown()).optional()
|
|
364
|
-
}).optional(),
|
|
365
|
-
persistKey: z2.string().optional(),
|
|
366
|
-
sizes: z2.array(z2.number()).optional(),
|
|
367
|
-
layoutId: z2.string().optional(),
|
|
368
|
-
fieldId: z2.string().optional(),
|
|
369
|
-
actionId: z2.string().optional(),
|
|
370
|
-
placement: z2.enum(["header", "inline", "context", "assistant"]).optional(),
|
|
371
|
-
targetId: z2.string().optional()
|
|
372
|
-
}))
|
|
373
|
-
});
|
|
374
|
-
function createSurfacePlannerTools(config) {
|
|
375
|
-
const { plan, constraints, onPatchProposal } = config;
|
|
376
|
-
const resolvedConstraints = constraints ?? deriveConstraints(plan);
|
|
377
|
-
const proposePatchTool = tool2({
|
|
378
|
-
description: "Propose surface patches (layout changes, node insertions, etc.) for user approval. " + "Only use allowed ops, slots, and node kinds from the planner context.",
|
|
379
|
-
inputSchema: ProposePatchInputSchema,
|
|
380
|
-
execute: async (input) => {
|
|
381
|
-
const ops = input.ops;
|
|
382
|
-
try {
|
|
383
|
-
validatePatchProposal(ops, resolvedConstraints);
|
|
384
|
-
const proposal = buildSurfacePatchProposal(input.proposalId, ops);
|
|
385
|
-
onPatchProposal?.(proposal);
|
|
386
|
-
return {
|
|
387
|
-
success: true,
|
|
388
|
-
proposalId: proposal.proposalId,
|
|
389
|
-
opsCount: proposal.ops.length,
|
|
390
|
-
message: "Patch proposal validated; awaiting user approval"
|
|
391
|
-
};
|
|
392
|
-
} catch (err) {
|
|
393
|
-
return {
|
|
394
|
-
success: false,
|
|
395
|
-
error: err instanceof Error ? err.message : String(err),
|
|
396
|
-
proposalId: input.proposalId
|
|
397
|
-
};
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
});
|
|
401
|
-
return {
|
|
402
|
-
"propose-patch": proposePatchTool
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
function buildPlannerPromptInput(plan) {
|
|
406
|
-
const constraints = deriveConstraints(plan);
|
|
407
|
-
return {
|
|
408
|
-
bundleMeta: {
|
|
409
|
-
key: plan.bundleKey,
|
|
410
|
-
version: "0.0.0",
|
|
411
|
-
title: plan.bundleKey
|
|
412
|
-
},
|
|
413
|
-
surfaceId: plan.surfaceId,
|
|
414
|
-
allowedPatchOps: constraints.allowedOps,
|
|
415
|
-
allowedSlots: [...constraints.allowedSlots],
|
|
416
|
-
allowedNodeKinds: [...constraints.allowedNodeKinds],
|
|
417
|
-
actions: plan.actions.map((a) => ({
|
|
418
|
-
actionId: a.actionId,
|
|
419
|
-
title: a.title
|
|
420
|
-
})),
|
|
421
|
-
preferences: {
|
|
422
|
-
guidance: "hints",
|
|
423
|
-
density: "standard",
|
|
424
|
-
dataDepth: "detailed",
|
|
425
|
-
control: "standard",
|
|
426
|
-
media: "text",
|
|
427
|
-
pace: "balanced",
|
|
428
|
-
narrative: "top-down"
|
|
429
|
-
}
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// src/core/thinking-levels.ts
|
|
434
|
-
var THINKING_LEVEL_LABELS = {
|
|
435
|
-
instant: "Instant",
|
|
436
|
-
thinking: "Thinking",
|
|
437
|
-
extra_thinking: "Extra Thinking",
|
|
438
|
-
max: "Max"
|
|
439
|
-
};
|
|
440
|
-
var THINKING_LEVEL_DESCRIPTIONS = {
|
|
441
|
-
instant: "Fast responses, minimal reasoning",
|
|
442
|
-
thinking: "Standard reasoning depth",
|
|
443
|
-
extra_thinking: "More thorough reasoning",
|
|
444
|
-
max: "Maximum reasoning depth"
|
|
445
|
-
};
|
|
446
|
-
function getProviderOptions(level, providerName) {
|
|
447
|
-
if (!level || level === "instant") {
|
|
448
|
-
return {};
|
|
449
|
-
}
|
|
450
|
-
switch (providerName) {
|
|
451
|
-
case "anthropic": {
|
|
452
|
-
const budgetMap = {
|
|
453
|
-
thinking: 8000,
|
|
454
|
-
extra_thinking: 16000,
|
|
455
|
-
max: 32000
|
|
456
|
-
};
|
|
457
|
-
return {
|
|
458
|
-
anthropic: {
|
|
459
|
-
thinking: { type: "enabled", budgetTokens: budgetMap[level] }
|
|
460
|
-
}
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
case "openai": {
|
|
464
|
-
const effortMap = {
|
|
465
|
-
thinking: "low",
|
|
466
|
-
extra_thinking: "medium",
|
|
467
|
-
max: "high"
|
|
468
|
-
};
|
|
469
|
-
return {
|
|
470
|
-
openai: {
|
|
471
|
-
reasoningEffort: effortMap[level]
|
|
472
|
-
}
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
case "ollama":
|
|
476
|
-
case "mistral":
|
|
477
|
-
case "gemini":
|
|
478
|
-
return {};
|
|
479
|
-
default:
|
|
480
|
-
return {};
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
// src/core/workflow-tools.ts
|
|
485
|
-
import {
|
|
486
|
-
validateExtension,
|
|
487
|
-
WorkflowComposer
|
|
488
|
-
} from "@contractspec/lib.workflow-composer";
|
|
489
|
-
import { tool as tool3 } from "ai";
|
|
490
|
-
import { z as z3 } from "zod";
|
|
491
|
-
var StepTypeSchema = z3.enum(["human", "automation", "decision"]);
|
|
492
|
-
var StepActionSchema = z3.object({
|
|
493
|
-
operation: z3.object({
|
|
494
|
-
name: z3.string(),
|
|
495
|
-
version: z3.number()
|
|
496
|
-
}).optional(),
|
|
497
|
-
form: z3.object({
|
|
498
|
-
key: z3.string(),
|
|
499
|
-
version: z3.number()
|
|
500
|
-
}).optional()
|
|
501
|
-
}).optional();
|
|
502
|
-
var StepSchema = z3.object({
|
|
503
|
-
id: z3.string(),
|
|
504
|
-
type: StepTypeSchema,
|
|
505
|
-
label: z3.string(),
|
|
506
|
-
description: z3.string().optional(),
|
|
507
|
-
action: StepActionSchema
|
|
508
|
-
});
|
|
509
|
-
var StepInjectionSchema = z3.object({
|
|
510
|
-
after: z3.string().optional(),
|
|
511
|
-
before: z3.string().optional(),
|
|
512
|
-
inject: StepSchema,
|
|
513
|
-
transitionTo: z3.string().optional(),
|
|
514
|
-
transitionFrom: z3.string().optional(),
|
|
515
|
-
when: z3.string().optional()
|
|
516
|
-
});
|
|
517
|
-
var WorkflowExtensionInputSchema = z3.object({
|
|
518
|
-
workflow: z3.string(),
|
|
519
|
-
tenantId: z3.string().optional(),
|
|
520
|
-
role: z3.string().optional(),
|
|
521
|
-
priority: z3.number().optional(),
|
|
522
|
-
customSteps: z3.array(StepInjectionSchema).optional(),
|
|
523
|
-
hiddenSteps: z3.array(z3.string()).optional()
|
|
524
|
-
});
|
|
525
|
-
function createWorkflowTools(config) {
|
|
526
|
-
const { baseWorkflows, composer } = config;
|
|
527
|
-
const baseByKey = new Map(baseWorkflows.map((b) => [b.meta.key, b]));
|
|
528
|
-
const createWorkflowExtensionTool = tool3({
|
|
529
|
-
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.",
|
|
530
|
-
inputSchema: WorkflowExtensionInputSchema,
|
|
531
|
-
execute: async (input) => {
|
|
532
|
-
const extension = {
|
|
533
|
-
workflow: input.workflow,
|
|
534
|
-
tenantId: input.tenantId,
|
|
535
|
-
role: input.role,
|
|
536
|
-
priority: input.priority,
|
|
537
|
-
customSteps: input.customSteps,
|
|
538
|
-
hiddenSteps: input.hiddenSteps
|
|
539
|
-
};
|
|
540
|
-
const base = baseByKey.get(input.workflow);
|
|
541
|
-
if (!base) {
|
|
542
|
-
return {
|
|
543
|
-
success: false,
|
|
544
|
-
error: `Base workflow "${input.workflow}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
|
|
545
|
-
extension
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
try {
|
|
549
|
-
validateExtension(extension, base);
|
|
550
|
-
return {
|
|
551
|
-
success: true,
|
|
552
|
-
message: "Extension validated successfully",
|
|
553
|
-
extension
|
|
554
|
-
};
|
|
555
|
-
} catch (err) {
|
|
556
|
-
return {
|
|
557
|
-
success: false,
|
|
558
|
-
error: err instanceof Error ? err.message : String(err),
|
|
559
|
-
extension
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
});
|
|
564
|
-
const composeWorkflowInputSchema = z3.object({
|
|
565
|
-
workflowKey: z3.string().describe("Base workflow meta.key"),
|
|
566
|
-
tenantId: z3.string().optional(),
|
|
567
|
-
role: z3.string().optional(),
|
|
568
|
-
extensions: z3.array(WorkflowExtensionInputSchema).optional().describe("Extensions to register before composing")
|
|
569
|
-
});
|
|
570
|
-
const composeWorkflowTool = tool3({
|
|
571
|
-
description: "Compose a workflow by applying registered extensions to a base workflow. Returns the composed WorkflowSpec.",
|
|
572
|
-
inputSchema: composeWorkflowInputSchema,
|
|
573
|
-
execute: async (input) => {
|
|
574
|
-
const base = baseByKey.get(input.workflowKey);
|
|
575
|
-
if (!base) {
|
|
576
|
-
return {
|
|
577
|
-
success: false,
|
|
578
|
-
error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
const comp = composer ?? new WorkflowComposer;
|
|
582
|
-
if (input.extensions?.length) {
|
|
583
|
-
for (const ext of input.extensions) {
|
|
584
|
-
comp.register({
|
|
585
|
-
workflow: ext.workflow,
|
|
586
|
-
tenantId: ext.tenantId,
|
|
587
|
-
role: ext.role,
|
|
588
|
-
priority: ext.priority,
|
|
589
|
-
customSteps: ext.customSteps,
|
|
590
|
-
hiddenSteps: ext.hiddenSteps
|
|
591
|
-
});
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
try {
|
|
595
|
-
const composed = comp.compose({
|
|
596
|
-
base,
|
|
597
|
-
tenantId: input.tenantId,
|
|
598
|
-
role: input.role
|
|
599
|
-
});
|
|
600
|
-
return {
|
|
601
|
-
success: true,
|
|
602
|
-
workflow: composed,
|
|
603
|
-
meta: composed.meta,
|
|
604
|
-
stepIds: composed.definition.steps.map((s) => s.id)
|
|
605
|
-
};
|
|
606
|
-
} catch (err) {
|
|
607
|
-
return {
|
|
608
|
-
success: false,
|
|
609
|
-
error: err instanceof Error ? err.message : String(err)
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
const generateWorkflowSpecCodeInputSchema = z3.object({
|
|
615
|
-
workflowKey: z3.string().describe("Workflow meta.key"),
|
|
616
|
-
composedSteps: z3.array(z3.object({
|
|
617
|
-
id: z3.string(),
|
|
618
|
-
type: z3.enum(["human", "automation", "decision"]),
|
|
619
|
-
label: z3.string(),
|
|
620
|
-
description: z3.string().optional()
|
|
621
|
-
})).optional().describe("Steps to include; if omitted, uses the base workflow")
|
|
622
|
-
});
|
|
623
|
-
const generateWorkflowSpecCodeTool = tool3({
|
|
624
|
-
description: "Generate TypeScript code for a workflow spec. Use after composing a workflow to output the spec as code the user can save.",
|
|
625
|
-
inputSchema: generateWorkflowSpecCodeInputSchema,
|
|
626
|
-
execute: async (input) => {
|
|
627
|
-
const base = baseByKey.get(input.workflowKey);
|
|
628
|
-
if (!base) {
|
|
629
|
-
return {
|
|
630
|
-
success: false,
|
|
631
|
-
error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
|
|
632
|
-
code: null
|
|
633
|
-
};
|
|
634
|
-
}
|
|
635
|
-
const steps = input.composedSteps ?? base.definition.steps;
|
|
636
|
-
const specVarName = toPascalCase((base.meta.key.split(".").pop() ?? "Workflow") + "") + "Workflow";
|
|
637
|
-
const stepsCode = steps.map((s) => ` {
|
|
638
|
-
id: '${s.id}',
|
|
639
|
-
type: '${s.type}',
|
|
640
|
-
label: '${escapeString(s.label)}',${s.description ? `
|
|
641
|
-
description: '${escapeString(s.description)}',` : ""}
|
|
1
|
+
var bX=((X)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(X,{get:(Z,$)=>(typeof require<"u"?require:Z)[$]}):X)(function(X){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+X+'" is not supported')});function CX(X){return{async generate({prompt:Z,signal:$}){let j=await X.generate({prompt:Z,signal:$});return{text:j.text,toolCalls:j.toolCalls,toolResults:j.toolResults,usage:j.usage}}}}import{tool as g}from"ai";import{z as p}from"zod";function c(X){return p.object({}).passthrough()}function b(X,Z){let $={};for(let j of X){let H=Z?.[j.name],V=c(j.schema);$[j.name]=g({description:j.description??j.name,inputSchema:V,execute:async(G)=>{if(!H)return{status:"unimplemented",message:"Wire handler in host",toolName:j.name};try{let J=await Promise.resolve(H(G));return typeof J==="string"?J:J}catch(J){return{status:"error",error:J instanceof Error?J.message:String(J),toolName:j.name}}}})}return $}import{generateText as VX,streamText as GX}from"ai";import{compilePlannerPrompt as JX}from"@contractspec/lib.surface-runtime/runtime/planner-prompt";function y(X){let Z=[];if(!X.agentSpecs?.length&&!X.dataViewSpecs?.length&&!X.formSpecs?.length&&!X.presentationSpecs?.length&&!X.operationRefs?.length)return"";if(Z.push(`
|
|
2
|
+
|
|
3
|
+
## Available resources`),X.agentSpecs?.length){Z.push(`
|
|
4
|
+
### Agent tools`);for(let $ of X.agentSpecs){let j=$.tools?.map((H)=>H.name).join(", ")??"none";Z.push(`- **${$.key}**: tools: ${j}`)}}if(X.dataViewSpecs?.length){Z.push(`
|
|
5
|
+
### Data views`);for(let $ of X.dataViewSpecs)Z.push(`- **${$.key}**: ${$.meta.title??$.key}`)}if(X.formSpecs?.length){Z.push(`
|
|
6
|
+
### Forms`);for(let $ of X.formSpecs)Z.push(`- **${$.key}**: ${$.meta.title??$.key}`)}if(X.presentationSpecs?.length){Z.push(`
|
|
7
|
+
### Presentations`);for(let $ of X.presentationSpecs)Z.push(`- **${$.key}**: ${$.meta.title??$.key} (targets: ${$.targets?.join(", ")??"react"})`)}if(X.operationRefs?.length){Z.push(`
|
|
8
|
+
### Operations`);for(let $ of X.operationRefs)Z.push(`- **${$.key}@${$.version}**`)}return Z.push(`
|
|
9
|
+
Use the available tools to invoke operations, query data views, or propose surface changes when appropriate.`),Z.join(`
|
|
10
|
+
`)}function z(X){return`${X}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}class P{conversations=new Map;async get(X){return this.conversations.get(X)??null}async create(X){let Z=new Date,$={...X,id:z("conv"),createdAt:Z,updatedAt:Z};return this.conversations.set($.id,$),$}async update(X,Z){let $=this.conversations.get(X);if(!$)return null;let j={...$,...Z,updatedAt:new Date};return this.conversations.set(X,j),j}async appendMessage(X,Z){let $=this.conversations.get(X);if(!$)throw Error(`Conversation ${X} not found`);let j=new Date,H={...Z,id:z("msg"),conversationId:X,createdAt:j,updatedAt:j};return $.messages.push(H),$.updatedAt=j,H}async updateMessage(X,Z,$){let j=this.conversations.get(X);if(!j)return null;let H=j.messages.findIndex((J)=>J.id===Z);if(H===-1)return null;let V=j.messages[H];if(!V)return null;let G={...V,...$,updatedAt:new Date};return j.messages[H]=G,j.updatedAt=new Date,G}async delete(X){return this.conversations.delete(X)}async list(X){let Z=Array.from(this.conversations.values());if(X?.status)Z=Z.filter((H)=>H.status===X.status);if(X?.projectId)Z=Z.filter((H)=>H.projectId===X.projectId);if(X?.tags&&X.tags.length>0){let H=new Set(X.tags);Z=Z.filter((V)=>V.tags&&V.tags.some((G)=>H.has(G)))}Z.sort((H,V)=>V.updatedAt.getTime()-H.updatedAt.getTime());let $=X?.offset??0,j=X?.limit??100;return Z.slice($,$+j)}async fork(X,Z){let $=this.conversations.get(X);if(!$)throw Error(`Conversation ${X} not found`);let j=$.messages;if(Z){let J=$.messages.findIndex((Q)=>Q.id===Z);if(J===-1)throw Error(`Message ${Z} not found`);j=$.messages.slice(0,J+1)}let H=new Date,V=j.map((J)=>({...J,id:z("msg"),conversationId:"",createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),G={...$,id:z("conv"),title:$.title?`${$.title} (fork)`:void 0,forkedFromId:$.id,createdAt:H,updatedAt:H,messages:V};for(let J of G.messages)J.conversationId=G.id;return this.conversations.set(G.id,G),G}async truncateAfter(X,Z){let $=this.conversations.get(X);if(!$)return null;let j=$.messages.findIndex((H)=>H.id===Z);if(j===-1)return null;return $.messages=$.messages.slice(0,j+1),$.updatedAt=new Date,$}async search(X,Z=20){let $=X.toLowerCase(),j=[];for(let H of this.conversations.values()){if(H.title?.toLowerCase().includes($)){j.push(H);continue}if(H.messages.some((G)=>G.content.toLowerCase().includes($)))j.push(H);if(j.length>=Z)break}return j}clear(){this.conversations.clear()}}function dX(){return new P}import{buildSurfacePatchProposal as i}from"@contractspec/lib.surface-runtime/runtime/planner-tools";import{validatePatchProposal as r}from"@contractspec/lib.surface-runtime/spec/validate-surface-patch";import{tool as a}from"ai";import{z as F}from"zod";var t=["insert-node","replace-node","remove-node","move-node","resize-panel","set-layout","reveal-field","hide-field","promote-action","set-focus"],n=["entity-section","entity-card","data-view","assistant-panel","chat-thread","action-bar","timeline","table","rich-doc","form","chart","custom-widget"];function k(X){let Z=[];if(X.type==="slot")Z.push(X.slotId);if(X.type==="panel-group"||X.type==="stack")for(let $ of X.children)Z.push(...k($));if(X.type==="tabs")for(let $ of X.tabs)Z.push(...k($.child));if(X.type==="floating")Z.push(X.anchorSlotId),Z.push(...k(X.child));return Z}function C(X){let Z=k(X.layoutRoot),$=[...new Set(Z)];return{allowedOps:t,allowedSlots:$.length>0?$:["assistant","primary"],allowedNodeKinds:n}}var s=F.object({proposalId:F.string().describe("Unique proposal identifier"),ops:F.array(F.object({op:F.enum(["insert-node","replace-node","remove-node","move-node","resize-panel","set-layout","reveal-field","hide-field","promote-action","set-focus"]),slotId:F.string().optional(),nodeId:F.string().optional(),toSlotId:F.string().optional(),index:F.number().optional(),node:F.object({nodeId:F.string(),kind:F.string(),title:F.string().optional(),props:F.record(F.string(),F.unknown()).optional(),children:F.array(F.unknown()).optional()}).optional(),persistKey:F.string().optional(),sizes:F.array(F.number()).optional(),layoutId:F.string().optional(),fieldId:F.string().optional(),actionId:F.string().optional(),placement:F.enum(["header","inline","context","assistant"]).optional(),targetId:F.string().optional()}))});function T(X){let{plan:Z,constraints:$,onPatchProposal:j}=X,H=$??C(Z);return{"propose-patch":a({description:"Propose surface patches (layout changes, node insertions, etc.) for user approval. Only use allowed ops, slots, and node kinds from the planner context.",inputSchema:s,execute:async(G)=>{let J=G.ops;try{r(J,H);let Q=i(G.proposalId,J);return j?.(Q),{success:!0,proposalId:Q.proposalId,opsCount:Q.ops.length,message:"Patch proposal validated; awaiting user approval"}}catch(Q){return{success:!1,error:Q instanceof Error?Q.message:String(Q),proposalId:G.proposalId}}}})}}function I(X){let Z=C(X);return{bundleMeta:{key:X.bundleKey,version:"0.0.0",title:X.bundleKey},surfaceId:X.surfaceId,allowedPatchOps:Z.allowedOps,allowedSlots:[...Z.allowedSlots],allowedNodeKinds:[...Z.allowedNodeKinds],actions:X.actions.map(($)=>({actionId:$.actionId,title:$.title})),preferences:{guidance:"hints",density:"standard",dataDepth:"detailed",control:"standard",media:"text",pace:"balanced",narrative:"top-down"}}}var rX={instant:"Instant",thinking:"Thinking",extra_thinking:"Extra Thinking",max:"Max"},aX={instant:"Fast responses, minimal reasoning",thinking:"Standard reasoning depth",extra_thinking:"More thorough reasoning",max:"Maximum reasoning depth"};function A(X,Z){if(!X||X==="instant")return{};switch(Z){case"anthropic":return{anthropic:{thinking:{type:"enabled",budgetTokens:{thinking:8000,extra_thinking:16000,max:32000}[X]}}};case"openai":return{openai:{reasoningEffort:{thinking:"low",extra_thinking:"medium",max:"high"}[X]}};case"ollama":case"mistral":case"gemini":return{};default:return{}}}import{validateExtension as e,WorkflowComposer as o}from"@contractspec/lib.workflow-composer";import{tool as x}from"ai";import{z as Y}from"zod";var XX=Y.enum(["human","automation","decision"]),ZX=Y.object({operation:Y.object({name:Y.string(),version:Y.number()}).optional(),form:Y.object({key:Y.string(),version:Y.number()}).optional()}).optional(),$X=Y.object({id:Y.string(),type:XX,label:Y.string(),description:Y.string().optional(),action:ZX}),jX=Y.object({after:Y.string().optional(),before:Y.string().optional(),inject:$X,transitionTo:Y.string().optional(),transitionFrom:Y.string().optional(),when:Y.string().optional()}),f=Y.object({workflow:Y.string(),tenantId:Y.string().optional(),role:Y.string().optional(),priority:Y.number().optional(),customSteps:Y.array(jX).optional(),hiddenSteps:Y.array(Y.string()).optional()});function v(X){let{baseWorkflows:Z,composer:$}=X,j=new Map(Z.map((D)=>[D.meta.key,D])),H=x({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.",inputSchema:f,execute:async(D)=>{let B={workflow:D.workflow,tenantId:D.tenantId,role:D.role,priority:D.priority,customSteps:D.customSteps,hiddenSteps:D.hiddenSteps},_=j.get(D.workflow);if(!_)return{success:!1,error:`Base workflow "${D.workflow}" not found. Available: ${Array.from(j.keys()).join(", ")}`,extension:B};try{return e(B,_),{success:!0,message:"Extension validated successfully",extension:B}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U),extension:B}}}}),V=Y.object({workflowKey:Y.string().describe("Base workflow meta.key"),tenantId:Y.string().optional(),role:Y.string().optional(),extensions:Y.array(f).optional().describe("Extensions to register before composing")}),G=x({description:"Compose a workflow by applying registered extensions to a base workflow. Returns the composed WorkflowSpec.",inputSchema:V,execute:async(D)=>{let B=j.get(D.workflowKey);if(!B)return{success:!1,error:`Base workflow "${D.workflowKey}" not found. Available: ${Array.from(j.keys()).join(", ")}`};let _=$??new o;if(D.extensions?.length)for(let U of D.extensions)_.register({workflow:U.workflow,tenantId:U.tenantId,role:U.role,priority:U.priority,customSteps:U.customSteps,hiddenSteps:U.hiddenSteps});try{let U=_.compose({base:B,tenantId:D.tenantId,role:D.role});return{success:!0,workflow:U,meta:U.meta,stepIds:U.definition.steps.map((q)=>q.id)}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}}),J=Y.object({workflowKey:Y.string().describe("Workflow meta.key"),composedSteps:Y.array(Y.object({id:Y.string(),type:Y.enum(["human","automation","decision"]),label:Y.string(),description:Y.string().optional()})).optional().describe("Steps to include; if omitted, uses the base workflow")}),Q=x({description:"Generate TypeScript code for a workflow spec. Use after composing a workflow to output the spec as code the user can save.",inputSchema:J,execute:async(D)=>{let B=j.get(D.workflowKey);if(!B)return{success:!1,error:`Base workflow "${D.workflowKey}" not found. Available: ${Array.from(j.keys()).join(", ")}`,code:null};let _=D.composedSteps??B.definition.steps,U=HX((B.meta.key.split(".").pop()??"Workflow")+"")+"Workflow",q=_.map((N)=>` {
|
|
11
|
+
id: '${N.id}',
|
|
12
|
+
type: '${N.type}',
|
|
13
|
+
label: '${w(N.label)}',${N.description?`
|
|
14
|
+
description: '${w(N.description)}',`:""}
|
|
642
15
|
}`).join(`,
|
|
643
|
-
`);
|
|
644
|
-
const meta = base.meta;
|
|
645
|
-
const transitionsJson = JSON.stringify(base.definition.transitions, null, 6);
|
|
646
|
-
const code = `import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow';
|
|
16
|
+
`),K=B.meta,E=JSON.stringify(B.definition.transitions,null,6);return{success:!0,code:`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
647
17
|
|
|
648
18
|
/**
|
|
649
|
-
* Workflow: ${
|
|
19
|
+
* Workflow: ${B.meta.key}
|
|
650
20
|
* Generated via AI chat workflow tools.
|
|
651
21
|
*/
|
|
652
|
-
export const ${
|
|
22
|
+
export const ${U}: WorkflowSpec = {
|
|
653
23
|
meta: {
|
|
654
|
-
key: '${
|
|
655
|
-
version: '${String(
|
|
656
|
-
title: '${
|
|
657
|
-
description: '${
|
|
24
|
+
key: '${B.meta.key}',
|
|
25
|
+
version: '${String(B.meta.version)}',
|
|
26
|
+
title: '${w(K.title??B.meta.key)}',
|
|
27
|
+
description: '${w(K.description??"")}',
|
|
658
28
|
},
|
|
659
29
|
definition: {
|
|
660
|
-
entryStepId: '${
|
|
30
|
+
entryStepId: '${B.definition.entryStepId??B.definition.steps[0]?.id??""}',
|
|
661
31
|
steps: [
|
|
662
|
-
${
|
|
32
|
+
${q}
|
|
663
33
|
],
|
|
664
|
-
transitions: ${
|
|
34
|
+
transitions: ${E},
|
|
665
35
|
},
|
|
666
36
|
};
|
|
667
|
-
|
|
668
|
-
return {
|
|
669
|
-
success: true,
|
|
670
|
-
code,
|
|
671
|
-
workflowKey: input.workflowKey
|
|
672
|
-
};
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
return {
|
|
676
|
-
create_workflow_extension: createWorkflowExtensionTool,
|
|
677
|
-
compose_workflow: composeWorkflowTool,
|
|
678
|
-
generate_workflow_spec_code: generateWorkflowSpecCodeTool
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
function toPascalCase(value) {
|
|
682
|
-
return value.split(/[-_.]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
683
|
-
}
|
|
684
|
-
function escapeString(value) {
|
|
685
|
-
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
// src/core/chat-service.ts
|
|
689
|
-
var DEFAULT_SYSTEM_PROMPT = `You are ContractSpec AI, an expert coding assistant specialized in ContractSpec development.
|
|
37
|
+
`,workflowKey:D.workflowKey}}});return{create_workflow_extension:H,compose_workflow:G,generate_workflow_spec_code:Q}}function HX(X){return X.split(/[-_.]/).filter(Boolean).map((Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)).join("")}function w(X){return X.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}var YX=`You are ContractSpec AI, an expert coding assistant specialized in ContractSpec development.
|
|
690
38
|
|
|
691
39
|
Your capabilities:
|
|
692
40
|
- Help users create, modify, and understand ContractSpec specifications
|
|
@@ -699,957 +47,64 @@ Guidelines:
|
|
|
699
47
|
- Provide code examples when helpful
|
|
700
48
|
- Reference relevant ContractSpec concepts and patterns
|
|
701
49
|
- Ask clarifying questions when the user's intent is unclear
|
|
702
|
-
- When suggesting code changes, explain the rationale
|
|
703
|
-
var WORKFLOW_TOOLS_PROMPT = `
|
|
704
|
-
|
|
705
|
-
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.`;
|
|
50
|
+
- When suggesting code changes, explain the rationale`,QX=`
|
|
706
51
|
|
|
707
|
-
class
|
|
708
|
-
provider;
|
|
709
|
-
context;
|
|
710
|
-
store;
|
|
711
|
-
systemPrompt;
|
|
712
|
-
maxHistoryMessages;
|
|
713
|
-
onUsage;
|
|
714
|
-
tools;
|
|
715
|
-
thinkingLevel;
|
|
716
|
-
sendReasoning;
|
|
717
|
-
sendSources;
|
|
718
|
-
modelSelector;
|
|
719
|
-
constructor(config) {
|
|
720
|
-
this.provider = config.provider;
|
|
721
|
-
this.context = config.context;
|
|
722
|
-
this.store = config.store ?? new InMemoryConversationStore;
|
|
723
|
-
this.systemPrompt = this.buildSystemPrompt(config);
|
|
724
|
-
this.maxHistoryMessages = config.maxHistoryMessages ?? 20;
|
|
725
|
-
this.onUsage = config.onUsage;
|
|
726
|
-
this.tools = this.mergeTools(config);
|
|
727
|
-
this.thinkingLevel = config.thinkingLevel;
|
|
728
|
-
this.modelSelector = config.modelSelector;
|
|
729
|
-
this.sendReasoning = config.sendReasoning ?? (config.thinkingLevel != null && config.thinkingLevel !== "instant");
|
|
730
|
-
this.sendSources = config.sendSources ?? false;
|
|
731
|
-
}
|
|
732
|
-
buildSystemPrompt(config) {
|
|
733
|
-
let base = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
|
|
734
|
-
if (config.workflowToolsConfig?.baseWorkflows?.length) {
|
|
735
|
-
base += WORKFLOW_TOOLS_PROMPT;
|
|
736
|
-
}
|
|
737
|
-
const contractsPrompt = buildContractsContextPrompt(config.contractsContext ?? {});
|
|
738
|
-
if (contractsPrompt) {
|
|
739
|
-
base += contractsPrompt;
|
|
740
|
-
}
|
|
741
|
-
if (config.surfacePlanConfig?.plan) {
|
|
742
|
-
const plannerInput = buildPlannerPromptInput(config.surfacePlanConfig.plan);
|
|
743
|
-
base += `
|
|
52
|
+
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.`;class u{provider;context;store;systemPrompt;maxHistoryMessages;onUsage;tools;thinkingLevel;sendReasoning;sendSources;modelSelector;constructor(X){this.provider=X.provider,this.context=X.context,this.store=X.store??new P,this.systemPrompt=this.buildSystemPrompt(X),this.maxHistoryMessages=X.maxHistoryMessages??20,this.onUsage=X.onUsage,this.tools=this.mergeTools(X),this.thinkingLevel=X.thinkingLevel,this.modelSelector=X.modelSelector,this.sendReasoning=X.sendReasoning??(X.thinkingLevel!=null&&X.thinkingLevel!=="instant"),this.sendSources=X.sendSources??!1}buildSystemPrompt(X){let Z=X.systemPrompt??YX;if(X.workflowToolsConfig?.baseWorkflows?.length)Z+=QX;let $=y(X.contractsContext??{});if($)Z+=$;if(X.surfacePlanConfig?.plan){let j=I(X.surfacePlanConfig.plan);Z+=`
|
|
744
53
|
|
|
745
|
-
`
|
|
746
|
-
}
|
|
747
|
-
return base;
|
|
748
|
-
}
|
|
749
|
-
mergeTools(config) {
|
|
750
|
-
let merged = config.tools ?? {};
|
|
751
|
-
const wfConfig = config.workflowToolsConfig;
|
|
752
|
-
if (wfConfig?.baseWorkflows?.length) {
|
|
753
|
-
const workflowTools = createWorkflowTools({
|
|
754
|
-
baseWorkflows: wfConfig.baseWorkflows,
|
|
755
|
-
composer: wfConfig.composer
|
|
756
|
-
});
|
|
757
|
-
merged = { ...merged, ...workflowTools };
|
|
758
|
-
}
|
|
759
|
-
const contractsCtx = config.contractsContext;
|
|
760
|
-
if (contractsCtx?.agentSpecs?.length) {
|
|
761
|
-
const allTools = [];
|
|
762
|
-
for (const agent of contractsCtx.agentSpecs) {
|
|
763
|
-
if (agent.tools?.length)
|
|
764
|
-
allTools.push(...agent.tools);
|
|
765
|
-
}
|
|
766
|
-
if (allTools.length > 0) {
|
|
767
|
-
const agentTools = agentToolConfigsToToolSet(allTools);
|
|
768
|
-
merged = { ...merged, ...agentTools };
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
const surfaceConfig = config.surfacePlanConfig;
|
|
772
|
-
if (surfaceConfig?.plan) {
|
|
773
|
-
const plannerTools = createSurfacePlannerTools({
|
|
774
|
-
plan: surfaceConfig.plan,
|
|
775
|
-
onPatchProposal: surfaceConfig.onPatchProposal
|
|
776
|
-
});
|
|
777
|
-
merged = { ...merged, ...plannerTools };
|
|
778
|
-
}
|
|
779
|
-
if (config.mcpTools && Object.keys(config.mcpTools).length > 0) {
|
|
780
|
-
merged = { ...merged, ...config.mcpTools };
|
|
781
|
-
}
|
|
782
|
-
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
783
|
-
}
|
|
784
|
-
async resolveModel() {
|
|
785
|
-
if (this.modelSelector) {
|
|
786
|
-
const dimension = this.thinkingLevelToDimension(this.thinkingLevel);
|
|
787
|
-
const { model, selection } = await this.modelSelector.selectAndCreate({
|
|
788
|
-
taskDimension: dimension
|
|
789
|
-
});
|
|
790
|
-
return { model, providerName: selection.providerKey };
|
|
791
|
-
}
|
|
792
|
-
return {
|
|
793
|
-
model: this.provider.getModel(),
|
|
794
|
-
providerName: this.provider.name
|
|
795
|
-
};
|
|
796
|
-
}
|
|
797
|
-
thinkingLevelToDimension(level) {
|
|
798
|
-
if (!level || level === "instant")
|
|
799
|
-
return "latency";
|
|
800
|
-
return "reasoning";
|
|
801
|
-
}
|
|
802
|
-
async send(options) {
|
|
803
|
-
let conversation;
|
|
804
|
-
if (options.conversationId) {
|
|
805
|
-
const existing = await this.store.get(options.conversationId);
|
|
806
|
-
if (!existing) {
|
|
807
|
-
throw new Error(`Conversation ${options.conversationId} not found`);
|
|
808
|
-
}
|
|
809
|
-
conversation = existing;
|
|
810
|
-
} else {
|
|
811
|
-
conversation = await this.store.create({
|
|
812
|
-
status: "active",
|
|
813
|
-
provider: this.provider.name,
|
|
814
|
-
model: this.provider.model,
|
|
815
|
-
messages: [],
|
|
816
|
-
workspacePath: this.context?.workspacePath
|
|
817
|
-
});
|
|
818
|
-
}
|
|
819
|
-
if (!options.skipUserAppend) {
|
|
820
|
-
await this.store.appendMessage(conversation.id, {
|
|
821
|
-
role: "user",
|
|
822
|
-
content: options.content,
|
|
823
|
-
status: "completed",
|
|
824
|
-
attachments: options.attachments
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
conversation = await this.store.get(conversation.id) ?? conversation;
|
|
828
|
-
const messages = this.buildMessages(conversation, options);
|
|
829
|
-
const { model, providerName } = await this.resolveModel();
|
|
830
|
-
const providerOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
831
|
-
try {
|
|
832
|
-
const result = await generateText({
|
|
833
|
-
model,
|
|
834
|
-
messages,
|
|
835
|
-
system: this.systemPrompt,
|
|
836
|
-
tools: this.tools,
|
|
837
|
-
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
|
|
838
|
-
});
|
|
839
|
-
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
840
|
-
role: "assistant",
|
|
841
|
-
content: result.text,
|
|
842
|
-
status: "completed"
|
|
843
|
-
});
|
|
844
|
-
const updatedConversation = await this.store.get(conversation.id);
|
|
845
|
-
if (!updatedConversation) {
|
|
846
|
-
throw new Error("Conversation lost after update");
|
|
847
|
-
}
|
|
848
|
-
return {
|
|
849
|
-
message: assistantMessage,
|
|
850
|
-
conversation: updatedConversation
|
|
851
|
-
};
|
|
852
|
-
} catch (error) {
|
|
853
|
-
await this.store.appendMessage(conversation.id, {
|
|
854
|
-
role: "assistant",
|
|
855
|
-
content: "",
|
|
856
|
-
status: "error",
|
|
857
|
-
error: {
|
|
858
|
-
code: "generation_failed",
|
|
859
|
-
message: error instanceof Error ? error.message : String(error)
|
|
860
|
-
}
|
|
861
|
-
});
|
|
862
|
-
throw error;
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
async stream(options) {
|
|
866
|
-
let conversation;
|
|
867
|
-
if (options.conversationId) {
|
|
868
|
-
const existing = await this.store.get(options.conversationId);
|
|
869
|
-
if (!existing) {
|
|
870
|
-
throw new Error(`Conversation ${options.conversationId} not found`);
|
|
871
|
-
}
|
|
872
|
-
conversation = existing;
|
|
873
|
-
} else {
|
|
874
|
-
conversation = await this.store.create({
|
|
875
|
-
status: "active",
|
|
876
|
-
provider: this.provider.name,
|
|
877
|
-
model: this.provider.model,
|
|
878
|
-
messages: [],
|
|
879
|
-
workspacePath: this.context?.workspacePath
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
if (!options.skipUserAppend) {
|
|
883
|
-
await this.store.appendMessage(conversation.id, {
|
|
884
|
-
role: "user",
|
|
885
|
-
content: options.content,
|
|
886
|
-
status: "completed",
|
|
887
|
-
attachments: options.attachments
|
|
888
|
-
});
|
|
889
|
-
}
|
|
890
|
-
conversation = await this.store.get(conversation.id) ?? conversation;
|
|
891
|
-
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
892
|
-
role: "assistant",
|
|
893
|
-
content: "",
|
|
894
|
-
status: "streaming"
|
|
895
|
-
});
|
|
896
|
-
const messages = this.buildMessages(conversation, options);
|
|
897
|
-
const { model, providerName } = await this.resolveModel();
|
|
898
|
-
const systemPrompt = this.systemPrompt;
|
|
899
|
-
const tools = this.tools;
|
|
900
|
-
const store = this.store;
|
|
901
|
-
const onUsage = this.onUsage;
|
|
902
|
-
const streamProviderOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
903
|
-
async function* streamGenerator() {
|
|
904
|
-
let fullContent = "";
|
|
905
|
-
let fullReasoning = "";
|
|
906
|
-
const toolCallsMap = new Map;
|
|
907
|
-
const sources = [];
|
|
908
|
-
try {
|
|
909
|
-
const result = streamText({
|
|
910
|
-
model,
|
|
911
|
-
messages,
|
|
912
|
-
system: systemPrompt,
|
|
913
|
-
tools,
|
|
914
|
-
providerOptions: Object.keys(streamProviderOptions).length > 0 ? streamProviderOptions : undefined
|
|
915
|
-
});
|
|
916
|
-
for await (const part of result.fullStream) {
|
|
917
|
-
if (part.type === "text-delta") {
|
|
918
|
-
const text = part.text ?? "";
|
|
919
|
-
if (text) {
|
|
920
|
-
fullContent += text;
|
|
921
|
-
yield { type: "text", content: text };
|
|
922
|
-
}
|
|
923
|
-
} else if (part.type === "reasoning-delta") {
|
|
924
|
-
const text = part.text ?? "";
|
|
925
|
-
if (text) {
|
|
926
|
-
fullReasoning += text;
|
|
927
|
-
yield { type: "reasoning", content: text };
|
|
928
|
-
}
|
|
929
|
-
} else if (part.type === "source") {
|
|
930
|
-
const src = part;
|
|
931
|
-
const source = {
|
|
932
|
-
id: src.id,
|
|
933
|
-
title: src.title ?? "",
|
|
934
|
-
url: src.url,
|
|
935
|
-
type: "web"
|
|
936
|
-
};
|
|
937
|
-
sources.push(source);
|
|
938
|
-
yield { type: "source", source };
|
|
939
|
-
} else if (part.type === "tool-call") {
|
|
940
|
-
const toolCall = {
|
|
941
|
-
id: part.toolCallId,
|
|
942
|
-
name: part.toolName,
|
|
943
|
-
args: part.input ?? {},
|
|
944
|
-
status: "running"
|
|
945
|
-
};
|
|
946
|
-
toolCallsMap.set(part.toolCallId, toolCall);
|
|
947
|
-
yield { type: "tool_call", toolCall };
|
|
948
|
-
} else if (part.type === "tool-result") {
|
|
949
|
-
const tc = toolCallsMap.get(part.toolCallId);
|
|
950
|
-
if (tc) {
|
|
951
|
-
tc.result = part.output;
|
|
952
|
-
tc.status = "completed";
|
|
953
|
-
}
|
|
954
|
-
yield {
|
|
955
|
-
type: "tool_result",
|
|
956
|
-
toolResult: {
|
|
957
|
-
toolCallId: part.toolCallId,
|
|
958
|
-
toolName: part.toolName,
|
|
959
|
-
result: part.output
|
|
960
|
-
}
|
|
961
|
-
};
|
|
962
|
-
} else if (part.type === "tool-error") {
|
|
963
|
-
const tc = toolCallsMap.get(part.toolCallId);
|
|
964
|
-
if (tc) {
|
|
965
|
-
tc.status = "error";
|
|
966
|
-
tc.error = part.error ?? "Tool execution failed";
|
|
967
|
-
}
|
|
968
|
-
} else if (part.type === "finish") {
|
|
969
|
-
const usage = part.usage;
|
|
970
|
-
const inputTokens = usage?.inputTokens ?? 0;
|
|
971
|
-
const outputTokens = usage?.completionTokens ?? 0;
|
|
972
|
-
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
973
|
-
content: fullContent,
|
|
974
|
-
status: "completed",
|
|
975
|
-
reasoning: fullReasoning || undefined,
|
|
976
|
-
sources: sources.length > 0 ? sources : undefined,
|
|
977
|
-
toolCalls: toolCallsMap.size > 0 ? Array.from(toolCallsMap.values()) : undefined,
|
|
978
|
-
usage: usage ? { inputTokens, outputTokens } : undefined
|
|
979
|
-
});
|
|
980
|
-
onUsage?.({ inputTokens, outputTokens });
|
|
981
|
-
yield {
|
|
982
|
-
type: "done",
|
|
983
|
-
usage: usage ? { inputTokens, outputTokens } : undefined
|
|
984
|
-
};
|
|
985
|
-
return;
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
989
|
-
content: fullContent,
|
|
990
|
-
status: "completed",
|
|
991
|
-
reasoning: fullReasoning || undefined,
|
|
992
|
-
sources: sources.length > 0 ? sources : undefined,
|
|
993
|
-
toolCalls: toolCallsMap.size > 0 ? Array.from(toolCallsMap.values()) : undefined
|
|
994
|
-
});
|
|
995
|
-
yield { type: "done" };
|
|
996
|
-
} catch (error) {
|
|
997
|
-
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
998
|
-
content: fullContent,
|
|
999
|
-
status: "error",
|
|
1000
|
-
error: {
|
|
1001
|
-
code: "stream_failed",
|
|
1002
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1003
|
-
}
|
|
1004
|
-
});
|
|
1005
|
-
yield {
|
|
1006
|
-
type: "error",
|
|
1007
|
-
error: {
|
|
1008
|
-
code: "stream_failed",
|
|
1009
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1010
|
-
}
|
|
1011
|
-
};
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
return {
|
|
1015
|
-
conversationId: conversation.id,
|
|
1016
|
-
messageId: assistantMessage.id,
|
|
1017
|
-
stream: streamGenerator()
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
async getConversation(conversationId) {
|
|
1021
|
-
return this.store.get(conversationId);
|
|
1022
|
-
}
|
|
1023
|
-
async listConversations(options) {
|
|
1024
|
-
return this.store.list({
|
|
1025
|
-
status: "active",
|
|
1026
|
-
...options
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
async updateConversation(conversationId, updates) {
|
|
1030
|
-
return this.store.update(conversationId, updates);
|
|
1031
|
-
}
|
|
1032
|
-
async forkConversation(conversationId, upToMessageId) {
|
|
1033
|
-
return this.store.fork(conversationId, upToMessageId);
|
|
1034
|
-
}
|
|
1035
|
-
async updateMessage(conversationId, messageId, updates) {
|
|
1036
|
-
return this.store.updateMessage(conversationId, messageId, updates);
|
|
1037
|
-
}
|
|
1038
|
-
async truncateAfter(conversationId, messageId) {
|
|
1039
|
-
return this.store.truncateAfter(conversationId, messageId);
|
|
1040
|
-
}
|
|
1041
|
-
async deleteConversation(conversationId) {
|
|
1042
|
-
return this.store.delete(conversationId);
|
|
1043
|
-
}
|
|
1044
|
-
buildMessages(conversation, _options) {
|
|
1045
|
-
const historyStart = Math.max(0, conversation.messages.length - this.maxHistoryMessages);
|
|
1046
|
-
const messages = [];
|
|
1047
|
-
for (let i = historyStart;i < conversation.messages.length; i++) {
|
|
1048
|
-
const msg = conversation.messages[i];
|
|
1049
|
-
if (!msg)
|
|
1050
|
-
continue;
|
|
1051
|
-
if (msg.role === "user") {
|
|
1052
|
-
let content = msg.content;
|
|
1053
|
-
if (msg.attachments?.length) {
|
|
1054
|
-
const attachmentInfo = msg.attachments.map((a) => {
|
|
1055
|
-
if (a.type === "file" || a.type === "code") {
|
|
1056
|
-
return `
|
|
54
|
+
`+JX(j)}return Z}mergeTools(X){let Z=X.tools??{},$=X.workflowToolsConfig;if($?.baseWorkflows?.length){let V=v({baseWorkflows:$.baseWorkflows,composer:$.composer});Z={...Z,...V}}let j=X.contractsContext;if(j?.agentSpecs?.length){let V=[];for(let G of j.agentSpecs)if(G.tools?.length)V.push(...G.tools);if(V.length>0){let G=b(V);Z={...Z,...G}}}let H=X.surfacePlanConfig;if(H?.plan){let V=T({plan:H.plan,onPatchProposal:H.onPatchProposal});Z={...Z,...V}}if(X.mcpTools&&Object.keys(X.mcpTools).length>0)Z={...Z,...X.mcpTools};return Object.keys(Z).length>0?Z:void 0}async resolveModel(){if(this.modelSelector){let X=this.thinkingLevelToDimension(this.thinkingLevel),{model:Z,selection:$}=await this.modelSelector.selectAndCreate({taskDimension:X});return{model:Z,providerName:$.providerKey}}return{model:this.provider.getModel(),providerName:this.provider.name}}thinkingLevelToDimension(X){if(!X||X==="instant")return"latency";return"reasoning"}async send(X){let Z;if(X.conversationId){let G=await this.store.get(X.conversationId);if(!G)throw Error(`Conversation ${X.conversationId} not found`);Z=G}else Z=await this.store.create({status:"active",provider:this.provider.name,model:this.provider.model,messages:[],workspacePath:this.context?.workspacePath});if(!X.skipUserAppend)await this.store.appendMessage(Z.id,{role:"user",content:X.content,status:"completed",attachments:X.attachments});Z=await this.store.get(Z.id)??Z;let $=this.buildMessages(Z,X),{model:j,providerName:H}=await this.resolveModel(),V=A(this.thinkingLevel,H);try{let G=await VX({model:j,messages:$,system:this.systemPrompt,tools:this.tools,providerOptions:Object.keys(V).length>0?V:void 0}),J=await this.store.appendMessage(Z.id,{role:"assistant",content:G.text,status:"completed"}),Q=await this.store.get(Z.id);if(!Q)throw Error("Conversation lost after update");return{message:J,conversation:Q}}catch(G){throw await this.store.appendMessage(Z.id,{role:"assistant",content:"",status:"error",error:{code:"generation_failed",message:G instanceof Error?G.message:String(G)}}),G}}async stream(X){let Z;if(X.conversationId){let U=await this.store.get(X.conversationId);if(!U)throw Error(`Conversation ${X.conversationId} not found`);Z=U}else Z=await this.store.create({status:"active",provider:this.provider.name,model:this.provider.model,messages:[],workspacePath:this.context?.workspacePath});if(!X.skipUserAppend)await this.store.appendMessage(Z.id,{role:"user",content:X.content,status:"completed",attachments:X.attachments});Z=await this.store.get(Z.id)??Z;let $=await this.store.appendMessage(Z.id,{role:"assistant",content:"",status:"streaming"}),j=this.buildMessages(Z,X),{model:H,providerName:V}=await this.resolveModel(),G=this.systemPrompt,J=this.tools,Q=this.store,D=this.onUsage,B=A(this.thinkingLevel,V);async function*_(){let U="",q="",K=new Map,E=[];try{let L=GX({model:H,messages:j,system:G,tools:J,providerOptions:Object.keys(B).length>0?B:void 0});for await(let N of L.fullStream)if(N.type==="text-delta"){let W=N.text??"";if(W)U+=W,yield{type:"text",content:W}}else if(N.type==="reasoning-delta"){let W=N.text??"";if(W)q+=W,yield{type:"reasoning",content:W}}else if(N.type==="source"){let W=N,O={id:W.id,title:W.title??"",url:W.url,type:"web"};E.push(O),yield{type:"source",source:O}}else if(N.type==="tool-call"){let W={id:N.toolCallId,name:N.toolName,args:N.input??{},status:"running"};K.set(N.toolCallId,W),yield{type:"tool_call",toolCall:W}}else if(N.type==="tool-result"){let W=K.get(N.toolCallId);if(W)W.result=N.output,W.status="completed";yield{type:"tool_result",toolResult:{toolCallId:N.toolCallId,toolName:N.toolName,result:N.output}}}else if(N.type==="tool-error"){let W=K.get(N.toolCallId);if(W)W.status="error",W.error=N.error??"Tool execution failed"}else if(N.type==="finish"){let W=N.usage,O=W?.inputTokens??0,S=W?.completionTokens??0;await Q.updateMessage(Z.id,$.id,{content:U,status:"completed",reasoning:q||void 0,sources:E.length>0?E:void 0,toolCalls:K.size>0?Array.from(K.values()):void 0,usage:W?{inputTokens:O,outputTokens:S}:void 0}),D?.({inputTokens:O,outputTokens:S}),yield{type:"done",usage:W?{inputTokens:O,outputTokens:S}:void 0};return}await Q.updateMessage(Z.id,$.id,{content:U,status:"completed",reasoning:q||void 0,sources:E.length>0?E:void 0,toolCalls:K.size>0?Array.from(K.values()):void 0}),yield{type:"done"}}catch(L){await Q.updateMessage(Z.id,$.id,{content:U,status:"error",error:{code:"stream_failed",message:L instanceof Error?L.message:String(L)}}),yield{type:"error",error:{code:"stream_failed",message:L instanceof Error?L.message:String(L)}}}}return{conversationId:Z.id,messageId:$.id,stream:_()}}async getConversation(X){return this.store.get(X)}async listConversations(X){return this.store.list({status:"active",...X})}async updateConversation(X,Z){return this.store.update(X,Z)}async forkConversation(X,Z){return this.store.fork(X,Z)}async updateMessage(X,Z,$){return this.store.updateMessage(X,Z,$)}async truncateAfter(X,Z){return this.store.truncateAfter(X,Z)}async deleteConversation(X){return this.store.delete(X)}buildMessages(X,Z){let $=Math.max(0,X.messages.length-this.maxHistoryMessages),j=[];for(let H=$;H<X.messages.length;H++){let V=X.messages[H];if(!V)continue;if(V.role==="user"){let G=V.content;if(V.attachments?.length){let J=V.attachments.map((Q)=>{if(Q.type==="file"||Q.type==="code")return`
|
|
1057
55
|
|
|
1058
|
-
### ${
|
|
56
|
+
### ${Q.name}
|
|
1059
57
|
\`\`\`
|
|
1060
|
-
${
|
|
1061
|
-
\`\`\``;
|
|
1062
|
-
}
|
|
1063
|
-
return `
|
|
58
|
+
${Q.content??""}
|
|
59
|
+
\`\`\``;return`
|
|
1064
60
|
|
|
1065
|
-
[Attachment: ${a.name}]
|
|
1066
|
-
}).join("");
|
|
1067
|
-
content += attachmentInfo;
|
|
1068
|
-
}
|
|
1069
|
-
messages.push({ role: "user", content });
|
|
1070
|
-
} else if (msg.role === "assistant") {
|
|
1071
|
-
if (msg.toolCalls?.length) {
|
|
1072
|
-
messages.push({
|
|
1073
|
-
role: "assistant",
|
|
1074
|
-
content: msg.content || "",
|
|
1075
|
-
toolCalls: msg.toolCalls.map((tc) => ({
|
|
1076
|
-
type: "tool-call",
|
|
1077
|
-
toolCallId: tc.id,
|
|
1078
|
-
toolName: tc.name,
|
|
1079
|
-
args: tc.args
|
|
1080
|
-
}))
|
|
1081
|
-
});
|
|
1082
|
-
messages.push({
|
|
1083
|
-
role: "tool",
|
|
1084
|
-
content: msg.toolCalls.map((tc) => ({
|
|
1085
|
-
type: "tool-result",
|
|
1086
|
-
toolCallId: tc.id,
|
|
1087
|
-
toolName: tc.name,
|
|
1088
|
-
output: tc.result
|
|
1089
|
-
}))
|
|
1090
|
-
});
|
|
1091
|
-
} else {
|
|
1092
|
-
messages.push({ role: "assistant", content: msg.content });
|
|
1093
|
-
}
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
return messages;
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
function createChatService(config) {
|
|
1100
|
-
return new ChatService(config);
|
|
1101
|
-
}
|
|
1102
|
-
// src/core/create-chat-route.ts
|
|
1103
|
-
import {
|
|
1104
|
-
convertToModelMessages,
|
|
1105
|
-
streamText as streamText2
|
|
1106
|
-
} from "ai";
|
|
1107
|
-
import { z as z4 } from "zod";
|
|
1108
|
-
var CHAT_ROUTE_MAX_DURATION = 30;
|
|
1109
|
-
var REQUEST_BODY_SCHEMA = z4.object({
|
|
1110
|
-
messages: z4.array(z4.unknown()).min(1, "messages array required"),
|
|
1111
|
-
thinkingLevel: z4.enum(["instant", "thinking", "extra_thinking", "max"]).optional(),
|
|
1112
|
-
model: z4.string().optional()
|
|
1113
|
-
});
|
|
1114
|
-
var DEFAULT_SYSTEM_PROMPT2 = `You are a helpful AI assistant.`;
|
|
1115
|
-
function defaultSendReasoning(thinkingLevel) {
|
|
1116
|
-
return Boolean(thinkingLevel && thinkingLevel !== "instant");
|
|
1117
|
-
}
|
|
1118
|
-
function defaultSendSources() {
|
|
1119
|
-
return true;
|
|
1120
|
-
}
|
|
1121
|
-
function createChatRoute(options) {
|
|
1122
|
-
const {
|
|
1123
|
-
provider,
|
|
1124
|
-
systemPrompt = DEFAULT_SYSTEM_PROMPT2,
|
|
1125
|
-
tools,
|
|
1126
|
-
thinkingLevel: defaultThinkingLevel,
|
|
1127
|
-
sendSources = defaultSendSources(),
|
|
1128
|
-
sendReasoning = defaultSendReasoning(defaultThinkingLevel),
|
|
1129
|
-
getModel
|
|
1130
|
-
} = options;
|
|
1131
|
-
return async (req) => {
|
|
1132
|
-
if (req.method !== "POST") {
|
|
1133
|
-
return new Response("Method not allowed", { status: 405 });
|
|
1134
|
-
}
|
|
1135
|
-
let rawBody;
|
|
1136
|
-
try {
|
|
1137
|
-
rawBody = await req.json();
|
|
1138
|
-
} catch {
|
|
1139
|
-
return new Response(JSON.stringify({ error: "Invalid JSON body" }), {
|
|
1140
|
-
status: 400,
|
|
1141
|
-
headers: { "Content-Type": "application/json" }
|
|
1142
|
-
});
|
|
1143
|
-
}
|
|
1144
|
-
const parsed = REQUEST_BODY_SCHEMA.safeParse(rawBody);
|
|
1145
|
-
if (!parsed.success) {
|
|
1146
|
-
const message = parsed.error.issues[0]?.message ?? "Invalid request body";
|
|
1147
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
1148
|
-
status: 400,
|
|
1149
|
-
headers: { "Content-Type": "application/json" }
|
|
1150
|
-
});
|
|
1151
|
-
}
|
|
1152
|
-
const body = parsed.data;
|
|
1153
|
-
const thinkingLevel = body.thinkingLevel ?? defaultThinkingLevel;
|
|
1154
|
-
const providerOptions = getProviderOptions(thinkingLevel, provider.name);
|
|
1155
|
-
const model = getModel ? getModel(body) : provider.getModel();
|
|
1156
|
-
try {
|
|
1157
|
-
const result = streamText2({
|
|
1158
|
-
model,
|
|
1159
|
-
messages: await convertToModelMessages(body.messages),
|
|
1160
|
-
system: systemPrompt,
|
|
1161
|
-
tools,
|
|
1162
|
-
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
|
|
1163
|
-
});
|
|
1164
|
-
return result.toUIMessageStreamResponse({
|
|
1165
|
-
sendSources,
|
|
1166
|
-
sendReasoning
|
|
1167
|
-
});
|
|
1168
|
-
} catch (error) {
|
|
1169
|
-
const message = error instanceof Error ? error.message : "An error occurred";
|
|
1170
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
1171
|
-
status: 500,
|
|
1172
|
-
headers: { "Content-Type": "application/json" }
|
|
1173
|
-
});
|
|
1174
|
-
}
|
|
1175
|
-
};
|
|
1176
|
-
}
|
|
1177
|
-
// src/core/create-completion-route.ts
|
|
1178
|
-
import { streamText as streamText3 } from "ai";
|
|
1179
|
-
function createCompletionRoute(options) {
|
|
1180
|
-
const { provider, systemPrompt } = options;
|
|
1181
|
-
return async (req) => {
|
|
1182
|
-
if (req.method !== "POST") {
|
|
1183
|
-
return new Response("Method not allowed", { status: 405 });
|
|
1184
|
-
}
|
|
1185
|
-
let body;
|
|
1186
|
-
try {
|
|
1187
|
-
body = await req.json();
|
|
1188
|
-
} catch {
|
|
1189
|
-
return new Response("Invalid JSON body", { status: 400 });
|
|
1190
|
-
}
|
|
1191
|
-
const prompt = body.prompt ?? "";
|
|
1192
|
-
if (!prompt || typeof prompt !== "string") {
|
|
1193
|
-
return new Response("prompt string required", { status: 400 });
|
|
1194
|
-
}
|
|
1195
|
-
const model = provider.getModel();
|
|
1196
|
-
const result = streamText3({
|
|
1197
|
-
model,
|
|
1198
|
-
prompt,
|
|
1199
|
-
system: systemPrompt
|
|
1200
|
-
});
|
|
1201
|
-
return result.toTextStreamResponse();
|
|
1202
|
-
};
|
|
1203
|
-
}
|
|
1204
|
-
// src/core/export-formatters.ts
|
|
1205
|
-
function formatTimestamp(date) {
|
|
1206
|
-
return date.toLocaleTimeString([], {
|
|
1207
|
-
hour: "2-digit",
|
|
1208
|
-
minute: "2-digit"
|
|
1209
|
-
});
|
|
1210
|
-
}
|
|
1211
|
-
function toIsoString(date) {
|
|
1212
|
-
return date.toISOString();
|
|
1213
|
-
}
|
|
1214
|
-
function messageToJsonSerializable(msg) {
|
|
1215
|
-
return {
|
|
1216
|
-
id: msg.id,
|
|
1217
|
-
conversationId: msg.conversationId,
|
|
1218
|
-
role: msg.role,
|
|
1219
|
-
content: msg.content,
|
|
1220
|
-
status: msg.status,
|
|
1221
|
-
createdAt: toIsoString(msg.createdAt),
|
|
1222
|
-
updatedAt: toIsoString(msg.updatedAt),
|
|
1223
|
-
...msg.attachments && { attachments: msg.attachments },
|
|
1224
|
-
...msg.codeBlocks && { codeBlocks: msg.codeBlocks },
|
|
1225
|
-
...msg.toolCalls && { toolCalls: msg.toolCalls },
|
|
1226
|
-
...msg.sources && { sources: msg.sources },
|
|
1227
|
-
...msg.reasoning && { reasoning: msg.reasoning },
|
|
1228
|
-
...msg.usage && { usage: msg.usage },
|
|
1229
|
-
...msg.error && { error: msg.error },
|
|
1230
|
-
...msg.metadata && { metadata: msg.metadata }
|
|
1231
|
-
};
|
|
1232
|
-
}
|
|
1233
|
-
function formatSourcesMarkdown(sources) {
|
|
1234
|
-
if (sources.length === 0)
|
|
1235
|
-
return "";
|
|
1236
|
-
return `
|
|
61
|
+
[Attachment: ${Q.name}]`}).join("");G+=J}j.push({role:"user",content:G})}else if(V.role==="assistant")if(V.toolCalls?.length)j.push({role:"assistant",content:V.content||"",toolCalls:V.toolCalls.map((G)=>({type:"tool-call",toolCallId:G.id,toolName:G.name,args:G.args}))}),j.push({role:"tool",content:V.toolCalls.map((G)=>({type:"tool-result",toolCallId:G.id,toolName:G.name,output:G.result}))});else j.push({role:"assistant",content:V.content})}return j}}function YZ(X){return new u(X)}import{convertToModelMessages as UX,streamText as DX}from"ai";import{z as R}from"zod";var WZ=30,NX=R.object({messages:R.array(R.unknown()).min(1,"messages array required"),thinkingLevel:R.enum(["instant","thinking","extra_thinking","max"]).optional(),model:R.string().optional()}),WX="You are a helpful AI assistant.";function BX(X){return Boolean(X&&X!=="instant")}function FX(){return!0}function BZ(X){let{provider:Z,systemPrompt:$=WX,tools:j,thinkingLevel:H,sendSources:V=FX(),sendReasoning:G=BX(H),getModel:J}=X;return async(Q)=>{if(Q.method!=="POST")return new Response("Method not allowed",{status:405});let D;try{D=await Q.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON body"}),{status:400,headers:{"Content-Type":"application/json"}})}let B=NX.safeParse(D);if(!B.success){let E=B.error.issues[0]?.message??"Invalid request body";return new Response(JSON.stringify({error:E}),{status:400,headers:{"Content-Type":"application/json"}})}let _=B.data,U=_.thinkingLevel??H,q=A(U,Z.name),K=J?J(_):Z.getModel();try{return DX({model:K,messages:await UX(_.messages),system:$,tools:j,providerOptions:Object.keys(q).length>0?q:void 0}).toUIMessageStreamResponse({sendSources:V,sendReasoning:G})}catch(E){let L=E instanceof Error?E.message:"An error occurred";return new Response(JSON.stringify({error:L}),{status:500,headers:{"Content-Type":"application/json"}})}}}import{streamText as _X}from"ai";function EZ(X){let{provider:Z,systemPrompt:$}=X;return async(j)=>{if(j.method!=="POST")return new Response("Method not allowed",{status:405});let H;try{H=await j.json()}catch{return new Response("Invalid JSON body",{status:400})}let V=H.prompt??"";if(!V||typeof V!=="string")return new Response("prompt string required",{status:400});let G=Z.getModel();return _X({model:G,prompt:V,system:$}).toTextStreamResponse()}}function d(X){return X.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function h(X){return X.toISOString()}function EX(X){return{id:X.id,conversationId:X.conversationId,role:X.role,content:X.content,status:X.status,createdAt:h(X.createdAt),updatedAt:h(X.updatedAt),...X.attachments&&{attachments:X.attachments},...X.codeBlocks&&{codeBlocks:X.codeBlocks},...X.toolCalls&&{toolCalls:X.toolCalls},...X.sources&&{sources:X.sources},...X.reasoning&&{reasoning:X.reasoning},...X.usage&&{usage:X.usage},...X.error&&{error:X.error},...X.metadata&&{metadata:X.metadata}}}function KX(X){if(X.length===0)return"";return`
|
|
1237
62
|
|
|
1238
63
|
**Sources:**
|
|
1239
|
-
|
|
1240
|
-
`);
|
|
1241
|
-
}
|
|
1242
|
-
function formatSourcesTxt(sources) {
|
|
1243
|
-
if (sources.length === 0)
|
|
1244
|
-
return "";
|
|
1245
|
-
return `
|
|
64
|
+
`+X.map((Z)=>`- [${Z.title}](${Z.url??"#"})`).join(`
|
|
65
|
+
`)}function LX(X){if(X.length===0)return"";return`
|
|
1246
66
|
|
|
1247
67
|
Sources:
|
|
1248
|
-
|
|
1249
|
-
`);
|
|
1250
|
-
}
|
|
1251
|
-
function formatToolCallsMarkdown(toolCalls) {
|
|
1252
|
-
if (toolCalls.length === 0)
|
|
1253
|
-
return "";
|
|
1254
|
-
return `
|
|
68
|
+
`+X.map((Z)=>`- ${Z.title}${Z.url?` - ${Z.url}`:""}`).join(`
|
|
69
|
+
`)}function qX(X){if(X.length===0)return"";return`
|
|
1255
70
|
|
|
1256
71
|
**Tool calls:**
|
|
1257
|
-
|
|
72
|
+
`+X.map((Z)=>`**${Z.name}** (${Z.status})
|
|
1258
73
|
\`\`\`json
|
|
1259
|
-
${JSON.stringify(
|
|
1260
|
-
|
|
74
|
+
${JSON.stringify(Z.args,null,2)}
|
|
75
|
+
\`\`\``+(Z.result!==void 0?`
|
|
1261
76
|
Output:
|
|
1262
77
|
\`\`\`json
|
|
1263
|
-
${typeof
|
|
1264
|
-
|
|
1265
|
-
Error: ${
|
|
78
|
+
${typeof Z.result==="object"?JSON.stringify(Z.result,null,2):String(Z.result)}
|
|
79
|
+
\`\`\``:"")+(Z.error?`
|
|
80
|
+
Error: ${Z.error}`:"")).join(`
|
|
1266
81
|
|
|
1267
|
-
`);
|
|
1268
|
-
}
|
|
1269
|
-
function formatToolCallsTxt(toolCalls) {
|
|
1270
|
-
if (toolCalls.length === 0)
|
|
1271
|
-
return "";
|
|
1272
|
-
return `
|
|
82
|
+
`)}function OX(X){if(X.length===0)return"";return`
|
|
1273
83
|
|
|
1274
84
|
Tool calls:
|
|
1275
|
-
|
|
1276
|
-
`);
|
|
1277
|
-
}
|
|
1278
|
-
function formatUsage(usage) {
|
|
1279
|
-
const total = usage.inputTokens + usage.outputTokens;
|
|
1280
|
-
return ` (${total} tokens)`;
|
|
1281
|
-
}
|
|
1282
|
-
function formatMessagesAsMarkdown(messages) {
|
|
1283
|
-
const parts = [];
|
|
1284
|
-
for (const msg of messages) {
|
|
1285
|
-
const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
|
|
1286
|
-
const header = `## ${roleLabel}`;
|
|
1287
|
-
const timestamp = `*${formatTimestamp(msg.createdAt)}*`;
|
|
1288
|
-
const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
|
|
1289
|
-
const meta = `${timestamp}${usageSuffix}
|
|
85
|
+
`+X.map((Z)=>`- ${Z.name} (${Z.status}): ${JSON.stringify(Z.args)}`+(Z.result!==void 0?` -> ${typeof Z.result==="object"?JSON.stringify(Z.result):String(Z.result)}`:"")+(Z.error?` [Error: ${Z.error}]`:"")).join(`
|
|
86
|
+
`)}function m(X){return` (${X.inputTokens+X.outputTokens} tokens)`}function AX(X){let Z=[];for(let $ of X){let H=`## ${$.role==="user"?"User":$.role==="assistant"?"Assistant":"System"}`,V=`*${d($.createdAt)}*`,G=$.usage?m($.usage):"",J=`${V}${G}
|
|
1290
87
|
|
|
1291
|
-
|
|
1292
|
-
let body = msg.content;
|
|
1293
|
-
if (msg.error) {
|
|
1294
|
-
body += `
|
|
88
|
+
`,Q=$.content;if($.error)Q+=`
|
|
1295
89
|
|
|
1296
|
-
**Error:** ${
|
|
1297
|
-
}
|
|
1298
|
-
if (msg.reasoning) {
|
|
1299
|
-
body += `
|
|
90
|
+
**Error:** ${$.error.code} - ${$.error.message}`;if($.reasoning)Q+=`
|
|
1300
91
|
|
|
1301
92
|
> **Reasoning:**
|
|
1302
|
-
> ${
|
|
1303
|
-
> `)}`;
|
|
1304
|
-
}
|
|
1305
|
-
body += formatSourcesMarkdown(msg.sources ?? []);
|
|
1306
|
-
body += formatToolCallsMarkdown(msg.toolCalls ?? []);
|
|
1307
|
-
parts.push(`${header}
|
|
93
|
+
> ${$.reasoning.replace(/\n/g,`
|
|
94
|
+
> `)}`;Q+=KX($.sources??[]),Q+=qX($.toolCalls??[]),Z.push(`${H}
|
|
1308
95
|
|
|
1309
|
-
${
|
|
1310
|
-
}
|
|
1311
|
-
return parts.join(`
|
|
96
|
+
${J}${Q}`)}return Z.join(`
|
|
1312
97
|
|
|
1313
98
|
---
|
|
1314
99
|
|
|
1315
|
-
`);
|
|
1316
|
-
}
|
|
1317
|
-
function formatMessagesAsTxt(messages) {
|
|
1318
|
-
const parts = [];
|
|
1319
|
-
for (const msg of messages) {
|
|
1320
|
-
const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
|
|
1321
|
-
const timestamp = `(${formatTimestamp(msg.createdAt)})`;
|
|
1322
|
-
const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
|
|
1323
|
-
const header = `[${roleLabel}] ${timestamp}${usageSuffix}
|
|
100
|
+
`)}function RX(X){let Z=[];for(let $ of X){let j=$.role==="user"?"User":$.role==="assistant"?"Assistant":"System",H=`(${d($.createdAt)})`,V=$.usage?m($.usage):"",G=`[${j}] ${H}${V}
|
|
1324
101
|
|
|
1325
|
-
|
|
1326
|
-
let body = msg.content;
|
|
1327
|
-
if (msg.error) {
|
|
1328
|
-
body += `
|
|
102
|
+
`,J=$.content;if($.error)J+=`
|
|
1329
103
|
|
|
1330
|
-
Error: ${
|
|
1331
|
-
}
|
|
1332
|
-
if (msg.reasoning) {
|
|
1333
|
-
body += `
|
|
104
|
+
Error: ${$.error.code} - ${$.error.message}`;if($.reasoning)J+=`
|
|
1334
105
|
|
|
1335
|
-
Reasoning: ${
|
|
1336
|
-
}
|
|
1337
|
-
body += formatSourcesTxt(msg.sources ?? []);
|
|
1338
|
-
body += formatToolCallsTxt(msg.toolCalls ?? []);
|
|
1339
|
-
parts.push(`${header}${body}`);
|
|
1340
|
-
}
|
|
1341
|
-
return parts.join(`
|
|
106
|
+
Reasoning: ${$.reasoning}`;J+=LX($.sources??[]),J+=OX($.toolCalls??[]),Z.push(`${G}${J}`)}return Z.join(`
|
|
1342
107
|
|
|
1343
108
|
---
|
|
1344
109
|
|
|
1345
|
-
`);
|
|
1346
|
-
}
|
|
1347
|
-
function formatMessagesAsJson(messages, conversation) {
|
|
1348
|
-
const payload = {
|
|
1349
|
-
messages: messages.map(messageToJsonSerializable)
|
|
1350
|
-
};
|
|
1351
|
-
if (conversation) {
|
|
1352
|
-
payload.conversation = {
|
|
1353
|
-
id: conversation.id,
|
|
1354
|
-
title: conversation.title,
|
|
1355
|
-
status: conversation.status,
|
|
1356
|
-
createdAt: toIsoString(conversation.createdAt),
|
|
1357
|
-
updatedAt: toIsoString(conversation.updatedAt),
|
|
1358
|
-
provider: conversation.provider,
|
|
1359
|
-
model: conversation.model,
|
|
1360
|
-
workspacePath: conversation.workspacePath,
|
|
1361
|
-
contextFiles: conversation.contextFiles,
|
|
1362
|
-
summary: conversation.summary,
|
|
1363
|
-
metadata: conversation.metadata
|
|
1364
|
-
};
|
|
1365
|
-
}
|
|
1366
|
-
return JSON.stringify(payload, null, 2);
|
|
1367
|
-
}
|
|
1368
|
-
function getExportFilename(format, conversation) {
|
|
1369
|
-
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1370
|
-
const base = conversation?.title ? conversation.title.replace(/[^a-zA-Z0-9-_]/g, "_").slice(0, 40) : "chat-export";
|
|
1371
|
-
const ext = format === "markdown" ? "md" : format === "txt" ? "txt" : "json";
|
|
1372
|
-
return `${base}-${timestamp}.${ext}`;
|
|
1373
|
-
}
|
|
1374
|
-
var MIME_TYPES = {
|
|
1375
|
-
markdown: "text/markdown",
|
|
1376
|
-
txt: "text/plain",
|
|
1377
|
-
json: "application/json"
|
|
1378
|
-
};
|
|
1379
|
-
function downloadAsFile(content, filename, mimeType) {
|
|
1380
|
-
const blob = new Blob([content], { type: mimeType });
|
|
1381
|
-
const url = URL.createObjectURL(blob);
|
|
1382
|
-
const a = document.createElement("a");
|
|
1383
|
-
a.href = url;
|
|
1384
|
-
a.download = filename;
|
|
1385
|
-
document.body.appendChild(a);
|
|
1386
|
-
a.click();
|
|
1387
|
-
document.body.removeChild(a);
|
|
1388
|
-
URL.revokeObjectURL(url);
|
|
1389
|
-
}
|
|
1390
|
-
function exportToFile(messages, format, conversation) {
|
|
1391
|
-
let content;
|
|
1392
|
-
if (format === "markdown") {
|
|
1393
|
-
content = formatMessagesAsMarkdown(messages);
|
|
1394
|
-
} else if (format === "txt") {
|
|
1395
|
-
content = formatMessagesAsTxt(messages);
|
|
1396
|
-
} else {
|
|
1397
|
-
content = formatMessagesAsJson(messages, conversation);
|
|
1398
|
-
}
|
|
1399
|
-
const filename = getExportFilename(format, conversation);
|
|
1400
|
-
const mimeType = MIME_TYPES[format];
|
|
1401
|
-
downloadAsFile(content, filename, mimeType);
|
|
1402
|
-
}
|
|
1403
|
-
// src/core/local-storage-conversation-store.ts
|
|
1404
|
-
var DEFAULT_KEY = "contractspec:ai-chat:conversations";
|
|
1405
|
-
function generateId2(prefix) {
|
|
1406
|
-
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
1407
|
-
}
|
|
1408
|
-
function toSerializable(conv) {
|
|
1409
|
-
return {
|
|
1410
|
-
...conv,
|
|
1411
|
-
createdAt: conv.createdAt.toISOString(),
|
|
1412
|
-
updatedAt: conv.updatedAt.toISOString(),
|
|
1413
|
-
messages: conv.messages.map((m) => ({
|
|
1414
|
-
...m,
|
|
1415
|
-
createdAt: m.createdAt.toISOString(),
|
|
1416
|
-
updatedAt: m.updatedAt.toISOString()
|
|
1417
|
-
}))
|
|
1418
|
-
};
|
|
1419
|
-
}
|
|
1420
|
-
function fromSerializable(raw) {
|
|
1421
|
-
const messages = raw.messages?.map((m) => ({
|
|
1422
|
-
...m,
|
|
1423
|
-
createdAt: new Date(m.createdAt),
|
|
1424
|
-
updatedAt: new Date(m.updatedAt)
|
|
1425
|
-
})) ?? [];
|
|
1426
|
-
return {
|
|
1427
|
-
...raw,
|
|
1428
|
-
createdAt: new Date(raw.createdAt),
|
|
1429
|
-
updatedAt: new Date(raw.updatedAt),
|
|
1430
|
-
messages
|
|
1431
|
-
};
|
|
1432
|
-
}
|
|
1433
|
-
function loadAll(key) {
|
|
1434
|
-
if (typeof window === "undefined")
|
|
1435
|
-
return new Map;
|
|
1436
|
-
try {
|
|
1437
|
-
const raw = window.localStorage.getItem(key);
|
|
1438
|
-
if (!raw)
|
|
1439
|
-
return new Map;
|
|
1440
|
-
const arr = JSON.parse(raw);
|
|
1441
|
-
const map = new Map;
|
|
1442
|
-
for (const item of arr) {
|
|
1443
|
-
const conv = fromSerializable(item);
|
|
1444
|
-
map.set(conv.id, conv);
|
|
1445
|
-
}
|
|
1446
|
-
return map;
|
|
1447
|
-
} catch {
|
|
1448
|
-
return new Map;
|
|
1449
|
-
}
|
|
1450
|
-
}
|
|
1451
|
-
function saveAll(key, map) {
|
|
1452
|
-
if (typeof window === "undefined")
|
|
1453
|
-
return;
|
|
1454
|
-
try {
|
|
1455
|
-
const arr = Array.from(map.values()).map(toSerializable);
|
|
1456
|
-
window.localStorage.setItem(key, JSON.stringify(arr));
|
|
1457
|
-
} catch {}
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
|
-
class LocalStorageConversationStore {
|
|
1461
|
-
key;
|
|
1462
|
-
cache = null;
|
|
1463
|
-
constructor(storageKey = DEFAULT_KEY) {
|
|
1464
|
-
this.key = storageKey;
|
|
1465
|
-
}
|
|
1466
|
-
getMap() {
|
|
1467
|
-
if (!this.cache) {
|
|
1468
|
-
this.cache = loadAll(this.key);
|
|
1469
|
-
}
|
|
1470
|
-
return this.cache;
|
|
1471
|
-
}
|
|
1472
|
-
persist() {
|
|
1473
|
-
saveAll(this.key, this.getMap());
|
|
1474
|
-
}
|
|
1475
|
-
async get(conversationId) {
|
|
1476
|
-
return this.getMap().get(conversationId) ?? null;
|
|
1477
|
-
}
|
|
1478
|
-
async create(conversation) {
|
|
1479
|
-
const now = new Date;
|
|
1480
|
-
const full = {
|
|
1481
|
-
...conversation,
|
|
1482
|
-
id: generateId2("conv"),
|
|
1483
|
-
createdAt: now,
|
|
1484
|
-
updatedAt: now
|
|
1485
|
-
};
|
|
1486
|
-
this.getMap().set(full.id, full);
|
|
1487
|
-
this.persist();
|
|
1488
|
-
return full;
|
|
1489
|
-
}
|
|
1490
|
-
async update(conversationId, updates) {
|
|
1491
|
-
const conv = this.getMap().get(conversationId);
|
|
1492
|
-
if (!conv)
|
|
1493
|
-
return null;
|
|
1494
|
-
const updated = {
|
|
1495
|
-
...conv,
|
|
1496
|
-
...updates,
|
|
1497
|
-
updatedAt: new Date
|
|
1498
|
-
};
|
|
1499
|
-
this.getMap().set(conversationId, updated);
|
|
1500
|
-
this.persist();
|
|
1501
|
-
return updated;
|
|
1502
|
-
}
|
|
1503
|
-
async appendMessage(conversationId, message) {
|
|
1504
|
-
const conv = this.getMap().get(conversationId);
|
|
1505
|
-
if (!conv)
|
|
1506
|
-
throw new Error(`Conversation ${conversationId} not found`);
|
|
1507
|
-
const now = new Date;
|
|
1508
|
-
const fullMessage = {
|
|
1509
|
-
...message,
|
|
1510
|
-
id: generateId2("msg"),
|
|
1511
|
-
conversationId,
|
|
1512
|
-
createdAt: now,
|
|
1513
|
-
updatedAt: now
|
|
1514
|
-
};
|
|
1515
|
-
conv.messages.push(fullMessage);
|
|
1516
|
-
conv.updatedAt = now;
|
|
1517
|
-
this.persist();
|
|
1518
|
-
return fullMessage;
|
|
1519
|
-
}
|
|
1520
|
-
async updateMessage(conversationId, messageId, updates) {
|
|
1521
|
-
const conv = this.getMap().get(conversationId);
|
|
1522
|
-
if (!conv)
|
|
1523
|
-
return null;
|
|
1524
|
-
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
1525
|
-
if (idx === -1)
|
|
1526
|
-
return null;
|
|
1527
|
-
const msg = conv.messages[idx];
|
|
1528
|
-
if (!msg)
|
|
1529
|
-
return null;
|
|
1530
|
-
const updated = {
|
|
1531
|
-
...msg,
|
|
1532
|
-
...updates,
|
|
1533
|
-
updatedAt: new Date
|
|
1534
|
-
};
|
|
1535
|
-
conv.messages[idx] = updated;
|
|
1536
|
-
conv.updatedAt = new Date;
|
|
1537
|
-
this.persist();
|
|
1538
|
-
return updated;
|
|
1539
|
-
}
|
|
1540
|
-
async delete(conversationId) {
|
|
1541
|
-
const deleted = this.getMap().delete(conversationId);
|
|
1542
|
-
if (deleted)
|
|
1543
|
-
this.persist();
|
|
1544
|
-
return deleted;
|
|
1545
|
-
}
|
|
1546
|
-
async list(options) {
|
|
1547
|
-
let results = Array.from(this.getMap().values());
|
|
1548
|
-
if (options?.status) {
|
|
1549
|
-
results = results.filter((c) => c.status === options.status);
|
|
1550
|
-
}
|
|
1551
|
-
if (options?.projectId) {
|
|
1552
|
-
results = results.filter((c) => c.projectId === options.projectId);
|
|
1553
|
-
}
|
|
1554
|
-
if (options?.tags && options.tags.length > 0) {
|
|
1555
|
-
const tagSet = new Set(options.tags);
|
|
1556
|
-
results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
|
|
1557
|
-
}
|
|
1558
|
-
results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
1559
|
-
const offset = options?.offset ?? 0;
|
|
1560
|
-
const limit = options?.limit ?? 100;
|
|
1561
|
-
return results.slice(offset, offset + limit);
|
|
1562
|
-
}
|
|
1563
|
-
async fork(conversationId, upToMessageId) {
|
|
1564
|
-
const source = this.getMap().get(conversationId);
|
|
1565
|
-
if (!source)
|
|
1566
|
-
throw new Error(`Conversation ${conversationId} not found`);
|
|
1567
|
-
let messagesToCopy = source.messages;
|
|
1568
|
-
if (upToMessageId) {
|
|
1569
|
-
const idx = source.messages.findIndex((m) => m.id === upToMessageId);
|
|
1570
|
-
if (idx === -1)
|
|
1571
|
-
throw new Error(`Message ${upToMessageId} not found`);
|
|
1572
|
-
messagesToCopy = source.messages.slice(0, idx + 1);
|
|
1573
|
-
}
|
|
1574
|
-
const now = new Date;
|
|
1575
|
-
const forkedMessages = messagesToCopy.map((m) => ({
|
|
1576
|
-
...m,
|
|
1577
|
-
id: generateId2("msg"),
|
|
1578
|
-
conversationId: "",
|
|
1579
|
-
createdAt: new Date(m.createdAt),
|
|
1580
|
-
updatedAt: new Date(m.updatedAt)
|
|
1581
|
-
}));
|
|
1582
|
-
const forked = {
|
|
1583
|
-
...source,
|
|
1584
|
-
id: generateId2("conv"),
|
|
1585
|
-
title: source.title ? `${source.title} (fork)` : undefined,
|
|
1586
|
-
forkedFromId: source.id,
|
|
1587
|
-
createdAt: now,
|
|
1588
|
-
updatedAt: now,
|
|
1589
|
-
messages: forkedMessages
|
|
1590
|
-
};
|
|
1591
|
-
for (const m of forked.messages) {
|
|
1592
|
-
m.conversationId = forked.id;
|
|
1593
|
-
}
|
|
1594
|
-
this.getMap().set(forked.id, forked);
|
|
1595
|
-
this.persist();
|
|
1596
|
-
return forked;
|
|
1597
|
-
}
|
|
1598
|
-
async truncateAfter(conversationId, messageId) {
|
|
1599
|
-
const conv = this.getMap().get(conversationId);
|
|
1600
|
-
if (!conv)
|
|
1601
|
-
return null;
|
|
1602
|
-
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
1603
|
-
if (idx === -1)
|
|
1604
|
-
return null;
|
|
1605
|
-
conv.messages = conv.messages.slice(0, idx + 1);
|
|
1606
|
-
conv.updatedAt = new Date;
|
|
1607
|
-
this.persist();
|
|
1608
|
-
return conv;
|
|
1609
|
-
}
|
|
1610
|
-
async search(query, limit = 20) {
|
|
1611
|
-
const lowerQuery = query.toLowerCase();
|
|
1612
|
-
const results = [];
|
|
1613
|
-
for (const conv of this.getMap().values()) {
|
|
1614
|
-
if (conv.title?.toLowerCase().includes(lowerQuery)) {
|
|
1615
|
-
results.push(conv);
|
|
1616
|
-
continue;
|
|
1617
|
-
}
|
|
1618
|
-
if (conv.messages.some((m) => m.content.toLowerCase().includes(lowerQuery))) {
|
|
1619
|
-
results.push(conv);
|
|
1620
|
-
}
|
|
1621
|
-
if (results.length >= limit)
|
|
1622
|
-
break;
|
|
1623
|
-
}
|
|
1624
|
-
return results;
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
function createLocalStorageConversationStore(storageKey) {
|
|
1628
|
-
return new LocalStorageConversationStore(storageKey);
|
|
1629
|
-
}
|
|
1630
|
-
export {
|
|
1631
|
-
getProviderOptions,
|
|
1632
|
-
getExportFilename,
|
|
1633
|
-
formatMessagesAsTxt,
|
|
1634
|
-
formatMessagesAsMarkdown,
|
|
1635
|
-
formatMessagesAsJson,
|
|
1636
|
-
exportToFile,
|
|
1637
|
-
downloadAsFile,
|
|
1638
|
-
createWorkflowTools,
|
|
1639
|
-
createSurfacePlannerTools,
|
|
1640
|
-
createLocalStorageConversationStore,
|
|
1641
|
-
createInMemoryConversationStore,
|
|
1642
|
-
createCompletionRoute,
|
|
1643
|
-
createChatService,
|
|
1644
|
-
createChatRoute,
|
|
1645
|
-
createChatAgentAdapter,
|
|
1646
|
-
buildPlannerPromptInput,
|
|
1647
|
-
buildContractsContextPrompt,
|
|
1648
|
-
agentToolConfigsToToolSet,
|
|
1649
|
-
THINKING_LEVEL_LABELS,
|
|
1650
|
-
THINKING_LEVEL_DESCRIPTIONS,
|
|
1651
|
-
LocalStorageConversationStore,
|
|
1652
|
-
InMemoryConversationStore,
|
|
1653
|
-
ChatService,
|
|
1654
|
-
CHAT_ROUTE_MAX_DURATION
|
|
1655
|
-
};
|
|
110
|
+
`)}function zX(X,Z){let $={messages:X.map(EX)};if(Z)$.conversation={id:Z.id,title:Z.title,status:Z.status,createdAt:h(Z.createdAt),updatedAt:h(Z.updatedAt),provider:Z.provider,model:Z.model,workspacePath:Z.workspacePath,contextFiles:Z.contextFiles,summary:Z.summary,metadata:Z.metadata};return JSON.stringify($,null,2)}function PX(X,Z){let $=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);return`${Z?.title?Z.title.replace(/[^a-zA-Z0-9-_]/g,"_").slice(0,40):"chat-export"}-${$}.${X==="markdown"?"md":X==="txt"?"txt":"json"}`}var kX={markdown:"text/markdown",txt:"text/plain",json:"application/json"};function wX(X,Z,$){let j=new Blob([X],{type:$}),H=URL.createObjectURL(j),V=document.createElement("a");V.href=H,V.download=Z,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(H)}function LZ(X,Z,$){let j;if(Z==="markdown")j=AX(X);else if(Z==="txt")j=RX(X);else j=zX(X,$);let H=PX(Z,$),V=kX[Z];wX(j,H,V)}function M(X){return`${X}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function hX(X){return{...X,createdAt:X.createdAt.toISOString(),updatedAt:X.updatedAt.toISOString(),messages:X.messages.map((Z)=>({...Z,createdAt:Z.createdAt.toISOString(),updatedAt:Z.updatedAt.toISOString()}))}}function MX(X){let Z=X.messages?.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)}))??[];return{...X,createdAt:new Date(X.createdAt),updatedAt:new Date(X.updatedAt),messages:Z}}function SX(X){if(typeof window>"u")return new Map;try{let Z=window.localStorage.getItem(X);if(!Z)return new Map;let $=JSON.parse(Z),j=new Map;for(let H of $){let V=MX(H);j.set(V.id,V)}return j}catch{return new Map}}function xX(X,Z){if(typeof window>"u")return;try{let $=Array.from(Z.values()).map(hX);window.localStorage.setItem(X,JSON.stringify($))}catch{}}class l{key;cache=null;constructor(X="contractspec:ai-chat:conversations"){this.key=X}getMap(){if(!this.cache)this.cache=SX(this.key);return this.cache}persist(){xX(this.key,this.getMap())}async get(X){return this.getMap().get(X)??null}async create(X){let Z=new Date,$={...X,id:M("conv"),createdAt:Z,updatedAt:Z};return this.getMap().set($.id,$),this.persist(),$}async update(X,Z){let $=this.getMap().get(X);if(!$)return null;let j={...$,...Z,updatedAt:new Date};return this.getMap().set(X,j),this.persist(),j}async appendMessage(X,Z){let $=this.getMap().get(X);if(!$)throw Error(`Conversation ${X} not found`);let j=new Date,H={...Z,id:M("msg"),conversationId:X,createdAt:j,updatedAt:j};return $.messages.push(H),$.updatedAt=j,this.persist(),H}async updateMessage(X,Z,$){let j=this.getMap().get(X);if(!j)return null;let H=j.messages.findIndex((J)=>J.id===Z);if(H===-1)return null;let V=j.messages[H];if(!V)return null;let G={...V,...$,updatedAt:new Date};return j.messages[H]=G,j.updatedAt=new Date,this.persist(),G}async delete(X){let Z=this.getMap().delete(X);if(Z)this.persist();return Z}async list(X){let Z=Array.from(this.getMap().values());if(X?.status)Z=Z.filter((H)=>H.status===X.status);if(X?.projectId)Z=Z.filter((H)=>H.projectId===X.projectId);if(X?.tags&&X.tags.length>0){let H=new Set(X.tags);Z=Z.filter((V)=>V.tags&&V.tags.some((G)=>H.has(G)))}Z.sort((H,V)=>V.updatedAt.getTime()-H.updatedAt.getTime());let $=X?.offset??0,j=X?.limit??100;return Z.slice($,$+j)}async fork(X,Z){let $=this.getMap().get(X);if(!$)throw Error(`Conversation ${X} not found`);let j=$.messages;if(Z){let J=$.messages.findIndex((Q)=>Q.id===Z);if(J===-1)throw Error(`Message ${Z} not found`);j=$.messages.slice(0,J+1)}let H=new Date,V=j.map((J)=>({...J,id:M("msg"),conversationId:"",createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),G={...$,id:M("conv"),title:$.title?`${$.title} (fork)`:void 0,forkedFromId:$.id,createdAt:H,updatedAt:H,messages:V};for(let J of G.messages)J.conversationId=G.id;return this.getMap().set(G.id,G),this.persist(),G}async truncateAfter(X,Z){let $=this.getMap().get(X);if(!$)return null;let j=$.messages.findIndex((H)=>H.id===Z);if(j===-1)return null;return $.messages=$.messages.slice(0,j+1),$.updatedAt=new Date,this.persist(),$}async search(X,Z=20){let $=X.toLowerCase(),j=[];for(let H of this.getMap().values()){if(H.title?.toLowerCase().includes($)){j.push(H);continue}if(H.messages.some((V)=>V.content.toLowerCase().includes($)))j.push(H);if(j.length>=Z)break}return j}}function OZ(X){return new l(X)}export{A as getProviderOptions,PX as getExportFilename,RX as formatMessagesAsTxt,AX as formatMessagesAsMarkdown,zX as formatMessagesAsJson,LZ as exportToFile,wX as downloadAsFile,v as createWorkflowTools,T as createSurfacePlannerTools,OZ as createLocalStorageConversationStore,dX as createInMemoryConversationStore,EZ as createCompletionRoute,YZ as createChatService,BZ as createChatRoute,CX as createChatAgentAdapter,I as buildPlannerPromptInput,y as buildContractsContextPrompt,b as agentToolConfigsToToolSet,rX as THINKING_LEVEL_LABELS,aX as THINKING_LEVEL_DESCRIPTIONS,l as LocalStorageConversationStore,P as InMemoryConversationStore,u as ChatService,WZ as CHAT_ROUTE_MAX_DURATION};
|