@cslug/ai 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/docs/README.md +182 -3
- package/docs/api.md +44 -0
- package/migrations/00000000_000500_cslug_ai.sql +48 -0
- package/package.json +24 -5
- package/src/agent.ts +168 -0
- package/src/ai-eval-command.ts +100 -0
- package/src/ai-provider.ts +187 -0
- package/src/ai-stream.ts +31 -0
- package/src/ai.ts +329 -0
- package/src/budget.ts +103 -0
- package/src/conversation-store.ts +79 -0
- package/src/conversations.ts +251 -0
- package/src/drivers.ts +249 -0
- package/src/embedders.ts +133 -0
- package/src/fake.ts +165 -0
- package/src/index.ts +88 -4
- package/src/mcp-client.ts +154 -0
- package/src/mcp.ts +75 -0
- package/src/model.ts +111 -0
- package/src/search-tools.ts +163 -0
- package/src/sse.ts +35 -0
package/src/model.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** A content block, close to the Anthropic Messages API. `raw` carries a provider's own blocks back unchanged. */
|
|
4
|
+
export type Block =
|
|
5
|
+
| { type: 'text'; text: string }
|
|
6
|
+
| { type: 'tool_use'; id: string; name: string; input: unknown }
|
|
7
|
+
| { type: 'tool_result'; toolUseId: string; content: string; isError?: boolean }
|
|
8
|
+
| { type: 'raw'; value: unknown }
|
|
9
|
+
export type Message = { role: 'user' | 'assistant'; content: Block[] }
|
|
10
|
+
export type ToolSpec = { name: string; description: string; inputSchema: Record<string, unknown> }
|
|
11
|
+
export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
|
|
12
|
+
|
|
13
|
+
export type ModelRequest = {
|
|
14
|
+
model: string
|
|
15
|
+
system: string
|
|
16
|
+
messages: Message[]
|
|
17
|
+
tools: ToolSpec[]
|
|
18
|
+
/** JSON Schema the final answer must follow (structured output). */
|
|
19
|
+
output?: Record<string, unknown>
|
|
20
|
+
maxTokens?: number
|
|
21
|
+
effort?: Effort
|
|
22
|
+
/** Compact a long history server-side where the provider can (Anthropic `compact_20260112`). */
|
|
23
|
+
compact?: boolean
|
|
24
|
+
}
|
|
25
|
+
/** Tokens a model call used; cache reads and writes are counted apart from `inputTokens` (Anthropic). */
|
|
26
|
+
export type Usage = { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number }
|
|
27
|
+
export type ModelResponse = { content: Block[]; stopReason: string; usage: Usage }
|
|
28
|
+
/** While streaming: text as it arrives, then the whole response. */
|
|
29
|
+
export type StreamEvent = { type: 'text'; text: string } | { type: 'done'; response: ModelResponse }
|
|
30
|
+
|
|
31
|
+
/** A model API. Built from `config/ai.ts` → `providers.<name>`. */
|
|
32
|
+
export interface Provider {
|
|
33
|
+
complete(request: ModelRequest): Promise<ModelResponse>
|
|
34
|
+
stream(request: ModelRequest): AsyncIterable<StreamEvent>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The provider declined (a safety refusal). */
|
|
38
|
+
export class AiRefusalError extends CslugError {
|
|
39
|
+
constructor(readonly category?: string) {
|
|
40
|
+
super('ai.refusal', `The model declined the request${category ? ` (${category})` : ''}`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** POST JSON; a non-2xx answer is an `ai.provider` error with the provider's message. */
|
|
45
|
+
export async function postJson(url: string, headers: Record<string, string>, body: unknown): Promise<Response> {
|
|
46
|
+
const res = await fetch(url, {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
49
|
+
body: JSON.stringify(body),
|
|
50
|
+
})
|
|
51
|
+
if (!res.ok)
|
|
52
|
+
throw new CslugError(
|
|
53
|
+
'ai.provider',
|
|
54
|
+
`${new URL(url).host} answered ${res.status}: ${(await res.text()).slice(0, 500)}`,
|
|
55
|
+
)
|
|
56
|
+
return res
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Server-sent events as `{ event, data }`, parsed from a fetch body. */
|
|
60
|
+
export async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncIterable<{ event?: string; data: string }> {
|
|
61
|
+
const decoder = new TextDecoder()
|
|
62
|
+
const reader = body.getReader() // not `for await`: some DOM typings lack ReadableStream's async iterator
|
|
63
|
+
let buffer = ''
|
|
64
|
+
for (let read = await reader.read(); !read.done; read = await reader.read()) {
|
|
65
|
+
buffer += decoder.decode(read.value, { stream: true })
|
|
66
|
+
let end = buffer.indexOf('\n\n')
|
|
67
|
+
while (end >= 0) {
|
|
68
|
+
const frame = buffer.slice(0, end)
|
|
69
|
+
buffer = buffer.slice(end + 2)
|
|
70
|
+
const event = /^event: ?(.*)$/m.exec(frame)?.[1]
|
|
71
|
+
const data = [...frame.matchAll(/^data: ?(.*)$/gm)].map((m) => m[1]).join('\n')
|
|
72
|
+
if (data) yield { event, data }
|
|
73
|
+
end = buffer.indexOf('\n\n')
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const UNSUPPORTED = [
|
|
79
|
+
'minimum',
|
|
80
|
+
'maximum',
|
|
81
|
+
'exclusiveMinimum',
|
|
82
|
+
'exclusiveMaximum',
|
|
83
|
+
'multipleOf',
|
|
84
|
+
'minLength',
|
|
85
|
+
'maxLength',
|
|
86
|
+
'pattern',
|
|
87
|
+
'minItems',
|
|
88
|
+
'maxItems',
|
|
89
|
+
'uniqueItems',
|
|
90
|
+
'$schema',
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A `v` schema's JSON Schema as structured output accepts it: numeric, length and array constraints removed (the
|
|
95
|
+
* `v` schema still checks them on the answer), `additionalProperties: false` on every object.
|
|
96
|
+
*/
|
|
97
|
+
export function modelSchema(schema: object): Record<string, unknown> {
|
|
98
|
+
const clean = (x: unknown): unknown =>
|
|
99
|
+
Array.isArray(x) ? x.map(clean) : x && typeof x === 'object' ? modelSchema(x) : x
|
|
100
|
+
const out: Record<string, unknown> = {}
|
|
101
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
102
|
+
if (UNSUPPORTED.includes(k)) continue
|
|
103
|
+
// under `properties` the keys are field names (a field may be called `pattern`), not keywords
|
|
104
|
+
out[k] =
|
|
105
|
+
k === 'properties' && v && typeof v === 'object'
|
|
106
|
+
? Object.fromEntries(Object.entries(v).map(([name, field]) => [name, clean(field)]))
|
|
107
|
+
: clean(v)
|
|
108
|
+
}
|
|
109
|
+
if (out.type === 'object') out.additionalProperties = false
|
|
110
|
+
return out
|
|
111
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { currentContext, resolve } from '@cslug/core'
|
|
2
|
+
import { v } from '@cslug/validation'
|
|
3
|
+
import type { RunnableTool } from './agent'
|
|
4
|
+
import { Ai } from './ai'
|
|
5
|
+
import type { Message } from './model'
|
|
6
|
+
|
|
7
|
+
/** What the tools use of a `@cslug/search` index (structural: this package does not import search). */
|
|
8
|
+
export type SearchableIndex = {
|
|
9
|
+
readonly name: string
|
|
10
|
+
search(
|
|
11
|
+
term: string,
|
|
12
|
+
options: {
|
|
13
|
+
page?: number
|
|
14
|
+
perPage?: number
|
|
15
|
+
filter?: Record<string, unknown>
|
|
16
|
+
highlight?: { words?: number; fragments?: number }
|
|
17
|
+
},
|
|
18
|
+
): Promise<{
|
|
19
|
+
data: {
|
|
20
|
+
key: string
|
|
21
|
+
title: string
|
|
22
|
+
metadata: Record<string, unknown>
|
|
23
|
+
rank: number
|
|
24
|
+
highlight?: { body: string }
|
|
25
|
+
}[]
|
|
26
|
+
meta: { page: number; total: number; lastPage: number }
|
|
27
|
+
}>
|
|
28
|
+
upsertMany(
|
|
29
|
+
documents: { key: string; title?: string; body?: string; metadata?: Record<string, unknown> }[],
|
|
30
|
+
): Promise<void>
|
|
31
|
+
removeWhere(filter: Record<string, unknown>): Promise<number>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const ENTITIES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"' }
|
|
35
|
+
/** A highlight as plain text for a model: marks dropped, entities decoded. */
|
|
36
|
+
const plain = (html = '') => html.replace(/<\/?mark>/g, '').replace(/&(amp|lt|gt|quot);/g, (e) => ENTITIES[e] ?? e)
|
|
37
|
+
|
|
38
|
+
const searchInput = v.object({
|
|
39
|
+
query: v.string().min(1).max(300).describe('What to look for, in the words of the question'),
|
|
40
|
+
page: v.int().min(1).optional().describe('Result page, from 1'),
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
export type SearchToolOptions = {
|
|
44
|
+
/** The tool's name for the model (default `search_<index>`). */
|
|
45
|
+
name?: string
|
|
46
|
+
/** What the index holds, for the model to know when to search it. */
|
|
47
|
+
description?: string
|
|
48
|
+
/** Results per call (default 5). */
|
|
49
|
+
perPage?: number
|
|
50
|
+
/** Always applied: `{ published: true }`, a tenant… */
|
|
51
|
+
filter?: Record<string, unknown>
|
|
52
|
+
/** Snippet length in words (default 40). */
|
|
53
|
+
words?: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A tool an agent searches an index with: `tools = [searchTool(helpIndex, { description: 'The help center' })]`.
|
|
58
|
+
* The model sends `{ query, page? }` and reads `{ results: [{ key, title, snippet, metadata }], total, page,
|
|
59
|
+
* lastPage }`, snippets in plain text.
|
|
60
|
+
*/
|
|
61
|
+
export function searchTool(index: SearchableIndex, options: SearchToolOptions = {}): RunnableTool {
|
|
62
|
+
const name = options.name ?? `search_${index.name.replace(/[^a-zA-Z0-9_]/g, '_')}`
|
|
63
|
+
return {
|
|
64
|
+
name,
|
|
65
|
+
description: `${options.description ?? `Search the "${index.name}" index`}. Returns the best matches with a snippet each.`,
|
|
66
|
+
input: searchInput,
|
|
67
|
+
async handle(input: never) {
|
|
68
|
+
const { query, page } = input as v.infer<typeof searchInput>
|
|
69
|
+
const found = await index.search(query, {
|
|
70
|
+
page: page ?? 1,
|
|
71
|
+
perPage: options.perPage ?? 5,
|
|
72
|
+
highlight: { words: options.words ?? 40, fragments: 2 },
|
|
73
|
+
...(options.filter ? { filter: options.filter } : {}),
|
|
74
|
+
})
|
|
75
|
+
return {
|
|
76
|
+
results: found.data.map((d) => ({
|
|
77
|
+
key: d.key,
|
|
78
|
+
title: d.title,
|
|
79
|
+
snippet: plain(d.highlight?.body),
|
|
80
|
+
metadata: d.metadata,
|
|
81
|
+
})),
|
|
82
|
+
total: found.meta.total,
|
|
83
|
+
page: found.meta.page,
|
|
84
|
+
lastPage: found.meta.lastPage,
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The conversation a run belongs to (set by `Conversation.send` / `stream` in the ambient context). */
|
|
91
|
+
export type ConversationScope = { id: string; owner: { type: string; id: string } | null }
|
|
92
|
+
export const CONVERSATION_KEY = 'aiConversation'
|
|
93
|
+
export const currentConversation = (): ConversationScope | undefined =>
|
|
94
|
+
currentContext()?.[CONVERSATION_KEY] as ConversationScope | undefined
|
|
95
|
+
|
|
96
|
+
/** The text of a message (its text blocks), or '' for tool rounds and provider blocks. */
|
|
97
|
+
export const messageText = (m: Message) =>
|
|
98
|
+
m.content
|
|
99
|
+
.flatMap((b) => (b.type === 'text' ? [b.text] : []))
|
|
100
|
+
.join('\n')
|
|
101
|
+
.trim()
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Store a turn's text messages in the recall index (`ai.recall`), keyed `<conversation>:<position>`, with the
|
|
105
|
+
* owner in the metadata so recall stays within one owner's conversations.
|
|
106
|
+
*/
|
|
107
|
+
export async function remember(index: SearchableIndex, scope: ConversationScope, after: number, messages: Message[]) {
|
|
108
|
+
if (!scope.owner) return // an unowned conversation is nobody's to recall
|
|
109
|
+
const owner = scope.owner
|
|
110
|
+
const documents = messages.flatMap((m, i) => {
|
|
111
|
+
const body = messageText(m)
|
|
112
|
+
return body
|
|
113
|
+
? [
|
|
114
|
+
{
|
|
115
|
+
key: `${scope.id}:${after + i}`,
|
|
116
|
+
body,
|
|
117
|
+
metadata: { ownerType: owner.type, ownerId: owner.id, conversationId: scope.id, role: m.role },
|
|
118
|
+
},
|
|
119
|
+
]
|
|
120
|
+
: []
|
|
121
|
+
})
|
|
122
|
+
if (documents.length) await index.upsertMany(documents)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const recallInput = v.object({
|
|
126
|
+
query: v.string().min(1).max(300).describe('What the user said or was told before, in their words'),
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A tool for a stored conversation's agent to look up what the same owner said in their earlier conversations
|
|
131
|
+
* (needs `ai.recall`). It only ever searches the current conversation's owner, never the model's choice.
|
|
132
|
+
*/
|
|
133
|
+
export function recallTool(options: { perPage?: number } = {}): RunnableTool {
|
|
134
|
+
return {
|
|
135
|
+
name: 'recall_conversations',
|
|
136
|
+
description:
|
|
137
|
+
"Search this user's earlier conversations (not the current one) for something they said or were told. " +
|
|
138
|
+
'Returns matching messages with their role and conversation.',
|
|
139
|
+
input: recallInput,
|
|
140
|
+
async handle(input: never) {
|
|
141
|
+
const { query } = input as v.infer<typeof recallInput>
|
|
142
|
+
const scope = currentConversation()
|
|
143
|
+
const recall = resolve(Ai).recallIndex
|
|
144
|
+
if (!recall) return 'Recall is not enabled (ai.recall).'
|
|
145
|
+
if (!scope?.owner) return 'There is no earlier conversation to search: this conversation has no owner.'
|
|
146
|
+
const perPage = options.perPage ?? 5
|
|
147
|
+
const found = await recall.search(query, {
|
|
148
|
+
perPage: perPage * 2,
|
|
149
|
+
filter: { ownerType: scope.owner.type, ownerId: scope.owner.id },
|
|
150
|
+
highlight: { words: 60, fragments: 0 }, // the message from its start: messages are short
|
|
151
|
+
})
|
|
152
|
+
const results = found.data
|
|
153
|
+
.filter((d) => d.metadata.conversationId !== scope.id)
|
|
154
|
+
.slice(0, perPage)
|
|
155
|
+
.map((d) => ({
|
|
156
|
+
conversationId: d.metadata.conversationId,
|
|
157
|
+
role: d.metadata.role,
|
|
158
|
+
text: plain(d.highlight?.body),
|
|
159
|
+
}))
|
|
160
|
+
return { results }
|
|
161
|
+
},
|
|
162
|
+
}
|
|
163
|
+
}
|
package/src/sse.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { currentContext, runInContext } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Stream text to the browser as server-sent events: `return sse(this.assistant.stream({ input }))`. Each piece of
|
|
5
|
+
* text is a `data:` line (JSON string); the end is `event: done`, a failure `event: error`. The stream keeps the
|
|
6
|
+
* request's context (user, scope) while the model answers.
|
|
7
|
+
*/
|
|
8
|
+
export function sse(text: AsyncIterable<string>) {
|
|
9
|
+
const context = currentContext()
|
|
10
|
+
const encoder = new TextEncoder()
|
|
11
|
+
const iterator = text[Symbol.asyncIterator]()
|
|
12
|
+
const next = () => (context ? runInContext(context, () => iterator.next()) : iterator.next())
|
|
13
|
+
return {
|
|
14
|
+
toResponse: () =>
|
|
15
|
+
new Response(
|
|
16
|
+
new ReadableStream<Uint8Array>({
|
|
17
|
+
async pull(controller) {
|
|
18
|
+
try {
|
|
19
|
+
const { value, done } = await next()
|
|
20
|
+
if (done) {
|
|
21
|
+
controller.enqueue(encoder.encode('event: done\ndata: {}\n\n'))
|
|
22
|
+
controller.close()
|
|
23
|
+
} else controller.enqueue(encoder.encode(`data: ${JSON.stringify(value)}\n\n`))
|
|
24
|
+
} catch (error) {
|
|
25
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
26
|
+
controller.enqueue(encoder.encode(`event: error\ndata: ${JSON.stringify({ message })}\n\n`))
|
|
27
|
+
controller.close()
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
cancel: () => void iterator.return?.(),
|
|
31
|
+
}),
|
|
32
|
+
{ headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' } },
|
|
33
|
+
),
|
|
34
|
+
}
|
|
35
|
+
}
|