@contractspec/module.ai-chat 4.0.3 → 4.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -10
- package/dist/adapters/ai-sdk-bundle-adapter.d.ts +18 -0
- package/dist/adapters/index.d.ts +4 -0
- package/dist/browser/core/index.js +1143 -21
- package/dist/browser/index.js +2813 -631
- package/dist/browser/presentation/components/index.js +3160 -358
- package/dist/browser/presentation/hooks/index.js +978 -43
- package/dist/browser/presentation/index.js +2801 -666
- package/dist/core/agent-adapter.d.ts +53 -0
- package/dist/core/agent-tools-adapter.d.ts +12 -0
- package/dist/core/chat-service.d.ts +49 -1
- package/dist/core/contracts-context.d.ts +46 -0
- package/dist/core/contracts-context.test.d.ts +1 -0
- package/dist/core/conversation-store.d.ts +16 -2
- package/dist/core/create-chat-route.d.ts +3 -0
- package/dist/core/export-formatters.d.ts +29 -0
- package/dist/core/export-formatters.test.d.ts +1 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.js +1143 -21
- package/dist/core/local-storage-conversation-store.d.ts +33 -0
- package/dist/core/message-types.d.ts +6 -0
- package/dist/core/surface-planner-tools.d.ts +23 -0
- package/dist/core/surface-planner-tools.test.d.ts +1 -0
- package/dist/core/thinking-levels.d.ts +38 -0
- package/dist/core/thinking-levels.test.d.ts +1 -0
- package/dist/core/workflow-tools.d.ts +18 -0
- package/dist/core/workflow-tools.test.d.ts +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2813 -631
- package/dist/node/core/index.js +1143 -21
- package/dist/node/index.js +2813 -631
- package/dist/node/presentation/components/index.js +3160 -358
- package/dist/node/presentation/hooks/index.js +978 -43
- package/dist/node/presentation/index.js +2804 -669
- package/dist/presentation/components/ChatContainer.d.ts +3 -1
- package/dist/presentation/components/ChatExportToolbar.d.ts +25 -0
- package/dist/presentation/components/ChatMessage.d.ts +16 -1
- package/dist/presentation/components/ChatSidebar.d.ts +26 -0
- package/dist/presentation/components/ChatWithExport.d.ts +34 -0
- package/dist/presentation/components/ChatWithSidebar.d.ts +19 -0
- package/dist/presentation/components/ThinkingLevelPicker.d.ts +16 -0
- package/dist/presentation/components/ToolResultRenderer.d.ts +33 -0
- package/dist/presentation/components/index.d.ts +6 -0
- package/dist/presentation/components/index.js +3160 -358
- package/dist/presentation/hooks/index.d.ts +2 -0
- package/dist/presentation/hooks/index.js +978 -43
- package/dist/presentation/hooks/useChat.d.ts +44 -2
- package/dist/presentation/hooks/useConversations.d.ts +18 -0
- package/dist/presentation/hooks/useMessageSelection.d.ts +13 -0
- package/dist/presentation/index.js +2804 -669
- package/package.json +14 -18
package/dist/node/core/index.js
CHANGED
|
@@ -77,11 +77,65 @@ class InMemoryConversationStore {
|
|
|
77
77
|
if (options?.status) {
|
|
78
78
|
results = results.filter((c) => c.status === options.status);
|
|
79
79
|
}
|
|
80
|
+
if (options?.projectId) {
|
|
81
|
+
results = results.filter((c) => c.projectId === options.projectId);
|
|
82
|
+
}
|
|
83
|
+
if (options?.tags && options.tags.length > 0) {
|
|
84
|
+
const tagSet = new Set(options.tags);
|
|
85
|
+
results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
|
|
86
|
+
}
|
|
80
87
|
results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
81
88
|
const offset = options?.offset ?? 0;
|
|
82
89
|
const limit = options?.limit ?? 100;
|
|
83
90
|
return results.slice(offset, offset + limit);
|
|
84
91
|
}
|
|
92
|
+
async fork(conversationId, upToMessageId) {
|
|
93
|
+
const source = this.conversations.get(conversationId);
|
|
94
|
+
if (!source) {
|
|
95
|
+
throw new Error(`Conversation ${conversationId} not found`);
|
|
96
|
+
}
|
|
97
|
+
let messagesToCopy = source.messages;
|
|
98
|
+
if (upToMessageId) {
|
|
99
|
+
const idx = source.messages.findIndex((m) => m.id === upToMessageId);
|
|
100
|
+
if (idx === -1) {
|
|
101
|
+
throw new Error(`Message ${upToMessageId} not found`);
|
|
102
|
+
}
|
|
103
|
+
messagesToCopy = source.messages.slice(0, idx + 1);
|
|
104
|
+
}
|
|
105
|
+
const now = new Date;
|
|
106
|
+
const forkedMessages = messagesToCopy.map((m) => ({
|
|
107
|
+
...m,
|
|
108
|
+
id: generateId("msg"),
|
|
109
|
+
conversationId: "",
|
|
110
|
+
createdAt: new Date(m.createdAt),
|
|
111
|
+
updatedAt: new Date(m.updatedAt)
|
|
112
|
+
}));
|
|
113
|
+
const forked = {
|
|
114
|
+
...source,
|
|
115
|
+
id: generateId("conv"),
|
|
116
|
+
title: source.title ? `${source.title} (fork)` : undefined,
|
|
117
|
+
forkedFromId: source.id,
|
|
118
|
+
createdAt: now,
|
|
119
|
+
updatedAt: now,
|
|
120
|
+
messages: forkedMessages
|
|
121
|
+
};
|
|
122
|
+
for (const m of forked.messages) {
|
|
123
|
+
m.conversationId = forked.id;
|
|
124
|
+
}
|
|
125
|
+
this.conversations.set(forked.id, forked);
|
|
126
|
+
return forked;
|
|
127
|
+
}
|
|
128
|
+
async truncateAfter(conversationId, messageId) {
|
|
129
|
+
const conv = this.conversations.get(conversationId);
|
|
130
|
+
if (!conv)
|
|
131
|
+
return null;
|
|
132
|
+
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
133
|
+
if (idx === -1)
|
|
134
|
+
return null;
|
|
135
|
+
conv.messages = conv.messages.slice(0, idx + 1);
|
|
136
|
+
conv.updatedAt = new Date;
|
|
137
|
+
return conv;
|
|
138
|
+
}
|
|
85
139
|
async search(query, limit = 20) {
|
|
86
140
|
const lowerQuery = query.toLowerCase();
|
|
87
141
|
const results = [];
|
|
@@ -108,6 +162,510 @@ function createInMemoryConversationStore() {
|
|
|
108
162
|
}
|
|
109
163
|
// src/core/chat-service.ts
|
|
110
164
|
import { generateText, streamText } from "ai";
|
|
165
|
+
|
|
166
|
+
// src/core/thinking-levels.ts
|
|
167
|
+
var THINKING_LEVEL_LABELS = {
|
|
168
|
+
instant: "Instant",
|
|
169
|
+
thinking: "Thinking",
|
|
170
|
+
extra_thinking: "Extra Thinking",
|
|
171
|
+
max: "Max"
|
|
172
|
+
};
|
|
173
|
+
var THINKING_LEVEL_DESCRIPTIONS = {
|
|
174
|
+
instant: "Fast responses, minimal reasoning",
|
|
175
|
+
thinking: "Standard reasoning depth",
|
|
176
|
+
extra_thinking: "More thorough reasoning",
|
|
177
|
+
max: "Maximum reasoning depth"
|
|
178
|
+
};
|
|
179
|
+
function getProviderOptions(level, providerName) {
|
|
180
|
+
if (!level || level === "instant") {
|
|
181
|
+
return {};
|
|
182
|
+
}
|
|
183
|
+
switch (providerName) {
|
|
184
|
+
case "anthropic": {
|
|
185
|
+
const budgetMap = {
|
|
186
|
+
thinking: 8000,
|
|
187
|
+
extra_thinking: 16000,
|
|
188
|
+
max: 32000
|
|
189
|
+
};
|
|
190
|
+
return {
|
|
191
|
+
anthropic: {
|
|
192
|
+
thinking: { type: "enabled", budgetTokens: budgetMap[level] }
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
case "openai": {
|
|
197
|
+
const effortMap = {
|
|
198
|
+
thinking: "low",
|
|
199
|
+
extra_thinking: "medium",
|
|
200
|
+
max: "high"
|
|
201
|
+
};
|
|
202
|
+
return {
|
|
203
|
+
openai: {
|
|
204
|
+
reasoningEffort: effortMap[level]
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
case "ollama":
|
|
209
|
+
case "mistral":
|
|
210
|
+
case "gemini":
|
|
211
|
+
return {};
|
|
212
|
+
default:
|
|
213
|
+
return {};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/core/workflow-tools.ts
|
|
218
|
+
import { tool } from "ai";
|
|
219
|
+
import { z } from "zod";
|
|
220
|
+
import {
|
|
221
|
+
WorkflowComposer,
|
|
222
|
+
validateExtension
|
|
223
|
+
} from "@contractspec/lib.workflow-composer";
|
|
224
|
+
var StepTypeSchema = z.enum(["human", "automation", "decision"]);
|
|
225
|
+
var StepActionSchema = z.object({
|
|
226
|
+
operation: z.object({
|
|
227
|
+
name: z.string(),
|
|
228
|
+
version: z.number()
|
|
229
|
+
}).optional(),
|
|
230
|
+
form: z.object({
|
|
231
|
+
key: z.string(),
|
|
232
|
+
version: z.number()
|
|
233
|
+
}).optional()
|
|
234
|
+
}).optional();
|
|
235
|
+
var StepSchema = z.object({
|
|
236
|
+
id: z.string(),
|
|
237
|
+
type: StepTypeSchema,
|
|
238
|
+
label: z.string(),
|
|
239
|
+
description: z.string().optional(),
|
|
240
|
+
action: StepActionSchema
|
|
241
|
+
});
|
|
242
|
+
var StepInjectionSchema = z.object({
|
|
243
|
+
after: z.string().optional(),
|
|
244
|
+
before: z.string().optional(),
|
|
245
|
+
inject: StepSchema,
|
|
246
|
+
transitionTo: z.string().optional(),
|
|
247
|
+
transitionFrom: z.string().optional(),
|
|
248
|
+
when: z.string().optional()
|
|
249
|
+
});
|
|
250
|
+
var WorkflowExtensionInputSchema = z.object({
|
|
251
|
+
workflow: z.string(),
|
|
252
|
+
tenantId: z.string().optional(),
|
|
253
|
+
role: z.string().optional(),
|
|
254
|
+
priority: z.number().optional(),
|
|
255
|
+
customSteps: z.array(StepInjectionSchema).optional(),
|
|
256
|
+
hiddenSteps: z.array(z.string()).optional()
|
|
257
|
+
});
|
|
258
|
+
function createWorkflowTools(config) {
|
|
259
|
+
const { baseWorkflows, composer } = config;
|
|
260
|
+
const baseByKey = new Map(baseWorkflows.map((b) => [b.meta.key, b]));
|
|
261
|
+
const createWorkflowExtensionTool = tool({
|
|
262
|
+
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.",
|
|
263
|
+
inputSchema: WorkflowExtensionInputSchema,
|
|
264
|
+
execute: async (input) => {
|
|
265
|
+
const extension = {
|
|
266
|
+
workflow: input.workflow,
|
|
267
|
+
tenantId: input.tenantId,
|
|
268
|
+
role: input.role,
|
|
269
|
+
priority: input.priority,
|
|
270
|
+
customSteps: input.customSteps,
|
|
271
|
+
hiddenSteps: input.hiddenSteps
|
|
272
|
+
};
|
|
273
|
+
const base = baseByKey.get(input.workflow);
|
|
274
|
+
if (!base) {
|
|
275
|
+
return {
|
|
276
|
+
success: false,
|
|
277
|
+
error: `Base workflow "${input.workflow}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
|
|
278
|
+
extension
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
validateExtension(extension, base);
|
|
283
|
+
return {
|
|
284
|
+
success: true,
|
|
285
|
+
message: "Extension validated successfully",
|
|
286
|
+
extension
|
|
287
|
+
};
|
|
288
|
+
} catch (err) {
|
|
289
|
+
return {
|
|
290
|
+
success: false,
|
|
291
|
+
error: err instanceof Error ? err.message : String(err),
|
|
292
|
+
extension
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
const composeWorkflowInputSchema = z.object({
|
|
298
|
+
workflowKey: z.string().describe("Base workflow meta.key"),
|
|
299
|
+
tenantId: z.string().optional(),
|
|
300
|
+
role: z.string().optional(),
|
|
301
|
+
extensions: z.array(WorkflowExtensionInputSchema).optional().describe("Extensions to register before composing")
|
|
302
|
+
});
|
|
303
|
+
const composeWorkflowTool = tool({
|
|
304
|
+
description: "Compose a workflow by applying registered extensions to a base workflow. Returns the composed WorkflowSpec.",
|
|
305
|
+
inputSchema: composeWorkflowInputSchema,
|
|
306
|
+
execute: async (input) => {
|
|
307
|
+
const base = baseByKey.get(input.workflowKey);
|
|
308
|
+
if (!base) {
|
|
309
|
+
return {
|
|
310
|
+
success: false,
|
|
311
|
+
error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
const comp = composer ?? new WorkflowComposer;
|
|
315
|
+
if (input.extensions?.length) {
|
|
316
|
+
for (const ext of input.extensions) {
|
|
317
|
+
comp.register({
|
|
318
|
+
workflow: ext.workflow,
|
|
319
|
+
tenantId: ext.tenantId,
|
|
320
|
+
role: ext.role,
|
|
321
|
+
priority: ext.priority,
|
|
322
|
+
customSteps: ext.customSteps,
|
|
323
|
+
hiddenSteps: ext.hiddenSteps
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
const composed = comp.compose({
|
|
329
|
+
base,
|
|
330
|
+
tenantId: input.tenantId,
|
|
331
|
+
role: input.role
|
|
332
|
+
});
|
|
333
|
+
return {
|
|
334
|
+
success: true,
|
|
335
|
+
workflow: composed,
|
|
336
|
+
meta: composed.meta,
|
|
337
|
+
stepIds: composed.definition.steps.map((s) => s.id)
|
|
338
|
+
};
|
|
339
|
+
} catch (err) {
|
|
340
|
+
return {
|
|
341
|
+
success: false,
|
|
342
|
+
error: err instanceof Error ? err.message : String(err)
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
const generateWorkflowSpecCodeInputSchema = z.object({
|
|
348
|
+
workflowKey: z.string().describe("Workflow meta.key"),
|
|
349
|
+
composedSteps: z.array(z.object({
|
|
350
|
+
id: z.string(),
|
|
351
|
+
type: z.enum(["human", "automation", "decision"]),
|
|
352
|
+
label: z.string(),
|
|
353
|
+
description: z.string().optional()
|
|
354
|
+
})).optional().describe("Steps to include; if omitted, uses the base workflow")
|
|
355
|
+
});
|
|
356
|
+
const generateWorkflowSpecCodeTool = tool({
|
|
357
|
+
description: "Generate TypeScript code for a workflow spec. Use after composing a workflow to output the spec as code the user can save.",
|
|
358
|
+
inputSchema: generateWorkflowSpecCodeInputSchema,
|
|
359
|
+
execute: async (input) => {
|
|
360
|
+
const base = baseByKey.get(input.workflowKey);
|
|
361
|
+
if (!base) {
|
|
362
|
+
return {
|
|
363
|
+
success: false,
|
|
364
|
+
error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
|
|
365
|
+
code: null
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
const steps = input.composedSteps ?? base.definition.steps;
|
|
369
|
+
const specVarName = toPascalCase((base.meta.key.split(".").pop() ?? "Workflow") + "") + "Workflow";
|
|
370
|
+
const stepsCode = steps.map((s) => ` {
|
|
371
|
+
id: '${s.id}',
|
|
372
|
+
type: '${s.type}',
|
|
373
|
+
label: '${escapeString(s.label)}',${s.description ? `
|
|
374
|
+
description: '${escapeString(s.description)}',` : ""}
|
|
375
|
+
}`).join(`,
|
|
376
|
+
`);
|
|
377
|
+
const meta = base.meta;
|
|
378
|
+
const transitionsJson = JSON.stringify(base.definition.transitions, null, 6);
|
|
379
|
+
const code = `import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow';
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Workflow: ${base.meta.key}
|
|
383
|
+
* Generated via AI chat workflow tools.
|
|
384
|
+
*/
|
|
385
|
+
export const ${specVarName}: WorkflowSpec = {
|
|
386
|
+
meta: {
|
|
387
|
+
key: '${base.meta.key}',
|
|
388
|
+
version: '${String(base.meta.version)}',
|
|
389
|
+
title: '${escapeString(meta.title ?? base.meta.key)}',
|
|
390
|
+
description: '${escapeString(meta.description ?? "")}',
|
|
391
|
+
},
|
|
392
|
+
definition: {
|
|
393
|
+
entryStepId: '${base.definition.entryStepId ?? base.definition.steps[0]?.id ?? ""}',
|
|
394
|
+
steps: [
|
|
395
|
+
${stepsCode}
|
|
396
|
+
],
|
|
397
|
+
transitions: ${transitionsJson},
|
|
398
|
+
},
|
|
399
|
+
};
|
|
400
|
+
`;
|
|
401
|
+
return {
|
|
402
|
+
success: true,
|
|
403
|
+
code,
|
|
404
|
+
workflowKey: input.workflowKey
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
return {
|
|
409
|
+
create_workflow_extension: createWorkflowExtensionTool,
|
|
410
|
+
compose_workflow: composeWorkflowTool,
|
|
411
|
+
generate_workflow_spec_code: generateWorkflowSpecCodeTool
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function toPascalCase(value) {
|
|
415
|
+
return value.split(/[-_.]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
416
|
+
}
|
|
417
|
+
function escapeString(value) {
|
|
418
|
+
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// src/core/contracts-context.ts
|
|
422
|
+
function buildContractsContextPrompt(config) {
|
|
423
|
+
const parts = [];
|
|
424
|
+
if (!config.agentSpecs?.length && !config.dataViewSpecs?.length && !config.formSpecs?.length && !config.presentationSpecs?.length && !config.operationRefs?.length) {
|
|
425
|
+
return "";
|
|
426
|
+
}
|
|
427
|
+
parts.push(`
|
|
428
|
+
|
|
429
|
+
## Available resources`);
|
|
430
|
+
if (config.agentSpecs?.length) {
|
|
431
|
+
parts.push(`
|
|
432
|
+
### Agent tools`);
|
|
433
|
+
for (const agent of config.agentSpecs) {
|
|
434
|
+
const toolNames = agent.tools?.map((t) => t.name).join(", ") ?? "none";
|
|
435
|
+
parts.push(`- **${agent.key}**: tools: ${toolNames}`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (config.dataViewSpecs?.length) {
|
|
439
|
+
parts.push(`
|
|
440
|
+
### Data views`);
|
|
441
|
+
for (const dv of config.dataViewSpecs) {
|
|
442
|
+
parts.push(`- **${dv.key}**: ${dv.meta.title ?? dv.key}`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (config.formSpecs?.length) {
|
|
446
|
+
parts.push(`
|
|
447
|
+
### Forms`);
|
|
448
|
+
for (const form of config.formSpecs) {
|
|
449
|
+
parts.push(`- **${form.key}**: ${form.meta.title ?? form.key}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (config.presentationSpecs?.length) {
|
|
453
|
+
parts.push(`
|
|
454
|
+
### Presentations`);
|
|
455
|
+
for (const pres of config.presentationSpecs) {
|
|
456
|
+
parts.push(`- **${pres.key}**: ${pres.meta.title ?? pres.key} (targets: ${pres.targets?.join(", ") ?? "react"})`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (config.operationRefs?.length) {
|
|
460
|
+
parts.push(`
|
|
461
|
+
### Operations`);
|
|
462
|
+
for (const op of config.operationRefs) {
|
|
463
|
+
parts.push(`- **${op.key}@${op.version}**`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
parts.push(`
|
|
467
|
+
Use the available tools to invoke operations, query data views, or propose surface changes when appropriate.`);
|
|
468
|
+
return parts.join(`
|
|
469
|
+
`);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// src/core/agent-tools-adapter.ts
|
|
473
|
+
import { tool as tool2 } from "ai";
|
|
474
|
+
import { z as z2 } from "zod";
|
|
475
|
+
function getInputSchema(_schema) {
|
|
476
|
+
return z2.object({}).passthrough();
|
|
477
|
+
}
|
|
478
|
+
function agentToolConfigsToToolSet(configs, handlers) {
|
|
479
|
+
const result = {};
|
|
480
|
+
for (const config of configs) {
|
|
481
|
+
const handler = handlers?.[config.name];
|
|
482
|
+
const inputSchema = getInputSchema(config.schema);
|
|
483
|
+
result[config.name] = tool2({
|
|
484
|
+
description: config.description ?? config.name,
|
|
485
|
+
inputSchema,
|
|
486
|
+
execute: async (input) => {
|
|
487
|
+
if (!handler) {
|
|
488
|
+
return {
|
|
489
|
+
status: "unimplemented",
|
|
490
|
+
message: "Wire handler in host",
|
|
491
|
+
toolName: config.name
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
try {
|
|
495
|
+
const output = await Promise.resolve(handler(input));
|
|
496
|
+
return typeof output === "string" ? output : output;
|
|
497
|
+
} catch (err) {
|
|
498
|
+
return {
|
|
499
|
+
status: "error",
|
|
500
|
+
error: err instanceof Error ? err.message : String(err),
|
|
501
|
+
toolName: config.name
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// src/core/surface-planner-tools.ts
|
|
511
|
+
import { tool as tool3 } from "ai";
|
|
512
|
+
import { z as z3 } from "zod";
|
|
513
|
+
import {
|
|
514
|
+
validatePatchProposal
|
|
515
|
+
} from "@contractspec/lib.surface-runtime/spec/validate-surface-patch";
|
|
516
|
+
import { buildSurfacePatchProposal } from "@contractspec/lib.surface-runtime/runtime/planner-tools";
|
|
517
|
+
var VALID_OPS = [
|
|
518
|
+
"insert-node",
|
|
519
|
+
"replace-node",
|
|
520
|
+
"remove-node",
|
|
521
|
+
"move-node",
|
|
522
|
+
"resize-panel",
|
|
523
|
+
"set-layout",
|
|
524
|
+
"reveal-field",
|
|
525
|
+
"hide-field",
|
|
526
|
+
"promote-action",
|
|
527
|
+
"set-focus"
|
|
528
|
+
];
|
|
529
|
+
var DEFAULT_NODE_KINDS = [
|
|
530
|
+
"entity-section",
|
|
531
|
+
"entity-card",
|
|
532
|
+
"data-view",
|
|
533
|
+
"assistant-panel",
|
|
534
|
+
"chat-thread",
|
|
535
|
+
"action-bar",
|
|
536
|
+
"timeline",
|
|
537
|
+
"table",
|
|
538
|
+
"rich-doc",
|
|
539
|
+
"form",
|
|
540
|
+
"chart",
|
|
541
|
+
"custom-widget"
|
|
542
|
+
];
|
|
543
|
+
function collectSlotIdsFromRegion(node) {
|
|
544
|
+
const ids = [];
|
|
545
|
+
if (node.type === "slot") {
|
|
546
|
+
ids.push(node.slotId);
|
|
547
|
+
}
|
|
548
|
+
if (node.type === "panel-group" || node.type === "stack") {
|
|
549
|
+
for (const child of node.children) {
|
|
550
|
+
ids.push(...collectSlotIdsFromRegion(child));
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (node.type === "tabs") {
|
|
554
|
+
for (const tab of node.tabs) {
|
|
555
|
+
ids.push(...collectSlotIdsFromRegion(tab.child));
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
if (node.type === "floating") {
|
|
559
|
+
ids.push(node.anchorSlotId);
|
|
560
|
+
ids.push(...collectSlotIdsFromRegion(node.child));
|
|
561
|
+
}
|
|
562
|
+
return ids;
|
|
563
|
+
}
|
|
564
|
+
function deriveConstraints(plan) {
|
|
565
|
+
const slotIds = collectSlotIdsFromRegion(plan.layoutRoot);
|
|
566
|
+
const uniqueSlots = [...new Set(slotIds)];
|
|
567
|
+
return {
|
|
568
|
+
allowedOps: VALID_OPS,
|
|
569
|
+
allowedSlots: uniqueSlots.length > 0 ? uniqueSlots : ["assistant", "primary"],
|
|
570
|
+
allowedNodeKinds: DEFAULT_NODE_KINDS
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
var ProposePatchInputSchema = z3.object({
|
|
574
|
+
proposalId: z3.string().describe("Unique proposal identifier"),
|
|
575
|
+
ops: z3.array(z3.object({
|
|
576
|
+
op: z3.enum([
|
|
577
|
+
"insert-node",
|
|
578
|
+
"replace-node",
|
|
579
|
+
"remove-node",
|
|
580
|
+
"move-node",
|
|
581
|
+
"resize-panel",
|
|
582
|
+
"set-layout",
|
|
583
|
+
"reveal-field",
|
|
584
|
+
"hide-field",
|
|
585
|
+
"promote-action",
|
|
586
|
+
"set-focus"
|
|
587
|
+
]),
|
|
588
|
+
slotId: z3.string().optional(),
|
|
589
|
+
nodeId: z3.string().optional(),
|
|
590
|
+
toSlotId: z3.string().optional(),
|
|
591
|
+
index: z3.number().optional(),
|
|
592
|
+
node: z3.object({
|
|
593
|
+
nodeId: z3.string(),
|
|
594
|
+
kind: z3.string(),
|
|
595
|
+
title: z3.string().optional(),
|
|
596
|
+
props: z3.record(z3.string(), z3.unknown()).optional(),
|
|
597
|
+
children: z3.array(z3.unknown()).optional()
|
|
598
|
+
}).optional(),
|
|
599
|
+
persistKey: z3.string().optional(),
|
|
600
|
+
sizes: z3.array(z3.number()).optional(),
|
|
601
|
+
layoutId: z3.string().optional(),
|
|
602
|
+
fieldId: z3.string().optional(),
|
|
603
|
+
actionId: z3.string().optional(),
|
|
604
|
+
placement: z3.enum(["header", "inline", "context", "assistant"]).optional(),
|
|
605
|
+
targetId: z3.string().optional()
|
|
606
|
+
}))
|
|
607
|
+
});
|
|
608
|
+
function createSurfacePlannerTools(config) {
|
|
609
|
+
const { plan, constraints, onPatchProposal } = config;
|
|
610
|
+
const resolvedConstraints = constraints ?? deriveConstraints(plan);
|
|
611
|
+
const proposePatchTool = tool3({
|
|
612
|
+
description: "Propose surface patches (layout changes, node insertions, etc.) for user approval. " + "Only use allowed ops, slots, and node kinds from the planner context.",
|
|
613
|
+
inputSchema: ProposePatchInputSchema,
|
|
614
|
+
execute: async (input) => {
|
|
615
|
+
const ops = input.ops;
|
|
616
|
+
try {
|
|
617
|
+
validatePatchProposal(ops, resolvedConstraints);
|
|
618
|
+
const proposal = buildSurfacePatchProposal(input.proposalId, ops);
|
|
619
|
+
onPatchProposal?.(proposal);
|
|
620
|
+
return {
|
|
621
|
+
success: true,
|
|
622
|
+
proposalId: proposal.proposalId,
|
|
623
|
+
opsCount: proposal.ops.length,
|
|
624
|
+
message: "Patch proposal validated; awaiting user approval"
|
|
625
|
+
};
|
|
626
|
+
} catch (err) {
|
|
627
|
+
return {
|
|
628
|
+
success: false,
|
|
629
|
+
error: err instanceof Error ? err.message : String(err),
|
|
630
|
+
proposalId: input.proposalId
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
return {
|
|
636
|
+
"propose-patch": proposePatchTool
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
function buildPlannerPromptInput(plan) {
|
|
640
|
+
const constraints = deriveConstraints(plan);
|
|
641
|
+
return {
|
|
642
|
+
bundleMeta: {
|
|
643
|
+
key: plan.bundleKey,
|
|
644
|
+
version: "0.0.0",
|
|
645
|
+
title: plan.bundleKey
|
|
646
|
+
},
|
|
647
|
+
surfaceId: plan.surfaceId,
|
|
648
|
+
allowedPatchOps: constraints.allowedOps,
|
|
649
|
+
allowedSlots: [...constraints.allowedSlots],
|
|
650
|
+
allowedNodeKinds: [...constraints.allowedNodeKinds],
|
|
651
|
+
actions: plan.actions.map((a) => ({
|
|
652
|
+
actionId: a.actionId,
|
|
653
|
+
title: a.title
|
|
654
|
+
})),
|
|
655
|
+
preferences: {
|
|
656
|
+
guidance: "hints",
|
|
657
|
+
density: "standard",
|
|
658
|
+
dataDepth: "detailed",
|
|
659
|
+
control: "standard",
|
|
660
|
+
media: "text",
|
|
661
|
+
pace: "balanced",
|
|
662
|
+
narrative: "top-down"
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// src/core/chat-service.ts
|
|
668
|
+
import { compilePlannerPrompt } from "@contractspec/lib.surface-runtime/runtime/planner-prompt";
|
|
111
669
|
var DEFAULT_SYSTEM_PROMPT = `You are ContractSpec AI, an expert coding assistant specialized in ContractSpec development.
|
|
112
670
|
|
|
113
671
|
Your capabilities:
|
|
@@ -122,6 +680,9 @@ Guidelines:
|
|
|
122
680
|
- Reference relevant ContractSpec concepts and patterns
|
|
123
681
|
- Ask clarifying questions when the user's intent is unclear
|
|
124
682
|
- When suggesting code changes, explain the rationale`;
|
|
683
|
+
var WORKFLOW_TOOLS_PROMPT = `
|
|
684
|
+
|
|
685
|
+
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.`;
|
|
125
686
|
|
|
126
687
|
class ChatService {
|
|
127
688
|
provider;
|
|
@@ -131,19 +692,93 @@ class ChatService {
|
|
|
131
692
|
maxHistoryMessages;
|
|
132
693
|
onUsage;
|
|
133
694
|
tools;
|
|
695
|
+
thinkingLevel;
|
|
134
696
|
sendReasoning;
|
|
135
697
|
sendSources;
|
|
698
|
+
modelSelector;
|
|
136
699
|
constructor(config) {
|
|
137
700
|
this.provider = config.provider;
|
|
138
701
|
this.context = config.context;
|
|
139
702
|
this.store = config.store ?? new InMemoryConversationStore;
|
|
140
|
-
this.systemPrompt = config
|
|
703
|
+
this.systemPrompt = this.buildSystemPrompt(config);
|
|
141
704
|
this.maxHistoryMessages = config.maxHistoryMessages ?? 20;
|
|
142
705
|
this.onUsage = config.onUsage;
|
|
143
|
-
this.tools = config
|
|
144
|
-
this.
|
|
706
|
+
this.tools = this.mergeTools(config);
|
|
707
|
+
this.thinkingLevel = config.thinkingLevel;
|
|
708
|
+
this.modelSelector = config.modelSelector;
|
|
709
|
+
this.sendReasoning = config.sendReasoning ?? (config.thinkingLevel != null && config.thinkingLevel !== "instant");
|
|
145
710
|
this.sendSources = config.sendSources ?? false;
|
|
146
711
|
}
|
|
712
|
+
buildSystemPrompt(config) {
|
|
713
|
+
let base = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
|
|
714
|
+
if (config.workflowToolsConfig?.baseWorkflows?.length) {
|
|
715
|
+
base += WORKFLOW_TOOLS_PROMPT;
|
|
716
|
+
}
|
|
717
|
+
const contractsPrompt = buildContractsContextPrompt(config.contractsContext ?? {});
|
|
718
|
+
if (contractsPrompt) {
|
|
719
|
+
base += contractsPrompt;
|
|
720
|
+
}
|
|
721
|
+
if (config.surfacePlanConfig?.plan) {
|
|
722
|
+
const plannerInput = buildPlannerPromptInput(config.surfacePlanConfig.plan);
|
|
723
|
+
base += `
|
|
724
|
+
|
|
725
|
+
` + compilePlannerPrompt(plannerInput);
|
|
726
|
+
}
|
|
727
|
+
return base;
|
|
728
|
+
}
|
|
729
|
+
mergeTools(config) {
|
|
730
|
+
let merged = config.tools ?? {};
|
|
731
|
+
const wfConfig = config.workflowToolsConfig;
|
|
732
|
+
if (wfConfig?.baseWorkflows?.length) {
|
|
733
|
+
const workflowTools = createWorkflowTools({
|
|
734
|
+
baseWorkflows: wfConfig.baseWorkflows,
|
|
735
|
+
composer: wfConfig.composer
|
|
736
|
+
});
|
|
737
|
+
merged = { ...merged, ...workflowTools };
|
|
738
|
+
}
|
|
739
|
+
const contractsCtx = config.contractsContext;
|
|
740
|
+
if (contractsCtx?.agentSpecs?.length) {
|
|
741
|
+
const allTools = [];
|
|
742
|
+
for (const agent of contractsCtx.agentSpecs) {
|
|
743
|
+
if (agent.tools?.length)
|
|
744
|
+
allTools.push(...agent.tools);
|
|
745
|
+
}
|
|
746
|
+
if (allTools.length > 0) {
|
|
747
|
+
const agentTools = agentToolConfigsToToolSet(allTools);
|
|
748
|
+
merged = { ...merged, ...agentTools };
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const surfaceConfig = config.surfacePlanConfig;
|
|
752
|
+
if (surfaceConfig?.plan) {
|
|
753
|
+
const plannerTools = createSurfacePlannerTools({
|
|
754
|
+
plan: surfaceConfig.plan,
|
|
755
|
+
onPatchProposal: surfaceConfig.onPatchProposal
|
|
756
|
+
});
|
|
757
|
+
merged = { ...merged, ...plannerTools };
|
|
758
|
+
}
|
|
759
|
+
if (config.mcpTools && Object.keys(config.mcpTools).length > 0) {
|
|
760
|
+
merged = { ...merged, ...config.mcpTools };
|
|
761
|
+
}
|
|
762
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
763
|
+
}
|
|
764
|
+
async resolveModel() {
|
|
765
|
+
if (this.modelSelector) {
|
|
766
|
+
const dimension = this.thinkingLevelToDimension(this.thinkingLevel);
|
|
767
|
+
const { model, selection } = await this.modelSelector.selectAndCreate({
|
|
768
|
+
taskDimension: dimension
|
|
769
|
+
});
|
|
770
|
+
return { model, providerName: selection.providerKey };
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
model: this.provider.getModel(),
|
|
774
|
+
providerName: this.provider.name
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
thinkingLevelToDimension(level) {
|
|
778
|
+
if (!level || level === "instant")
|
|
779
|
+
return "latency";
|
|
780
|
+
return "reasoning";
|
|
781
|
+
}
|
|
147
782
|
async send(options) {
|
|
148
783
|
let conversation;
|
|
149
784
|
if (options.conversationId) {
|
|
@@ -161,20 +796,25 @@ class ChatService {
|
|
|
161
796
|
workspacePath: this.context?.workspacePath
|
|
162
797
|
});
|
|
163
798
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
799
|
+
if (!options.skipUserAppend) {
|
|
800
|
+
await this.store.appendMessage(conversation.id, {
|
|
801
|
+
role: "user",
|
|
802
|
+
content: options.content,
|
|
803
|
+
status: "completed",
|
|
804
|
+
attachments: options.attachments
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
conversation = await this.store.get(conversation.id) ?? conversation;
|
|
170
808
|
const messages = this.buildMessages(conversation, options);
|
|
171
|
-
const model = this.
|
|
809
|
+
const { model, providerName } = await this.resolveModel();
|
|
810
|
+
const providerOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
172
811
|
try {
|
|
173
812
|
const result = await generateText({
|
|
174
813
|
model,
|
|
175
814
|
messages,
|
|
176
815
|
system: this.systemPrompt,
|
|
177
|
-
tools: this.tools
|
|
816
|
+
tools: this.tools,
|
|
817
|
+
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
|
|
178
818
|
});
|
|
179
819
|
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
180
820
|
role: "assistant",
|
|
@@ -219,23 +859,27 @@ class ChatService {
|
|
|
219
859
|
workspacePath: this.context?.workspacePath
|
|
220
860
|
});
|
|
221
861
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
862
|
+
if (!options.skipUserAppend) {
|
|
863
|
+
await this.store.appendMessage(conversation.id, {
|
|
864
|
+
role: "user",
|
|
865
|
+
content: options.content,
|
|
866
|
+
status: "completed",
|
|
867
|
+
attachments: options.attachments
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
conversation = await this.store.get(conversation.id) ?? conversation;
|
|
228
871
|
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
229
872
|
role: "assistant",
|
|
230
873
|
content: "",
|
|
231
874
|
status: "streaming"
|
|
232
875
|
});
|
|
233
876
|
const messages = this.buildMessages(conversation, options);
|
|
234
|
-
const model = this.
|
|
877
|
+
const { model, providerName } = await this.resolveModel();
|
|
235
878
|
const systemPrompt = this.systemPrompt;
|
|
236
879
|
const tools = this.tools;
|
|
237
880
|
const store = this.store;
|
|
238
881
|
const onUsage = this.onUsage;
|
|
882
|
+
const streamProviderOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
239
883
|
async function* streamGenerator() {
|
|
240
884
|
let fullContent = "";
|
|
241
885
|
let fullReasoning = "";
|
|
@@ -246,7 +890,8 @@ class ChatService {
|
|
|
246
890
|
model,
|
|
247
891
|
messages,
|
|
248
892
|
system: systemPrompt,
|
|
249
|
-
tools
|
|
893
|
+
tools,
|
|
894
|
+
providerOptions: Object.keys(streamProviderOptions).length > 0 ? streamProviderOptions : undefined
|
|
250
895
|
});
|
|
251
896
|
for await (const part of result.fullStream) {
|
|
252
897
|
if (part.type === "text-delta") {
|
|
@@ -361,6 +1006,18 @@ class ChatService {
|
|
|
361
1006
|
...options
|
|
362
1007
|
});
|
|
363
1008
|
}
|
|
1009
|
+
async updateConversation(conversationId, updates) {
|
|
1010
|
+
return this.store.update(conversationId, updates);
|
|
1011
|
+
}
|
|
1012
|
+
async forkConversation(conversationId, upToMessageId) {
|
|
1013
|
+
return this.store.fork(conversationId, upToMessageId);
|
|
1014
|
+
}
|
|
1015
|
+
async updateMessage(conversationId, messageId, updates) {
|
|
1016
|
+
return this.store.updateMessage(conversationId, messageId, updates);
|
|
1017
|
+
}
|
|
1018
|
+
async truncateAfter(conversationId, messageId) {
|
|
1019
|
+
return this.store.truncateAfter(conversationId, messageId);
|
|
1020
|
+
}
|
|
364
1021
|
async deleteConversation(conversationId) {
|
|
365
1022
|
return this.store.delete(conversationId);
|
|
366
1023
|
}
|
|
@@ -429,7 +1086,12 @@ import {
|
|
|
429
1086
|
} from "ai";
|
|
430
1087
|
var DEFAULT_SYSTEM_PROMPT2 = `You are a helpful AI assistant.`;
|
|
431
1088
|
function createChatRoute(options) {
|
|
432
|
-
const {
|
|
1089
|
+
const {
|
|
1090
|
+
provider,
|
|
1091
|
+
systemPrompt = DEFAULT_SYSTEM_PROMPT2,
|
|
1092
|
+
tools,
|
|
1093
|
+
thinkingLevel: defaultThinkingLevel
|
|
1094
|
+
} = options;
|
|
433
1095
|
return async (req) => {
|
|
434
1096
|
if (req.method !== "POST") {
|
|
435
1097
|
return new Response("Method not allowed", { status: 405 });
|
|
@@ -444,12 +1106,15 @@ function createChatRoute(options) {
|
|
|
444
1106
|
if (!Array.isArray(messages) || messages.length === 0) {
|
|
445
1107
|
return new Response("messages array required", { status: 400 });
|
|
446
1108
|
}
|
|
1109
|
+
const thinkingLevel = body.thinkingLevel ?? defaultThinkingLevel;
|
|
1110
|
+
const providerOptions = getProviderOptions(thinkingLevel, provider.name);
|
|
447
1111
|
const model = provider.getModel();
|
|
448
1112
|
const result = streamText2({
|
|
449
1113
|
model,
|
|
450
1114
|
messages: await convertToModelMessages(messages),
|
|
451
1115
|
system: systemPrompt,
|
|
452
|
-
tools
|
|
1116
|
+
tools,
|
|
1117
|
+
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
|
|
453
1118
|
});
|
|
454
1119
|
return result.toUIMessageStreamResponse();
|
|
455
1120
|
};
|
|
@@ -481,11 +1146,468 @@ function createCompletionRoute(options) {
|
|
|
481
1146
|
return result.toTextStreamResponse();
|
|
482
1147
|
};
|
|
483
1148
|
}
|
|
1149
|
+
// src/core/export-formatters.ts
|
|
1150
|
+
function formatTimestamp(date) {
|
|
1151
|
+
return date.toLocaleTimeString([], {
|
|
1152
|
+
hour: "2-digit",
|
|
1153
|
+
minute: "2-digit"
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
function toIsoString(date) {
|
|
1157
|
+
return date.toISOString();
|
|
1158
|
+
}
|
|
1159
|
+
function messageToJsonSerializable(msg) {
|
|
1160
|
+
return {
|
|
1161
|
+
id: msg.id,
|
|
1162
|
+
conversationId: msg.conversationId,
|
|
1163
|
+
role: msg.role,
|
|
1164
|
+
content: msg.content,
|
|
1165
|
+
status: msg.status,
|
|
1166
|
+
createdAt: toIsoString(msg.createdAt),
|
|
1167
|
+
updatedAt: toIsoString(msg.updatedAt),
|
|
1168
|
+
...msg.attachments && { attachments: msg.attachments },
|
|
1169
|
+
...msg.codeBlocks && { codeBlocks: msg.codeBlocks },
|
|
1170
|
+
...msg.toolCalls && { toolCalls: msg.toolCalls },
|
|
1171
|
+
...msg.sources && { sources: msg.sources },
|
|
1172
|
+
...msg.reasoning && { reasoning: msg.reasoning },
|
|
1173
|
+
...msg.usage && { usage: msg.usage },
|
|
1174
|
+
...msg.error && { error: msg.error },
|
|
1175
|
+
...msg.metadata && { metadata: msg.metadata }
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
function formatSourcesMarkdown(sources) {
|
|
1179
|
+
if (sources.length === 0)
|
|
1180
|
+
return "";
|
|
1181
|
+
return `
|
|
1182
|
+
|
|
1183
|
+
**Sources:**
|
|
1184
|
+
` + sources.map((s) => `- [${s.title}](${s.url ?? "#"})`).join(`
|
|
1185
|
+
`);
|
|
1186
|
+
}
|
|
1187
|
+
function formatSourcesTxt(sources) {
|
|
1188
|
+
if (sources.length === 0)
|
|
1189
|
+
return "";
|
|
1190
|
+
return `
|
|
1191
|
+
|
|
1192
|
+
Sources:
|
|
1193
|
+
` + sources.map((s) => `- ${s.title}${s.url ? ` - ${s.url}` : ""}`).join(`
|
|
1194
|
+
`);
|
|
1195
|
+
}
|
|
1196
|
+
function formatToolCallsMarkdown(toolCalls) {
|
|
1197
|
+
if (toolCalls.length === 0)
|
|
1198
|
+
return "";
|
|
1199
|
+
return `
|
|
1200
|
+
|
|
1201
|
+
**Tool calls:**
|
|
1202
|
+
` + toolCalls.map((tc) => `**${tc.name}** (${tc.status})
|
|
1203
|
+
\`\`\`json
|
|
1204
|
+
${JSON.stringify(tc.args, null, 2)}
|
|
1205
|
+
\`\`\`` + (tc.result !== undefined ? `
|
|
1206
|
+
Output:
|
|
1207
|
+
\`\`\`json
|
|
1208
|
+
${typeof tc.result === "object" ? JSON.stringify(tc.result, null, 2) : String(tc.result)}
|
|
1209
|
+
\`\`\`` : "") + (tc.error ? `
|
|
1210
|
+
Error: ${tc.error}` : "")).join(`
|
|
1211
|
+
|
|
1212
|
+
`);
|
|
1213
|
+
}
|
|
1214
|
+
function formatToolCallsTxt(toolCalls) {
|
|
1215
|
+
if (toolCalls.length === 0)
|
|
1216
|
+
return "";
|
|
1217
|
+
return `
|
|
1218
|
+
|
|
1219
|
+
Tool calls:
|
|
1220
|
+
` + toolCalls.map((tc) => `- ${tc.name} (${tc.status}): ${JSON.stringify(tc.args)}` + (tc.result !== undefined ? ` -> ${typeof tc.result === "object" ? JSON.stringify(tc.result) : String(tc.result)}` : "") + (tc.error ? ` [Error: ${tc.error}]` : "")).join(`
|
|
1221
|
+
`);
|
|
1222
|
+
}
|
|
1223
|
+
function formatUsage(usage) {
|
|
1224
|
+
const total = usage.inputTokens + usage.outputTokens;
|
|
1225
|
+
return ` (${total} tokens)`;
|
|
1226
|
+
}
|
|
1227
|
+
function formatMessagesAsMarkdown(messages) {
|
|
1228
|
+
const parts = [];
|
|
1229
|
+
for (const msg of messages) {
|
|
1230
|
+
const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
|
|
1231
|
+
const header = `## ${roleLabel}`;
|
|
1232
|
+
const timestamp = `*${formatTimestamp(msg.createdAt)}*`;
|
|
1233
|
+
const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
|
|
1234
|
+
const meta = `${timestamp}${usageSuffix}
|
|
1235
|
+
|
|
1236
|
+
`;
|
|
1237
|
+
let body = msg.content;
|
|
1238
|
+
if (msg.error) {
|
|
1239
|
+
body += `
|
|
1240
|
+
|
|
1241
|
+
**Error:** ${msg.error.code} - ${msg.error.message}`;
|
|
1242
|
+
}
|
|
1243
|
+
if (msg.reasoning) {
|
|
1244
|
+
body += `
|
|
1245
|
+
|
|
1246
|
+
> **Reasoning:**
|
|
1247
|
+
> ${msg.reasoning.replace(/\n/g, `
|
|
1248
|
+
> `)}`;
|
|
1249
|
+
}
|
|
1250
|
+
body += formatSourcesMarkdown(msg.sources ?? []);
|
|
1251
|
+
body += formatToolCallsMarkdown(msg.toolCalls ?? []);
|
|
1252
|
+
parts.push(`${header}
|
|
1253
|
+
|
|
1254
|
+
${meta}${body}`);
|
|
1255
|
+
}
|
|
1256
|
+
return parts.join(`
|
|
1257
|
+
|
|
1258
|
+
---
|
|
1259
|
+
|
|
1260
|
+
`);
|
|
1261
|
+
}
|
|
1262
|
+
function formatMessagesAsTxt(messages) {
|
|
1263
|
+
const parts = [];
|
|
1264
|
+
for (const msg of messages) {
|
|
1265
|
+
const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
|
|
1266
|
+
const timestamp = `(${formatTimestamp(msg.createdAt)})`;
|
|
1267
|
+
const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
|
|
1268
|
+
const header = `[${roleLabel}] ${timestamp}${usageSuffix}
|
|
1269
|
+
|
|
1270
|
+
`;
|
|
1271
|
+
let body = msg.content;
|
|
1272
|
+
if (msg.error) {
|
|
1273
|
+
body += `
|
|
1274
|
+
|
|
1275
|
+
Error: ${msg.error.code} - ${msg.error.message}`;
|
|
1276
|
+
}
|
|
1277
|
+
if (msg.reasoning) {
|
|
1278
|
+
body += `
|
|
1279
|
+
|
|
1280
|
+
Reasoning: ${msg.reasoning}`;
|
|
1281
|
+
}
|
|
1282
|
+
body += formatSourcesTxt(msg.sources ?? []);
|
|
1283
|
+
body += formatToolCallsTxt(msg.toolCalls ?? []);
|
|
1284
|
+
parts.push(`${header}${body}`);
|
|
1285
|
+
}
|
|
1286
|
+
return parts.join(`
|
|
1287
|
+
|
|
1288
|
+
---
|
|
1289
|
+
|
|
1290
|
+
`);
|
|
1291
|
+
}
|
|
1292
|
+
function formatMessagesAsJson(messages, conversation) {
|
|
1293
|
+
const payload = {
|
|
1294
|
+
messages: messages.map(messageToJsonSerializable)
|
|
1295
|
+
};
|
|
1296
|
+
if (conversation) {
|
|
1297
|
+
payload.conversation = {
|
|
1298
|
+
id: conversation.id,
|
|
1299
|
+
title: conversation.title,
|
|
1300
|
+
status: conversation.status,
|
|
1301
|
+
createdAt: toIsoString(conversation.createdAt),
|
|
1302
|
+
updatedAt: toIsoString(conversation.updatedAt),
|
|
1303
|
+
provider: conversation.provider,
|
|
1304
|
+
model: conversation.model,
|
|
1305
|
+
workspacePath: conversation.workspacePath,
|
|
1306
|
+
contextFiles: conversation.contextFiles,
|
|
1307
|
+
summary: conversation.summary,
|
|
1308
|
+
metadata: conversation.metadata
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
return JSON.stringify(payload, null, 2);
|
|
1312
|
+
}
|
|
1313
|
+
function getExportFilename(format, conversation) {
|
|
1314
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1315
|
+
const base = conversation?.title ? conversation.title.replace(/[^a-zA-Z0-9-_]/g, "_").slice(0, 40) : "chat-export";
|
|
1316
|
+
const ext = format === "markdown" ? "md" : format === "txt" ? "txt" : "json";
|
|
1317
|
+
return `${base}-${timestamp}.${ext}`;
|
|
1318
|
+
}
|
|
1319
|
+
var MIME_TYPES = {
|
|
1320
|
+
markdown: "text/markdown",
|
|
1321
|
+
txt: "text/plain",
|
|
1322
|
+
json: "application/json"
|
|
1323
|
+
};
|
|
1324
|
+
function downloadAsFile(content, filename, mimeType) {
|
|
1325
|
+
const blob = new Blob([content], { type: mimeType });
|
|
1326
|
+
const url = URL.createObjectURL(blob);
|
|
1327
|
+
const a = document.createElement("a");
|
|
1328
|
+
a.href = url;
|
|
1329
|
+
a.download = filename;
|
|
1330
|
+
document.body.appendChild(a);
|
|
1331
|
+
a.click();
|
|
1332
|
+
document.body.removeChild(a);
|
|
1333
|
+
URL.revokeObjectURL(url);
|
|
1334
|
+
}
|
|
1335
|
+
function exportToFile(messages, format, conversation) {
|
|
1336
|
+
let content;
|
|
1337
|
+
if (format === "markdown") {
|
|
1338
|
+
content = formatMessagesAsMarkdown(messages);
|
|
1339
|
+
} else if (format === "txt") {
|
|
1340
|
+
content = formatMessagesAsTxt(messages);
|
|
1341
|
+
} else {
|
|
1342
|
+
content = formatMessagesAsJson(messages, conversation);
|
|
1343
|
+
}
|
|
1344
|
+
const filename = getExportFilename(format, conversation);
|
|
1345
|
+
const mimeType = MIME_TYPES[format];
|
|
1346
|
+
downloadAsFile(content, filename, mimeType);
|
|
1347
|
+
}
|
|
1348
|
+
// src/core/local-storage-conversation-store.ts
|
|
1349
|
+
var DEFAULT_KEY = "contractspec:ai-chat:conversations";
|
|
1350
|
+
function generateId2(prefix) {
|
|
1351
|
+
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
1352
|
+
}
|
|
1353
|
+
function toSerializable(conv) {
|
|
1354
|
+
return {
|
|
1355
|
+
...conv,
|
|
1356
|
+
createdAt: conv.createdAt.toISOString(),
|
|
1357
|
+
updatedAt: conv.updatedAt.toISOString(),
|
|
1358
|
+
messages: conv.messages.map((m) => ({
|
|
1359
|
+
...m,
|
|
1360
|
+
createdAt: m.createdAt.toISOString(),
|
|
1361
|
+
updatedAt: m.updatedAt.toISOString()
|
|
1362
|
+
}))
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
function fromSerializable(raw) {
|
|
1366
|
+
const messages = raw.messages?.map((m) => ({
|
|
1367
|
+
...m,
|
|
1368
|
+
createdAt: new Date(m.createdAt),
|
|
1369
|
+
updatedAt: new Date(m.updatedAt)
|
|
1370
|
+
})) ?? [];
|
|
1371
|
+
return {
|
|
1372
|
+
...raw,
|
|
1373
|
+
createdAt: new Date(raw.createdAt),
|
|
1374
|
+
updatedAt: new Date(raw.updatedAt),
|
|
1375
|
+
messages
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
function loadAll(key) {
|
|
1379
|
+
if (typeof window === "undefined")
|
|
1380
|
+
return new Map;
|
|
1381
|
+
try {
|
|
1382
|
+
const raw = window.localStorage.getItem(key);
|
|
1383
|
+
if (!raw)
|
|
1384
|
+
return new Map;
|
|
1385
|
+
const arr = JSON.parse(raw);
|
|
1386
|
+
const map = new Map;
|
|
1387
|
+
for (const item of arr) {
|
|
1388
|
+
const conv = fromSerializable(item);
|
|
1389
|
+
map.set(conv.id, conv);
|
|
1390
|
+
}
|
|
1391
|
+
return map;
|
|
1392
|
+
} catch {
|
|
1393
|
+
return new Map;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
function saveAll(key, map) {
|
|
1397
|
+
if (typeof window === "undefined")
|
|
1398
|
+
return;
|
|
1399
|
+
try {
|
|
1400
|
+
const arr = Array.from(map.values()).map(toSerializable);
|
|
1401
|
+
window.localStorage.setItem(key, JSON.stringify(arr));
|
|
1402
|
+
} catch {}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
class LocalStorageConversationStore {
|
|
1406
|
+
key;
|
|
1407
|
+
cache = null;
|
|
1408
|
+
constructor(storageKey = DEFAULT_KEY) {
|
|
1409
|
+
this.key = storageKey;
|
|
1410
|
+
}
|
|
1411
|
+
getMap() {
|
|
1412
|
+
if (!this.cache) {
|
|
1413
|
+
this.cache = loadAll(this.key);
|
|
1414
|
+
}
|
|
1415
|
+
return this.cache;
|
|
1416
|
+
}
|
|
1417
|
+
persist() {
|
|
1418
|
+
saveAll(this.key, this.getMap());
|
|
1419
|
+
}
|
|
1420
|
+
async get(conversationId) {
|
|
1421
|
+
return this.getMap().get(conversationId) ?? null;
|
|
1422
|
+
}
|
|
1423
|
+
async create(conversation) {
|
|
1424
|
+
const now = new Date;
|
|
1425
|
+
const full = {
|
|
1426
|
+
...conversation,
|
|
1427
|
+
id: generateId2("conv"),
|
|
1428
|
+
createdAt: now,
|
|
1429
|
+
updatedAt: now
|
|
1430
|
+
};
|
|
1431
|
+
this.getMap().set(full.id, full);
|
|
1432
|
+
this.persist();
|
|
1433
|
+
return full;
|
|
1434
|
+
}
|
|
1435
|
+
async update(conversationId, updates) {
|
|
1436
|
+
const conv = this.getMap().get(conversationId);
|
|
1437
|
+
if (!conv)
|
|
1438
|
+
return null;
|
|
1439
|
+
const updated = {
|
|
1440
|
+
...conv,
|
|
1441
|
+
...updates,
|
|
1442
|
+
updatedAt: new Date
|
|
1443
|
+
};
|
|
1444
|
+
this.getMap().set(conversationId, updated);
|
|
1445
|
+
this.persist();
|
|
1446
|
+
return updated;
|
|
1447
|
+
}
|
|
1448
|
+
async appendMessage(conversationId, message) {
|
|
1449
|
+
const conv = this.getMap().get(conversationId);
|
|
1450
|
+
if (!conv)
|
|
1451
|
+
throw new Error(`Conversation ${conversationId} not found`);
|
|
1452
|
+
const now = new Date;
|
|
1453
|
+
const fullMessage = {
|
|
1454
|
+
...message,
|
|
1455
|
+
id: generateId2("msg"),
|
|
1456
|
+
conversationId,
|
|
1457
|
+
createdAt: now,
|
|
1458
|
+
updatedAt: now
|
|
1459
|
+
};
|
|
1460
|
+
conv.messages.push(fullMessage);
|
|
1461
|
+
conv.updatedAt = now;
|
|
1462
|
+
this.persist();
|
|
1463
|
+
return fullMessage;
|
|
1464
|
+
}
|
|
1465
|
+
async updateMessage(conversationId, messageId, updates) {
|
|
1466
|
+
const conv = this.getMap().get(conversationId);
|
|
1467
|
+
if (!conv)
|
|
1468
|
+
return null;
|
|
1469
|
+
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
1470
|
+
if (idx === -1)
|
|
1471
|
+
return null;
|
|
1472
|
+
const msg = conv.messages[idx];
|
|
1473
|
+
if (!msg)
|
|
1474
|
+
return null;
|
|
1475
|
+
const updated = {
|
|
1476
|
+
...msg,
|
|
1477
|
+
...updates,
|
|
1478
|
+
updatedAt: new Date
|
|
1479
|
+
};
|
|
1480
|
+
conv.messages[idx] = updated;
|
|
1481
|
+
conv.updatedAt = new Date;
|
|
1482
|
+
this.persist();
|
|
1483
|
+
return updated;
|
|
1484
|
+
}
|
|
1485
|
+
async delete(conversationId) {
|
|
1486
|
+
const deleted = this.getMap().delete(conversationId);
|
|
1487
|
+
if (deleted)
|
|
1488
|
+
this.persist();
|
|
1489
|
+
return deleted;
|
|
1490
|
+
}
|
|
1491
|
+
async list(options) {
|
|
1492
|
+
let results = Array.from(this.getMap().values());
|
|
1493
|
+
if (options?.status) {
|
|
1494
|
+
results = results.filter((c) => c.status === options.status);
|
|
1495
|
+
}
|
|
1496
|
+
if (options?.projectId) {
|
|
1497
|
+
results = results.filter((c) => c.projectId === options.projectId);
|
|
1498
|
+
}
|
|
1499
|
+
if (options?.tags && options.tags.length > 0) {
|
|
1500
|
+
const tagSet = new Set(options.tags);
|
|
1501
|
+
results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
|
|
1502
|
+
}
|
|
1503
|
+
results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
1504
|
+
const offset = options?.offset ?? 0;
|
|
1505
|
+
const limit = options?.limit ?? 100;
|
|
1506
|
+
return results.slice(offset, offset + limit);
|
|
1507
|
+
}
|
|
1508
|
+
async fork(conversationId, upToMessageId) {
|
|
1509
|
+
const source = this.getMap().get(conversationId);
|
|
1510
|
+
if (!source)
|
|
1511
|
+
throw new Error(`Conversation ${conversationId} not found`);
|
|
1512
|
+
let messagesToCopy = source.messages;
|
|
1513
|
+
if (upToMessageId) {
|
|
1514
|
+
const idx = source.messages.findIndex((m) => m.id === upToMessageId);
|
|
1515
|
+
if (idx === -1)
|
|
1516
|
+
throw new Error(`Message ${upToMessageId} not found`);
|
|
1517
|
+
messagesToCopy = source.messages.slice(0, idx + 1);
|
|
1518
|
+
}
|
|
1519
|
+
const now = new Date;
|
|
1520
|
+
const forkedMessages = messagesToCopy.map((m) => ({
|
|
1521
|
+
...m,
|
|
1522
|
+
id: generateId2("msg"),
|
|
1523
|
+
conversationId: "",
|
|
1524
|
+
createdAt: new Date(m.createdAt),
|
|
1525
|
+
updatedAt: new Date(m.updatedAt)
|
|
1526
|
+
}));
|
|
1527
|
+
const forked = {
|
|
1528
|
+
...source,
|
|
1529
|
+
id: generateId2("conv"),
|
|
1530
|
+
title: source.title ? `${source.title} (fork)` : undefined,
|
|
1531
|
+
forkedFromId: source.id,
|
|
1532
|
+
createdAt: now,
|
|
1533
|
+
updatedAt: now,
|
|
1534
|
+
messages: forkedMessages
|
|
1535
|
+
};
|
|
1536
|
+
for (const m of forked.messages) {
|
|
1537
|
+
m.conversationId = forked.id;
|
|
1538
|
+
}
|
|
1539
|
+
this.getMap().set(forked.id, forked);
|
|
1540
|
+
this.persist();
|
|
1541
|
+
return forked;
|
|
1542
|
+
}
|
|
1543
|
+
async truncateAfter(conversationId, messageId) {
|
|
1544
|
+
const conv = this.getMap().get(conversationId);
|
|
1545
|
+
if (!conv)
|
|
1546
|
+
return null;
|
|
1547
|
+
const idx = conv.messages.findIndex((m) => m.id === messageId);
|
|
1548
|
+
if (idx === -1)
|
|
1549
|
+
return null;
|
|
1550
|
+
conv.messages = conv.messages.slice(0, idx + 1);
|
|
1551
|
+
conv.updatedAt = new Date;
|
|
1552
|
+
this.persist();
|
|
1553
|
+
return conv;
|
|
1554
|
+
}
|
|
1555
|
+
async search(query, limit = 20) {
|
|
1556
|
+
const lowerQuery = query.toLowerCase();
|
|
1557
|
+
const results = [];
|
|
1558
|
+
for (const conv of this.getMap().values()) {
|
|
1559
|
+
if (conv.title?.toLowerCase().includes(lowerQuery)) {
|
|
1560
|
+
results.push(conv);
|
|
1561
|
+
continue;
|
|
1562
|
+
}
|
|
1563
|
+
if (conv.messages.some((m) => m.content.toLowerCase().includes(lowerQuery))) {
|
|
1564
|
+
results.push(conv);
|
|
1565
|
+
}
|
|
1566
|
+
if (results.length >= limit)
|
|
1567
|
+
break;
|
|
1568
|
+
}
|
|
1569
|
+
return results;
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
function createLocalStorageConversationStore(storageKey) {
|
|
1573
|
+
return new LocalStorageConversationStore(storageKey);
|
|
1574
|
+
}
|
|
1575
|
+
// src/core/agent-adapter.ts
|
|
1576
|
+
function createChatAgentAdapter(agent) {
|
|
1577
|
+
return {
|
|
1578
|
+
async generate({ prompt, signal }) {
|
|
1579
|
+
const result = await agent.generate({ prompt, signal });
|
|
1580
|
+
return {
|
|
1581
|
+
text: result.text,
|
|
1582
|
+
toolCalls: result.toolCalls,
|
|
1583
|
+
toolResults: result.toolResults,
|
|
1584
|
+
usage: result.usage
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
484
1589
|
export {
|
|
1590
|
+
getProviderOptions,
|
|
1591
|
+
getExportFilename,
|
|
1592
|
+
formatMessagesAsTxt,
|
|
1593
|
+
formatMessagesAsMarkdown,
|
|
1594
|
+
formatMessagesAsJson,
|
|
1595
|
+
exportToFile,
|
|
1596
|
+
downloadAsFile,
|
|
1597
|
+
createWorkflowTools,
|
|
1598
|
+
createSurfacePlannerTools,
|
|
1599
|
+
createLocalStorageConversationStore,
|
|
485
1600
|
createInMemoryConversationStore,
|
|
486
1601
|
createCompletionRoute,
|
|
487
1602
|
createChatService,
|
|
488
1603
|
createChatRoute,
|
|
1604
|
+
createChatAgentAdapter,
|
|
1605
|
+
buildPlannerPromptInput,
|
|
1606
|
+
buildContractsContextPrompt,
|
|
1607
|
+
agentToolConfigsToToolSet,
|
|
1608
|
+
THINKING_LEVEL_LABELS,
|
|
1609
|
+
THINKING_LEVEL_DESCRIPTIONS,
|
|
1610
|
+
LocalStorageConversationStore,
|
|
489
1611
|
InMemoryConversationStore,
|
|
490
1612
|
ChatService
|
|
491
1613
|
};
|