@anvia/core 0.12.8 → 0.13.1
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/agent/index.d.ts +11 -11
- package/dist/agent/index.js +10 -11
- package/dist/{agent-BB9vVH6P.d.ts → agent-3qSfIKIj.d.ts} +8 -7
- package/dist/audio-generation/index.d.ts +1 -1
- package/dist/{chunk-NPZDYOE6.js → chunk-2ODTMRHP.js} +11 -10
- package/dist/chunk-2ODTMRHP.js.map +1 -0
- package/dist/{chunk-IN5NPAWL.js → chunk-CLFDBOH3.js} +6 -6
- package/dist/{chunk-QVFOCNF6.js → chunk-CNTGKNZ3.js} +99 -10
- package/dist/chunk-CNTGKNZ3.js.map +1 -0
- package/dist/chunk-CQNNSZPG.js +9 -0
- package/dist/chunk-CQNNSZPG.js.map +1 -0
- package/dist/{chunk-HF4KHHNM.js → chunk-DC2GJDPR.js} +5 -5
- package/dist/chunk-DC2GJDPR.js.map +1 -0
- package/dist/{chunk-IZM6FNCT.js → chunk-I7TM7TKX.js} +48 -42
- package/dist/chunk-I7TM7TKX.js.map +1 -0
- package/dist/{chunk-WRNPY5C6.js → chunk-KXXFWLKP.js} +3 -3
- package/dist/{chunk-2STANSN6.js → chunk-L52YHJ5L.js} +23 -20
- package/dist/chunk-L52YHJ5L.js.map +1 -0
- package/dist/{chunk-UDISNNKR.js → chunk-NS7W4G26.js} +70 -21
- package/dist/chunk-NS7W4G26.js.map +1 -0
- package/dist/{chunk-SHORX7TZ.js → chunk-WHHQWT7D.js} +12 -13
- package/dist/chunk-WHHQWT7D.js.map +1 -0
- package/dist/{chunk-EGZCTSEW.js → chunk-WWNXZWST.js} +208 -132
- package/dist/chunk-WWNXZWST.js.map +1 -0
- package/dist/{chunk-JS5MGVNM.js → chunk-YBBD4HZ3.js} +8 -7
- package/dist/{chunk-JS5MGVNM.js.map → chunk-YBBD4HZ3.js.map} +1 -1
- package/dist/{chunk-FUJ3POKH.js → chunk-YTF65GYU.js} +2 -2
- package/dist/completion/index.d.ts +3 -3
- package/dist/completion/index.js +4 -2
- package/dist/embeddings/index.js +1 -1
- package/dist/evals/index.d.ts +8 -8
- package/dist/evals/index.js +59 -36
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +8 -8
- package/dist/extractor/index.js +11 -12
- package/dist/guardrails/index.d.ts +1 -1
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +1 -2
- package/dist/image-generation/index.d.ts +1 -1
- package/dist/{index-CM-V4LS3.d.ts → index-ZQAiHW5Q.d.ts} +2 -2
- package/dist/index.d.ts +12 -12
- package/dist/index.js +16 -14
- package/dist/internal/agent.d.ts +8 -8
- package/dist/internal/agent.js +9 -10
- package/dist/{create-completion-CC8-Ep3w.d.ts → json-C5a6auAm.d.ts} +4 -2
- package/dist/loaders/index.d.ts +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/memory/index.d.ts +3 -3
- package/dist/{middleware-i-jLsLom.d.ts → middleware-Cc_-sosu.d.ts} +3 -3
- package/dist/observability/index.d.ts +3 -3
- package/dist/pipeline/index.d.ts +8 -8
- package/dist/pipeline/index.js +34 -19
- package/dist/pipeline/index.js.map +1 -1
- package/dist/request/index.d.ts +8 -8
- package/dist/request/index.js +8 -9
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +7 -7
- package/dist/{think-tool-BKDCOJh5.d.ts → think-tool-DvhOlrL8.d.ts} +1 -1
- package/dist/tool/index.d.ts +5 -5
- package/dist/tool/index.js +5 -6
- package/dist/{tool-f2stpvUP.d.ts → tool-6f9bK92X.d.ts} +1 -1
- package/dist/transcription/index.d.ts +1 -1
- package/dist/{types-5JgWDgaM.d.ts → types-BG3s2WzI.d.ts} +2 -2
- package/dist/{types-b6fOVoW1.d.ts → types-BZQlZ4Vs.d.ts} +1 -1
- package/dist/{types-Dh7gfoGw.d.ts → types-BaYwqozV.d.ts} +1 -1
- package/dist/{types-DmvXANwl.d.ts → types-C708DOhL.d.ts} +1 -1
- package/dist/{types-bNDxj4Tt.d.ts → types-CNeDsGjw.d.ts} +1 -1
- package/dist/{types-C15r7N_4.d.ts → types-DzdJOf35.d.ts} +17 -6
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/dist/vector-store/index.d.ts +4 -4
- package/dist/vector-store/index.js +3 -4
- package/package.json +1 -1
- package/dist/chunk-2STANSN6.js.map +0 -1
- package/dist/chunk-EGZCTSEW.js.map +0 -1
- package/dist/chunk-HF4KHHNM.js.map +0 -1
- package/dist/chunk-IZM6FNCT.js.map +0 -1
- package/dist/chunk-MMHG7WAM.js +0 -19
- package/dist/chunk-MMHG7WAM.js.map +0 -1
- package/dist/chunk-NPZDYOE6.js.map +0 -1
- package/dist/chunk-QVFOCNF6.js.map +0 -1
- package/dist/chunk-SHORX7TZ.js.map +0 -1
- package/dist/chunk-UDISNNKR.js.map +0 -1
- /package/dist/{chunk-IN5NPAWL.js.map → chunk-CLFDBOH3.js.map} +0 -0
- /package/dist/{chunk-WRNPY5C6.js.map → chunk-KXXFWLKP.js.map} +0 -0
- /package/dist/{chunk-FUJ3POKH.js.map → chunk-YTF65GYU.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vector-store/index.ts","../src/tool/create-tool.ts","../src/vector-store/filter.ts","../src/vector-store/lsh.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n cosineSimilarity,\n type EmbeddedDocument,\n type Embedding,\n type EmbeddingModel,\n embedText,\n type VectorMetadata,\n} from \"../embeddings\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool } from \"../tool/tool\";\nimport { matchesVectorFilter } from \"./filter\";\nimport { LshIndex } from \"./lsh\";\nimport type {\n IndexStrategy,\n VectorInspectItem,\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchIndex,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n} from \"./types\";\n\nexport { vectorFilter } from \"./filter\";\nexport type * from \"./types\";\n\ntype StoredDocument<T, Metadata extends VectorMetadata> = EmbeddedDocument<T, Metadata>;\n\nexport class InMemoryVectorStore<T, Metadata extends VectorMetadata = VectorMetadata> {\n private readonly documents = new Map<string, StoredDocument<T, Metadata>>();\n private indexStrategy: IndexStrategy;\n private lshIndex: LshIndex | undefined;\n private embeddingDimension: number | undefined;\n\n constructor(options: { index?: IndexStrategy } = {}) {\n this.indexStrategy = options.index ?? { type: \"bruteForce\" };\n }\n\n static fromDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n documents: Array<EmbeddedDocument<T, Metadata>>,\n options: { index?: IndexStrategy } = {},\n ): InMemoryVectorStore<T, Metadata> {\n const store = new InMemoryVectorStore<T, Metadata>(options);\n store.addDocuments(documents);\n return store;\n }\n\n addDocuments(documents: Array<EmbeddedDocument<T, Metadata>>): this {\n this.validateDocumentDimensions(documents);\n for (const document of documents) {\n this.documents.set(document.id, document);\n }\n this.rebuildLshIndex();\n return this;\n }\n\n get(id: string): StoredDocument<T, Metadata> | undefined {\n return this.documents.get(id);\n }\n\n values(): Array<StoredDocument<T, Metadata>> {\n return [...this.documents.values()];\n }\n\n len(): number {\n return this.documents.size;\n }\n\n isEmpty(): boolean {\n return this.documents.size === 0;\n }\n\n index(model: EmbeddingModel): InMemoryVectorIndex<T, Metadata> {\n return new InMemoryVectorIndex(model, this);\n }\n\n candidates(queryEmbedding: Embedding): Array<StoredDocument<T, Metadata>> {\n this.validateQueryDimension(queryEmbedding);\n if (this.indexStrategy.type !== \"lsh\" || this.lshIndex === undefined) {\n return this.values();\n }\n\n const candidateIds = this.lshIndex.query(queryEmbedding.vector);\n if (candidateIds.size === 0) {\n return this.values();\n }\n\n return [...candidateIds].flatMap((id) => {\n const document = this.documents.get(id);\n return document === undefined ? [] : [document];\n });\n }\n\n private rebuildLshIndex(): void {\n if (this.indexStrategy.type !== \"lsh\") {\n this.lshIndex = undefined;\n return;\n }\n\n const firstEmbedding = this.values().flatMap((document) => document.embeddings)[0];\n if (firstEmbedding === undefined) {\n this.lshIndex = undefined;\n return;\n }\n\n const index = new LshIndex(firstEmbedding.vector.length, this.indexStrategy);\n for (const document of this.documents.values()) {\n for (const embedding of document.embeddings) {\n index.insert(document.id, embedding.vector);\n }\n }\n this.lshIndex = index;\n }\n\n private validateDocumentDimensions(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n let dimension = this.embeddingDimension;\n for (const document of documents) {\n for (const embedding of document.embeddings) {\n dimension = validateEmbeddingDimension(dimension, embedding, document.id);\n }\n }\n this.embeddingDimension = dimension;\n }\n\n private validateQueryDimension(queryEmbedding: Embedding): void {\n if (this.embeddingDimension === undefined) {\n return;\n }\n validateEmbeddingDimension(this.embeddingDimension, queryEmbedding, \"query\");\n }\n}\n\nexport class InMemoryVectorIndex<T, Metadata extends VectorMetadata = VectorMetadata>\n implements VectorSearchIndex<T, Metadata>\n{\n constructor(\n private readonly model: EmbeddingModel,\n private readonly store: InMemoryVectorStore<T, Metadata>,\n ) {}\n\n async search(request: VectorSearchRequest): Promise<Array<VectorSearchResult<T, Metadata>>> {\n const queryEmbedding = await embedText(this.model, request.query);\n return this.store\n .candidates(queryEmbedding)\n .filter((document) => matchesVectorFilter(document.metadata, request.filter))\n .flatMap((document) => {\n const score = bestScore(queryEmbedding, document.embeddings);\n if (score === undefined) {\n return [];\n }\n if (request.threshold !== undefined && score < request.threshold) {\n return [];\n }\n const result: VectorSearchResult<T, Metadata> = {\n score,\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n result.metadata = document.metadata;\n }\n return [result];\n })\n .sort((left, right) => right.score - left.score)\n .slice(0, Math.max(0, Math.trunc(request.topK)));\n }\n\n async searchIds(request: VectorSearchRequest): Promise<Array<{ score: number; id: string }>> {\n return (await this.search(request)).map(({ score, id }) => ({ score, id }));\n }\n\n async inspect(request: VectorInspectRequest): Promise<VectorInspectPage<T, Metadata>> {\n const limit = Math.max(0, Math.trunc(request.limit));\n const start = Math.max(0, Math.trunc(Number(request.cursor ?? \"0\")));\n const documents = this.store\n .values()\n .filter((document) => matchesVectorFilter(document.metadata, request.filter));\n const page = documents.slice(start, start + limit);\n const nextOffset = start + page.length;\n const result: VectorInspectPage<T, Metadata> = {\n items: page.map((document) => {\n const item: VectorInspectItem<T, Metadata> = {\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n item.metadata = document.metadata;\n }\n return item;\n }),\n };\n if (nextOffset < documents.length) {\n result.nextCursor = String(nextOffset);\n }\n result.totalCount = documents.length;\n return result;\n }\n\n asTool(options: VectorSearchToolOptions): Tool<{ query: string; topK?: number }, unknown> {\n return createVectorSearchTool(this, options);\n }\n}\n\nexport function createVectorSearchTool<T, Metadata extends VectorMetadata>(\n index: VectorSearchIndex<T, Metadata>,\n options: VectorSearchToolOptions,\n): Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>> {\n return createTool({\n name: options.name,\n description:\n options.description ?? \"Search a vector store for documents relevant to the provided query.\",\n input: z.object({\n query: z.string().describe(\"The query string to search for relevant documents.\"),\n topK: z.number().int().positive().optional().describe(\"The maximum number of results.\"),\n }),\n output: z.array(\n z.object({\n score: z.number(),\n id: z.string(),\n document: z.any(),\n metadata: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))\n .optional(),\n }),\n ),\n execute: ({ query, topK }) =>\n index.search({\n query,\n topK: topK ?? options.topK ?? 5,\n threshold: options.threshold,\n filter: options.filter,\n }),\n }) as Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>>;\n}\n\nfunction bestScore(queryEmbedding: Embedding, embeddings: Embedding[]): number | undefined {\n let best: number | undefined;\n for (const embedding of embeddings) {\n const score = cosineSimilarity(queryEmbedding.vector, embedding.vector);\n best = best === undefined ? score : Math.max(best, score);\n }\n return best;\n}\n\nfunction validateEmbeddingDimension(\n expectedDimension: number | undefined,\n embedding: Embedding,\n id: string,\n): number {\n if (expectedDimension === undefined) {\n return embedding.vector.length;\n }\n if (embedding.vector.length !== expectedDimension) {\n throw new Error(\n `Vector dimension mismatch: expected ${expectedDimension} dimensions but received ${embedding.vector.length} for ${id}`,\n );\n }\n return expectedDimension;\n}\n","import type { z } from \"zod\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { Tool, ToolApprovalPolicy, ToolCallContext } from \"./tool\";\n\nexport type CreateToolOptions<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n> = {\n name: string;\n description: string;\n input: InputSchema;\n output?: OutputSchema;\n approval?: ToolApprovalPolicy<z.output<InputSchema>>;\n execute(\n args: z.output<InputSchema>,\n context: ToolCallContext,\n ): OutputSchema extends ZodSchema\n ? z.input<OutputSchema> | Promise<z.input<OutputSchema>>\n : Output | Promise<Output>;\n};\n\ntype CreateToolOutput<\n OutputSchema extends ZodSchema | undefined,\n Output,\n> = OutputSchema extends ZodSchema ? z.output<OutputSchema> : Output;\n\nexport function createTool<InputSchema extends ZodSchema, Output = unknown>(\n options: CreateToolOptions<InputSchema, undefined, Output> & { output?: undefined },\n): Tool<z.output<InputSchema>, Output>;\n\nexport function createTool<InputSchema extends ZodSchema, OutputSchema extends ZodSchema>(\n options: CreateToolOptions<InputSchema, OutputSchema>,\n): Tool<z.output<InputSchema>, z.output<OutputSchema>>;\n\nexport function createTool<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n>(\n options: CreateToolOptions<InputSchema, OutputSchema, Output>,\n): Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> {\n const parameters = toProviderJsonSchema(options.input);\n const definition = () => ({\n name: options.name,\n description: options.description,\n parameters,\n });\n const call = async (\n args: z.output<InputSchema>,\n context: ToolCallContext = {},\n ): Promise<CreateToolOutput<OutputSchema, Output>> => {\n const parsedArgs = options.input.parse(args);\n const result = await options.execute(parsedArgs, context);\n return (\n options.output === undefined ? result : options.output.parse(result)\n ) as CreateToolOutput<OutputSchema, Output>;\n };\n const parseApprovalArgs = (args: unknown): z.output<InputSchema> => options.input.parse(args);\n\n if (options.approval === undefined) {\n return { name: options.name, definition, call, parseApprovalArgs };\n }\n return {\n name: options.name,\n approval: options.approval,\n definition,\n call,\n parseApprovalArgs,\n };\n}\n","import type { VectorMetadata, VectorMetadataValue } from \"../embeddings\";\nimport type { VectorFilter } from \"./types\";\n\nexport type { VectorFilter } from \"./types\";\n\nexport const vectorFilter = {\n eq(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"eq\", key, value };\n },\n gt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"gt\", key, value };\n },\n lt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"lt\", key, value };\n },\n and(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"and\", filters: [left, right] };\n },\n or(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"or\", filters: [left, right] };\n },\n};\n\nexport function matchesVectorFilter(\n metadata: VectorMetadata | undefined,\n filter: VectorFilter | undefined,\n): boolean {\n if (filter === undefined) {\n return true;\n }\n if (metadata === undefined) {\n return false;\n }\n\n switch (filter.type) {\n case \"eq\":\n return metadata[filter.key] === filter.value;\n case \"gt\":\n return compare(metadata[filter.key], filter.value) > 0;\n case \"lt\":\n return compare(metadata[filter.key], filter.value) < 0;\n case \"and\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) &&\n matchesVectorFilter(metadata, filter.filters[1])\n );\n case \"or\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) ||\n matchesVectorFilter(metadata, filter.filters[1])\n );\n }\n}\n\nfunction compare(left: VectorMetadataValue | undefined, right: VectorMetadataValue): number {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n if (typeof left === \"string\" && typeof right === \"string\") {\n return left.localeCompare(right);\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right);\n }\n return 0;\n}\n","import type { LshOptions } from \"./types\";\n\nexport type { LshOptions } from \"./types\";\n\nexport class LshIndex {\n private readonly hyperplanes: number[][];\n private readonly tables: Array<Map<string, Set<string>>>;\n\n constructor(\n dimensions: number,\n private readonly options: LshOptions,\n ) {\n const rng = seededRandom(options.seed ?? 42);\n this.hyperplanes = [];\n for (let index = 0; index < options.numTables * options.numHyperplanes; index += 1) {\n const plane = Array.from({ length: dimensions }, () => rng() * 2 - 1);\n const norm = Math.sqrt(plane.reduce((sum, value) => sum + value ** 2, 0));\n this.hyperplanes.push(norm === 0 ? plane : plane.map((value) => value / norm));\n }\n this.tables = Array.from({ length: options.numTables }, () => new Map());\n }\n\n insert(id: string, vector: number[]): void {\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n const bucket = this.tables[table]?.get(hash) ?? new Set<string>();\n bucket.add(id);\n this.tables[table]?.set(hash, bucket);\n }\n }\n\n query(vector: number[]): Set<string> {\n const candidates = new Set<string>();\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n for (const id of this.tables[table]?.get(hash) ?? []) {\n candidates.add(id);\n }\n }\n return candidates;\n }\n\n private hash(vector: number[], table: number): string {\n let hash = \"\";\n const start = table * this.options.numHyperplanes;\n for (let offset = 0; offset < this.options.numHyperplanes; offset += 1) {\n const plane = this.hyperplanes[start + offset] as number[];\n const dot = vector.reduce((sum, value, index) => sum + value * (plane[index] ?? 0), 0);\n hash += dot >= 0 ? \"1\" : \"0\";\n }\n return hash;\n }\n}\n\nfunction seededRandom(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (state * 1664525 + 1013904223) >>> 0;\n return state / 0x100000000;\n };\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,SAAS;;;ACmCX,SAAS,WAKd,SACqE;AACrE,QAAM,aAAa,qBAAqB,QAAQ,KAAK;AACrD,QAAM,aAAa,OAAO;AAAA,IACxB,MAAM,QAAQ;AAAA,I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A,SAAS,2BACP,mBACA,WACA,IACQ;AACR,MAAI,sBAAsB,QAAW;AACnC,WAAO,UAAU,OAAO;AAAA,EAC1B;AACA,MAAI,UAAU,OAAO,WAAW,mBAAmB;AACjD,UAAM,IAAI;AAAA,MACR,uCAAuC,iBAAiB,4BAA4B,UAAU,OAAO,MAAM,QAAQ,EAAE;AAAA,IACvH;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent,
|
|
3
3
|
normalizeAgentId
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-L52YHJ5L.js";
|
|
5
5
|
import {
|
|
6
6
|
ToolSet
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-WHHQWT7D.js";
|
|
8
8
|
import {
|
|
9
9
|
resolveMemoryOptions
|
|
10
10
|
} from "./chunk-M6RPFHG7.js";
|
|
@@ -212,4 +212,4 @@ var AgentBuilder = class {
|
|
|
212
212
|
export {
|
|
213
213
|
AgentBuilder
|
|
214
214
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-KXXFWLKP.js.map
|
|
@@ -1,21 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PromptRequest
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-WWNXZWST.js";
|
|
4
4
|
import {
|
|
5
5
|
isSkillTool
|
|
6
6
|
} from "./chunk-YK4WAAS4.js";
|
|
7
7
|
import {
|
|
8
8
|
ToolSet
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-WHHQWT7D.js";
|
|
10
10
|
import {
|
|
11
11
|
createTool
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import {
|
|
14
|
-
compact
|
|
15
|
-
} from "./chunk-MMHG7WAM.js";
|
|
12
|
+
} from "./chunk-I7TM7TKX.js";
|
|
16
13
|
import {
|
|
17
14
|
isStreamingCompletionModel
|
|
18
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-YTF65GYU.js";
|
|
19
16
|
|
|
20
17
|
// src/agent/agent.ts
|
|
21
18
|
import { z } from "zod";
|
|
@@ -97,11 +94,16 @@ var Agent = class {
|
|
|
97
94
|
if (normalized.length === 0) {
|
|
98
95
|
throw new TypeError("Session id must be a non-empty string.");
|
|
99
96
|
}
|
|
100
|
-
|
|
101
|
-
sessionId: normalized
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
97
|
+
const context = {
|
|
98
|
+
sessionId: normalized
|
|
99
|
+
};
|
|
100
|
+
if (options.userId !== void 0) {
|
|
101
|
+
context.userId = options.userId;
|
|
102
|
+
}
|
|
103
|
+
if (options.metadata !== void 0) {
|
|
104
|
+
context.metadata = options.metadata;
|
|
105
|
+
}
|
|
106
|
+
return new AgentSession(this, context);
|
|
105
107
|
}
|
|
106
108
|
asTool(options) {
|
|
107
109
|
const description = options.description ?? this.description ?? `Prompt the ${options.name} agent.`;
|
|
@@ -118,13 +120,14 @@ var Agent = class {
|
|
|
118
120
|
if (options.stream === true && context.emitStreamEvent !== void 0 && this.model.capabilities.streaming && isStreamingCompletionModel(this.model)) {
|
|
119
121
|
let output = "";
|
|
120
122
|
for await (const event of childRequest.stream()) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
123
|
+
const streamEvent = {
|
|
124
|
+
agentId: this.id,
|
|
125
|
+
event
|
|
126
|
+
};
|
|
127
|
+
if (this.name !== void 0) {
|
|
128
|
+
streamEvent.agentName = this.name;
|
|
129
|
+
}
|
|
130
|
+
await context.emitStreamEvent(streamEvent);
|
|
128
131
|
if (event.type === "final") {
|
|
129
132
|
output = event.output;
|
|
130
133
|
}
|
|
@@ -204,4 +207,4 @@ export {
|
|
|
204
207
|
Agent,
|
|
205
208
|
AgentSession
|
|
206
209
|
};
|
|
207
|
-
//# sourceMappingURL=chunk-
|
|
210
|
+
//# sourceMappingURL=chunk-L52YHJ5L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/agent.ts","../src/agent/ids.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { isStreamingCompletionModel } from \"../completion/create-completion\";\nimport type {\n CompletionModel,\n Document,\n JsonObject,\n JsonValue,\n Message as MessageType,\n ToolChoice,\n} from \"../completion/index\";\nimport type { GuardrailPolicy } from \"../guardrails\";\nimport type { PromptHook } from \"../hooks\";\nimport type { MemoryContext, MemoryRegistration, SessionOptions } from \"../memory/types\";\nimport type { AgentObserverRegistration } from \"../observability\";\nimport { PromptRequest } from \"../request\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { ToolSearchDocument } from \"../tool/dynamic-tools\";\nimport type { AgentMiddleware } from \"../tool/middleware\";\nimport { isSkillTool } from \"../tool/skill-tool-marker\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n Tool,\n ToolApprovalsOptions,\n ToolCallContext,\n ToolCallStreamEvent,\n} from \"../tool/tool\";\nimport { ToolSet } from \"../tool/tool-set\";\nimport type { VectorSearchIndex } from \"../vector-store\";\nimport { normalizeAgentId } from \"./ids\";\nimport type {\n AgentEventStoreRegistration,\n AgentOptions,\n AgentToolOptions,\n DynamicContextRegistration,\n DynamicToolRegistration,\n} from \"./types\";\n\nexport const DEFAULT_MAX_TURNS = 20;\n\nexport class Agent<M extends CompletionModel = CompletionModel> {\n readonly id: string;\n readonly name: string | undefined;\n readonly description: string | undefined;\n readonly model: M;\n readonly instructions: string | undefined;\n readonly staticContext: Document[];\n readonly temperature: number | undefined;\n readonly maxTokens: number | undefined;\n readonly additionalParams: JsonValue | undefined;\n readonly toolSet: ToolSet;\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly hook: PromptHook | undefined;\n readonly outputSchema: JsonObject | undefined;\n readonly observers: AgentObserverRegistration[];\n readonly approvals: ToolApprovalsOptions | undefined;\n readonly guardrails: GuardrailPolicy[];\n readonly dynamicContexts: DynamicContextRegistration[];\n readonly dynamicTools: DynamicToolRegistration[];\n readonly middlewares: AgentMiddleware[];\n /**\n * @deprecated Use `middlewares` instead.\n */\n readonly toolMiddlewares: AgentMiddleware[];\n readonly memory: MemoryRegistration | undefined;\n readonly eventStore: AgentEventStoreRegistration | undefined;\n\n constructor(options: AgentOptions<M>) {\n this.id = normalizeAgentId(options.id);\n this.name = options.name;\n this.description = options.description;\n this.model = options.model;\n this.instructions = options.instructions;\n this.staticContext = [...(options.staticContext ?? [])];\n this.temperature = options.temperature;\n this.maxTokens = options.maxTokens;\n this.additionalParams = options.additionalParams;\n this.toolSet = options.toolSet ?? new ToolSet();\n this.toolChoice = options.toolChoice;\n this.defaultMaxTurns = options.defaultMaxTurns ?? DEFAULT_MAX_TURNS;\n this.hook = options.hook;\n this.outputSchema = options.outputSchema;\n this.observers = [...(options.observers ?? [])];\n this.approvals = options.approvals;\n this.guardrails = [...(options.guardrails ?? [])];\n this.dynamicContexts = [...(options.dynamicContexts ?? [])];\n this.dynamicTools = [...(options.dynamicTools ?? [])];\n this.middlewares = [...(options.middlewares ?? options.toolMiddlewares ?? [])];\n this.toolMiddlewares = this.middlewares;\n this.memory = options.memory;\n this.eventStore = options.eventStore;\n }\n\n prompt(prompt: string | MessageType | MessageType[]): PromptRequest<M> {\n return PromptRequest.fromAgent(this, prompt);\n }\n\n session(sessionId: string, options: SessionOptions = {}): AgentSession<M> {\n if (this.memory === undefined) {\n throw new Error(`Agent \"${this.id}\" has no memory store configured.`);\n }\n const normalized = sessionId.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Session id must be a non-empty string.\");\n }\n const context: MemoryContext = {\n sessionId: normalized,\n };\n if (options.userId !== undefined) {\n context.userId = options.userId;\n }\n if (options.metadata !== undefined) {\n context.metadata = options.metadata;\n }\n return new AgentSession(this, context);\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, string> {\n const description =\n options.description ?? this.description ?? `Prompt the ${options.name} agent.`;\n\n return createTool({\n name: options.name,\n description,\n input: z.object({\n prompt: z.string().describe(\"The prompt to send to the agent.\"),\n }),\n output: z.string(),\n execute: async ({ prompt }, context: ToolCallContext) => {\n const request = this.prompt(prompt);\n const childRequest =\n options.maxTurns === undefined ? request : request.maxTurns(options.maxTurns);\n if (\n options.stream === true &&\n context.emitStreamEvent !== undefined &&\n this.model.capabilities.streaming &&\n isStreamingCompletionModel(this.model)\n ) {\n let output = \"\";\n for await (const event of childRequest.stream()) {\n const streamEvent: ToolCallStreamEvent = {\n agentId: this.id,\n event,\n };\n if (this.name !== undefined) {\n streamEvent.agentName = this.name;\n }\n await context.emitStreamEvent(streamEvent);\n if (event.type === \"final\") {\n output = event.output;\n }\n }\n return output;\n }\n const response = await childRequest.send();\n return response.output;\n },\n });\n }\n\n getTool(toolName: string): AnyTool | undefined {\n const staticTool = this.toolSet.get(toolName);\n if (staticTool !== undefined) {\n return staticTool;\n }\n\n for (const registration of this.dynamicTools) {\n const dynamicTool = dynamicToolSetFromIndex(registration.index)?.get(toolName);\n if (dynamicTool !== undefined) {\n return dynamicTool;\n }\n }\n\n return undefined;\n }\n\n async callTool(\n toolName: string,\n args: string,\n context?: ToolCallContext,\n ): Promise<NormalizedToolOutput> {\n if (this.toolSet.contains(toolName)) {\n return this.toolSet.call(toolName, args, context);\n }\n\n for (const registration of this.dynamicTools) {\n const toolSet = dynamicToolSetFromIndex(registration.index);\n if (toolSet?.contains(toolName)) {\n return toolSet.call(toolName, args, context);\n }\n }\n\n return this.toolSet.call(toolName, args, context);\n }\n\n shouldApplyToolMiddleware(toolName: string): boolean {\n return !isSkillTool(this.getTool(toolName));\n }\n}\n\nexport class AgentSession<M extends CompletionModel = CompletionModel> {\n constructor(\n private readonly agent: Agent<M>,\n private readonly context: {\n sessionId: string;\n userId?: string | undefined;\n metadata?: JsonObject | undefined;\n },\n ) {}\n\n prompt(prompt: string | MessageType): PromptRequest<M> {\n if (Array.isArray(prompt)) {\n throw new TypeError(\"AgentSession.prompt does not accept Message[] transcripts.\");\n }\n return PromptRequest.fromAgent(this.agent, prompt, { memoryContext: this.context });\n }\n\n async messages(): Promise<MessageType[]> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n return memory.store.load(this.context);\n }\n\n async clear(): Promise<void> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n await memory.store.clear(this.context);\n }\n}\n\nfunction dynamicToolSetFromIndex(\n index: VectorSearchIndex<ToolSearchDocument>,\n): ToolSet | undefined {\n const maybeIndex = index as { toolSet?: unknown };\n return maybeIndex.toolSet instanceof ToolSet ? maybeIndex.toolSet : undefined;\n}\n","export function normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACAX,SAAS,iBAAiB,IAAoB;AACnD,MAAI,OAAO,OAAO,UAAU;AAC1B,UAAM,IAAI,UAAU,4BAA4B;AAAA,EAClD;AAEA,QAAM,aAAa,GAAG,KAAK;AAC3B,MAAI,WAAW,WAAW,GAAG;AAC3B,UAAM,IAAI,UAAU,sCAAsC;AAAA,EAC5D;AAEA,SAAO;AACT;;;AD2BO,IAAM,oBAAoB;AAE1B,IAAM,QAAN,MAAyD;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA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,MAAM,QAAuB;AAC3B,UAAM,SAAS,KAAK,MAAM;AAC1B,QAAI,WAAW,QAAW;AACxB,YAAM,IAAI,MAAM,UAAU,KAAK,MAAM,EAAE,mCAAmC;AAAA,IAC5E;AACA,UAAM,OAAO,MAAM,MAAM,KAAK,OAAO;AAAA,EACvC;AACF;AAEA,SAAS,wBACP,OACqB;AACrB,QAAM,aAAa;AACnB,SAAO,WAAW,mBAAmB,UAAU,WAAW,UAAU;AACtE;","names":[]}
|
|
@@ -3,9 +3,10 @@ import {
|
|
|
3
3
|
Message,
|
|
4
4
|
ToolContent,
|
|
5
5
|
UserContent,
|
|
6
|
+
isJsonValue,
|
|
6
7
|
reasoningDisplayText,
|
|
7
8
|
serializeToolResultOutput
|
|
8
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-CNTGKNZ3.js";
|
|
9
10
|
|
|
10
11
|
// src/ui/messages.ts
|
|
11
12
|
function uiMessagesToCoreMessages(messages) {
|
|
@@ -14,7 +15,7 @@ function uiMessagesToCoreMessages(messages) {
|
|
|
14
15
|
const text = textFromUIParts(message.parts);
|
|
15
16
|
if (message.role === "system") {
|
|
16
17
|
if (text.length > 0) {
|
|
17
|
-
coreMessages.push(Message.system(text));
|
|
18
|
+
coreMessages.push(Message.system(text, metadataOptions(message.metadata)));
|
|
18
19
|
}
|
|
19
20
|
continue;
|
|
20
21
|
}
|
|
@@ -38,7 +39,7 @@ function uiMessagesToCoreMessages(messages) {
|
|
|
38
39
|
);
|
|
39
40
|
}
|
|
40
41
|
if (content.length > 0) {
|
|
41
|
-
coreMessages.push(Message.user(content));
|
|
42
|
+
coreMessages.push(Message.user(content, metadataOptions(message.metadata)));
|
|
42
43
|
}
|
|
43
44
|
continue;
|
|
44
45
|
}
|
|
@@ -74,7 +75,12 @@ function uiMessagesToCoreMessages(messages) {
|
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
if (content.length > 0) {
|
|
77
|
-
coreMessages.push(
|
|
78
|
+
coreMessages.push(
|
|
79
|
+
Message.assistant(content, {
|
|
80
|
+
id: message.id,
|
|
81
|
+
...metadataOptions(message.metadata)
|
|
82
|
+
})
|
|
83
|
+
);
|
|
78
84
|
}
|
|
79
85
|
if (toolResults2.length > 0) {
|
|
80
86
|
coreMessages.push(Message.tool(toolResults2));
|
|
@@ -94,7 +100,7 @@ function uiMessagesToCoreMessages(messages) {
|
|
|
94
100
|
);
|
|
95
101
|
}
|
|
96
102
|
if (toolResults.length > 0) {
|
|
97
|
-
coreMessages.push(Message.tool(toolResults));
|
|
103
|
+
coreMessages.push(Message.tool(toolResults, metadataOptions(message.metadata)));
|
|
98
104
|
}
|
|
99
105
|
}
|
|
100
106
|
return coreMessages;
|
|
@@ -110,7 +116,8 @@ function coreMessagesToUIMessages(messages) {
|
|
|
110
116
|
uiMessages.push({
|
|
111
117
|
id: createId("msg"),
|
|
112
118
|
role: "system",
|
|
113
|
-
parts: [{ id: createId("part"), type: "text", text: message.content }]
|
|
119
|
+
parts: [{ id: createId("part"), type: "text", text: message.content }],
|
|
120
|
+
...uiMetadata(message.metadata)
|
|
114
121
|
});
|
|
115
122
|
continue;
|
|
116
123
|
}
|
|
@@ -127,7 +134,12 @@ function coreMessagesToUIMessages(messages) {
|
|
|
127
134
|
});
|
|
128
135
|
}
|
|
129
136
|
}
|
|
130
|
-
uiMessages.push({
|
|
137
|
+
uiMessages.push({
|
|
138
|
+
id: createId("msg"),
|
|
139
|
+
role: "user",
|
|
140
|
+
parts: parts2,
|
|
141
|
+
...uiMetadata(message.metadata)
|
|
142
|
+
});
|
|
131
143
|
continue;
|
|
132
144
|
}
|
|
133
145
|
if (message.role === "assistant") {
|
|
@@ -172,7 +184,12 @@ function coreMessagesToUIMessages(messages) {
|
|
|
172
184
|
});
|
|
173
185
|
}
|
|
174
186
|
const messageIndex = uiMessages.length;
|
|
175
|
-
uiMessages.push({
|
|
187
|
+
uiMessages.push({
|
|
188
|
+
id: message.id ?? createId("msg"),
|
|
189
|
+
role: "assistant",
|
|
190
|
+
parts: parts2,
|
|
191
|
+
...uiMetadata(message.metadata)
|
|
192
|
+
});
|
|
176
193
|
registerToolPartLocations(parts2, messageIndex, toolPartLocations);
|
|
177
194
|
continue;
|
|
178
195
|
}
|
|
@@ -189,17 +206,40 @@ function coreMessagesToUIMessages(messages) {
|
|
|
189
206
|
if (content.callId !== void 0) {
|
|
190
207
|
part.callId = content.callId;
|
|
191
208
|
}
|
|
192
|
-
if (mergeToolResultPart(uiMessages, toolPartLocations, part)) {
|
|
209
|
+
if (message.metadata === void 0 && mergeToolResultPart(uiMessages, toolPartLocations, part)) {
|
|
193
210
|
continue;
|
|
194
211
|
}
|
|
195
212
|
parts.push(part);
|
|
196
213
|
}
|
|
197
214
|
if (parts.length > 0) {
|
|
198
|
-
uiMessages.push({
|
|
215
|
+
uiMessages.push({
|
|
216
|
+
id: createId("msg"),
|
|
217
|
+
role: "tool",
|
|
218
|
+
parts,
|
|
219
|
+
...uiMetadata(message.metadata)
|
|
220
|
+
});
|
|
199
221
|
}
|
|
200
222
|
}
|
|
201
223
|
return uiMessages;
|
|
202
224
|
}
|
|
225
|
+
function metadataOptions(metadata) {
|
|
226
|
+
if (metadata === void 0) {
|
|
227
|
+
return {};
|
|
228
|
+
}
|
|
229
|
+
if (!isJsonValue(metadata)) {
|
|
230
|
+
throw new TypeError("UI message metadata must be a strict JSON value.");
|
|
231
|
+
}
|
|
232
|
+
return { metadata };
|
|
233
|
+
}
|
|
234
|
+
function uiMetadata(metadata) {
|
|
235
|
+
if (metadata === void 0) {
|
|
236
|
+
return {};
|
|
237
|
+
}
|
|
238
|
+
if (!isJsonValue(metadata)) {
|
|
239
|
+
throw new TypeError("Core message metadata must be a strict JSON value.");
|
|
240
|
+
}
|
|
241
|
+
return { metadata };
|
|
242
|
+
}
|
|
203
243
|
function registerToolPartLocations(parts, messageIndex, toolPartLocations) {
|
|
204
244
|
for (const [partIndex, part] of parts.entries()) {
|
|
205
245
|
if (part.type !== "tool") {
|
|
@@ -232,9 +272,11 @@ function mergeToolResultPart(uiMessages, toolPartLocations, resultPart) {
|
|
|
232
272
|
const mergedPart = {
|
|
233
273
|
...currentPart,
|
|
234
274
|
toolName: resultPart.toolName === "tool" ? currentPart.toolName : resultPart.toolName,
|
|
235
|
-
state: "output-available"
|
|
236
|
-
...resultPart.output === void 0 ? {} : { output: resultPart.output }
|
|
275
|
+
state: "output-available"
|
|
237
276
|
};
|
|
277
|
+
if (resultPart.output !== void 0) {
|
|
278
|
+
mergedPart.output = resultPart.output;
|
|
279
|
+
}
|
|
238
280
|
if (currentPart.callId === void 0 && resultPart.callId !== void 0) {
|
|
239
281
|
mergedPart.callId = resultPart.callId;
|
|
240
282
|
toolPartLocations.byCallId.set(resultPart.callId, location);
|
|
@@ -276,14 +318,19 @@ function attachmentToUserContent(attachment) {
|
|
|
276
318
|
throw new TypeError("Image attachments require a url or base64 data with mediaType.");
|
|
277
319
|
}
|
|
278
320
|
if (attachment.text !== void 0) {
|
|
321
|
+
const source = {
|
|
322
|
+
type: "text",
|
|
323
|
+
text: attachment.text
|
|
324
|
+
};
|
|
325
|
+
if (attachment.mediaType !== void 0) {
|
|
326
|
+
source.mediaType = attachment.mediaType;
|
|
327
|
+
}
|
|
328
|
+
if (attachment.name !== void 0) {
|
|
329
|
+
source.filename = attachment.name;
|
|
330
|
+
}
|
|
279
331
|
return {
|
|
280
332
|
type: "document",
|
|
281
|
-
source
|
|
282
|
-
type: "text",
|
|
283
|
-
text: attachment.text,
|
|
284
|
-
...attachment.mediaType === void 0 ? {} : { mediaType: attachment.mediaType },
|
|
285
|
-
...attachment.name === void 0 ? {} : { filename: attachment.name }
|
|
286
|
-
}
|
|
333
|
+
source
|
|
287
334
|
};
|
|
288
335
|
}
|
|
289
336
|
const mediaType = attachment.mediaType ?? "application/octet-stream";
|
|
@@ -299,9 +346,11 @@ function userContentToAttachment(content) {
|
|
|
299
346
|
if (content.type === "image") {
|
|
300
347
|
const attachment2 = {
|
|
301
348
|
id: createId("attachment"),
|
|
302
|
-
type: "image"
|
|
303
|
-
...content.detail === void 0 ? {} : { detail: content.detail }
|
|
349
|
+
type: "image"
|
|
304
350
|
};
|
|
351
|
+
if (content.detail !== void 0) {
|
|
352
|
+
attachment2.detail = content.detail;
|
|
353
|
+
}
|
|
305
354
|
if (content.source.type === "url") {
|
|
306
355
|
attachment2.url = content.source.url;
|
|
307
356
|
} else {
|
|
@@ -414,4 +463,4 @@ export {
|
|
|
414
463
|
uiMessagesToCoreMessages,
|
|
415
464
|
coreMessagesToUIMessages
|
|
416
465
|
};
|
|
417
|
-
//# sourceMappingURL=chunk-
|
|
466
|
+
//# sourceMappingURL=chunk-NS7W4G26.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ui/messages.ts"],"sourcesContent":["import { isJsonValue } from \"../completion/json\";\nimport {\n AssistantContent,\n type AssistantContent as AssistantContentType,\n type Message as CoreMessage,\n type DocumentContent,\n type ImageContent,\n type ImageDetail,\n type JsonValue,\n Message,\n reasoningDisplayText,\n serializeToolResultOutput,\n ToolContent,\n type ToolContent as ToolContentType,\n type ToolResultContent,\n UserContent,\n type UserContent as UserContentType,\n} from \"../completion/types\";\nimport type { UIAttachment, UIMessage, UIMessagePart } from \"./types\";\n\ntype UIToolPartLocation = {\n messageIndex: number;\n partIndex: number;\n};\n\ntype UIToolPartLocations = {\n byToolCallId: Map<string, UIToolPartLocation>;\n byCallId: Map<string, UIToolPartLocation>;\n};\n\ntype UIToolMessagePart = Extract<UIMessagePart, { type: \"tool\" }>;\n\nexport function uiMessagesToCoreMessages(messages: UIMessage[]): CoreMessage[] {\n const coreMessages: CoreMessage[] = [];\n\n for (const message of messages) {\n const text = textFromUIParts(message.parts);\n\n if (message.role === \"system\") {\n if (text.length > 0) {\n coreMessages.push(Message.system(text, metadataOptions(message.metadata)));\n }\n continue;\n }\n\n if (message.role === \"user\") {\n const content: UserContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\") {\n content.push(UserContent.text(part.text));\n continue;\n }\n if (part.type === \"attachment\") {\n content.push(attachmentToUserContent(part.attachment));\n continue;\n }\n if (part.type === \"data\" && isUserContent(part.data)) {\n content.push(part.data);\n continue;\n }\n throw new TypeError(\n \"User UI messages can only be converted from text, attachment, or image/document data parts.\",\n );\n }\n if (content.length > 0) {\n coreMessages.push(Message.user(content, metadataOptions(message.metadata)));\n }\n continue;\n }\n\n if (message.role === \"assistant\") {\n const content: AssistantContentType[] = [];\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\" && part.text.length > 0) {\n content.push(AssistantContent.text(part.text));\n continue;\n }\n if (part.type === \"reasoning\" && part.text.length > 0) {\n content.push(AssistantContent.reasoning(part.text, part.reasoningId));\n continue;\n }\n if (\n part.type === \"tool\" &&\n (part.state === \"input-streaming\" ||\n part.state === \"input-available\" ||\n part.state === \"output-available\")\n ) {\n content.push(\n AssistantContent.toolCall(\n part.toolCallId,\n part.toolName,\n part.input ?? {},\n part.callId,\n ),\n );\n if (part.state === \"output-available\") {\n toolResults.push(\n ToolContent.toolResult(part.toolCallId, outputToToolResultContent(part.output), {\n callId: part.callId,\n toolName: part.toolName,\n }),\n );\n }\n }\n }\n if (content.length > 0) {\n coreMessages.push(\n Message.assistant(content, {\n id: message.id,\n ...metadataOptions(message.metadata),\n }),\n );\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults));\n }\n continue;\n }\n\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type !== \"tool\" || part.state !== \"output-available\") {\n continue;\n }\n toolResults.push(\n ToolContent.toolResult(part.toolCallId, outputToToolResultContent(part.output), {\n callId: part.callId,\n toolName: part.toolName,\n }),\n );\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults, metadataOptions(message.metadata)));\n }\n }\n\n return coreMessages;\n}\n\nexport function coreMessagesToUIMessages(messages: CoreMessage[]): UIMessage[] {\n const uiMessages: UIMessage[] = [];\n const toolPartLocations: UIToolPartLocations = {\n byToolCallId: new Map(),\n byCallId: new Map(),\n };\n\n for (const message of messages) {\n if (message.role === \"system\") {\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"system\",\n parts: [{ id: createId(\"part\"), type: \"text\", text: message.content }],\n ...uiMetadata(message.metadata),\n });\n continue;\n }\n\n if (message.role === \"user\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n } else {\n parts.push({\n id: createId(\"part\"),\n type: \"attachment\",\n attachment: userContentToAttachment(content),\n });\n }\n }\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"user\",\n parts,\n ...uiMetadata(message.metadata),\n });\n continue;\n }\n\n if (message.role === \"assistant\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n continue;\n }\n if (content.type === \"reasoning\") {\n const part: UIMessagePart = {\n id: createId(\"part\"),\n type: \"reasoning\",\n text: reasoningDisplayText(content),\n };\n if (content.id !== undefined) {\n part.reasoningId = content.id;\n }\n parts.push(part);\n continue;\n }\n if (content.type === \"tool_call\") {\n const part: UIMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: content.function.name,\n toolCallId: content.id,\n state: \"input-available\",\n input: content.function.arguments,\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n parts.push(part);\n continue;\n }\n parts.push({\n id: createId(\"part\"),\n type: \"data\",\n name: content.type,\n data: content as JsonValue,\n });\n }\n const messageIndex = uiMessages.length;\n uiMessages.push({\n id: message.id ?? createId(\"msg\"),\n role: \"assistant\",\n parts,\n ...uiMetadata(message.metadata),\n });\n registerToolPartLocations(parts, messageIndex, toolPartLocations);\n continue;\n }\n\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n const part: UIToolMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: toolNameForResult(content, uiMessages, toolPartLocations),\n toolCallId: content.id,\n state: \"output-available\",\n output: toolResultContentToJson(content.content),\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n if (\n message.metadata === undefined &&\n mergeToolResultPart(uiMessages, toolPartLocations, part)\n ) {\n continue;\n }\n parts.push(part);\n }\n if (parts.length > 0) {\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"tool\",\n parts,\n ...uiMetadata(message.metadata),\n });\n }\n }\n\n return uiMessages;\n}\n\nfunction metadataOptions(metadata: UIMessage[\"metadata\"]): { metadata?: JsonValue } {\n if (metadata === undefined) {\n return {};\n }\n if (!isJsonValue(metadata)) {\n throw new TypeError(\"UI message metadata must be a strict JSON value.\");\n }\n return { metadata };\n}\n\nfunction uiMetadata(metadata: JsonValue | undefined): { metadata?: JsonValue } {\n if (metadata === undefined) {\n return {};\n }\n if (!isJsonValue(metadata)) {\n throw new TypeError(\"Core message metadata must be a strict JSON value.\");\n }\n return { metadata };\n}\n\nfunction registerToolPartLocations(\n parts: UIMessagePart[],\n messageIndex: number,\n toolPartLocations: UIToolPartLocations,\n): void {\n for (const [partIndex, part] of parts.entries()) {\n if (part.type !== \"tool\") {\n continue;\n }\n const location = { messageIndex, partIndex };\n toolPartLocations.byToolCallId.set(part.toolCallId, location);\n if (part.callId !== undefined) {\n toolPartLocations.byCallId.set(part.callId, location);\n }\n }\n}\n\nfunction mergeToolResultPart(\n uiMessages: UIMessage[],\n toolPartLocations: UIToolPartLocations,\n resultPart: UIMessagePart,\n): boolean {\n if (resultPart.type !== \"tool\") {\n return false;\n }\n\n const location = findToolPartLocation(\n resultPart.toolCallId,\n resultPart.callId,\n toolPartLocations,\n );\n if (location === undefined) {\n return false;\n }\n\n const message = uiMessages[location.messageIndex];\n const currentPart = message?.parts[location.partIndex];\n if (message === undefined || currentPart?.type !== \"tool\") {\n return false;\n }\n\n const mergedPart: UIToolMessagePart = {\n ...currentPart,\n toolName: resultPart.toolName === \"tool\" ? currentPart.toolName : resultPart.toolName,\n state: \"output-available\",\n };\n if (resultPart.output !== undefined) {\n mergedPart.output = resultPart.output;\n }\n if (currentPart.callId === undefined && resultPart.callId !== undefined) {\n mergedPart.callId = resultPart.callId;\n toolPartLocations.byCallId.set(resultPart.callId, location);\n }\n\n const nextParts = [...message.parts];\n nextParts[location.partIndex] = mergedPart;\n uiMessages[location.messageIndex] = { ...message, parts: nextParts };\n return true;\n}\n\nfunction findToolPartLocation(\n toolCallId: string,\n callId: string | undefined,\n toolPartLocations: UIToolPartLocations,\n): UIToolPartLocation | undefined {\n return (\n (callId === undefined ? undefined : toolPartLocations.byCallId.get(callId)) ??\n toolPartLocations.byToolCallId.get(toolCallId)\n );\n}\n\nfunction toolNameForResult(\n content: ToolContentType,\n uiMessages: UIMessage[],\n toolPartLocations: UIToolPartLocations,\n): string {\n if (content.toolName !== undefined) {\n return content.toolName;\n }\n\n const location = findToolPartLocation(content.id, content.callId, toolPartLocations);\n const part =\n location === undefined\n ? undefined\n : uiMessages[location.messageIndex]?.parts[location.partIndex];\n return part?.type === \"tool\" ? part.toolName : \"tool\";\n}\n\nexport function isUIMessage(value: unknown): value is UIMessage {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n isUIMessageRole(value.role) &&\n Array.isArray(value.parts)\n );\n}\n\nexport function isUIMessageArray(value: unknown): value is UIMessage[] {\n return Array.isArray(value) && value.every(isUIMessage);\n}\n\nfunction textFromUIParts(parts: UIMessagePart[]): string {\n return parts.flatMap((part) => (part.type === \"text\" ? [part.text] : [])).join(\"\");\n}\n\nfunction outputToToolResultContent(output: JsonValue | undefined): ToolResultContent[] {\n return [{ type: \"text\", text: serializeToolResultOutput(output ?? null) }];\n}\n\nfunction attachmentToUserContent(attachment: UIAttachment): UserContentType {\n if (attachment.type === \"image\" || isImageFileAttachment(attachment)) {\n if (attachment.url !== undefined) {\n return UserContent.imageUrl(attachment.url, imageOptions(attachment));\n }\n if (attachment.data !== undefined && attachment.mediaType !== undefined) {\n return UserContent.imageBase64(\n attachment.data,\n attachment.mediaType,\n imageOptions(attachment),\n );\n }\n throw new TypeError(\"Image attachments require a url or base64 data with mediaType.\");\n }\n\n if (attachment.text !== undefined) {\n const source: Extract<DocumentContent[\"source\"], { type: \"text\" }> = {\n type: \"text\",\n text: attachment.text,\n };\n if (attachment.mediaType !== undefined) {\n source.mediaType = attachment.mediaType;\n }\n if (attachment.name !== undefined) {\n source.filename = attachment.name;\n }\n return {\n type: \"document\",\n source,\n };\n }\n\n const mediaType = attachment.mediaType ?? \"application/octet-stream\";\n if (attachment.url !== undefined) {\n return UserContent.documentUrl(attachment.url, mediaType, documentOptions(attachment));\n }\n if (attachment.data !== undefined) {\n return UserContent.documentBase64(attachment.data, mediaType, documentOptions(attachment));\n }\n\n throw new TypeError(\"Document attachments require a url, base64 data, or text.\");\n}\n\nfunction userContentToAttachment(content: ImageContent | DocumentContent): UIAttachment {\n if (content.type === \"image\") {\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"image\",\n };\n if (content.detail !== undefined) {\n attachment.detail = content.detail;\n }\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n } else {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n }\n return attachment;\n }\n\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"document\",\n };\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else if (content.source.type === \"base64\") {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else {\n attachment.text = content.source.text;\n if (content.source.mediaType !== undefined) {\n attachment.mediaType = content.source.mediaType;\n }\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n }\n return attachment;\n}\n\nfunction isImageFileAttachment(attachment: UIAttachment): boolean {\n return attachment.type === \"file\" && attachment.mediaType?.startsWith(\"image/\") === true;\n}\n\nfunction imageOptions(attachment: UIAttachment): { detail?: ImageDetail } {\n return attachment.detail === undefined ? {} : { detail: attachment.detail };\n}\n\nfunction documentOptions(attachment: UIAttachment): { filename?: string } {\n return attachment.name === undefined ? {} : { filename: attachment.name };\n}\n\nfunction toolResultContentToJson(content: ToolResultContent[]): JsonValue {\n if (content.length === 1 && content[0]?.type === \"text\") {\n return content[0].text;\n }\n return content as JsonValue;\n}\n\nfunction isUserContent(value: unknown): value is UserContentType {\n if (!isRecord(value)) {\n return false;\n }\n\n if (value.type === \"text\") {\n return typeof value.text === \"string\";\n }\n\n if (value.type === \"image\") {\n return isImageContent(value);\n }\n\n if (value.type === \"document\") {\n return isDocumentContent(value);\n }\n\n return false;\n}\n\nfunction isImageContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n return false;\n}\n\nfunction isDocumentContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"text\") {\n return (\n typeof value.source.text === \"string\" &&\n (value.source.mediaType === undefined || typeof value.source.mediaType === \"string\")\n );\n }\n\n return false;\n}\n\nfunction toolPartId(toolCallId: string): string {\n return `tool_${toolCallId}`;\n}\n\nlet nextId = 0;\n\nfunction createId(prefix: string): string {\n const random = globalThis.crypto?.randomUUID?.();\n if (random !== undefined) {\n return `${prefix}_${random}`;\n }\n nextId += 1;\n return `${prefix}_${nextId.toString(36)}`;\n}\n\nfunction isUIMessageRole(value: unknown): value is UIMessage[\"role\"] {\n return value === \"system\" || value === \"user\" || value === \"assistant\" || value === \"tool\";\n}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EA,SAAO;AACT;AAEA,SAAS,WAAW,YAA4B;AAC9C,SAAO,QAAQ,UAAU;AAC3B;AAEA,IAAI,SAAS;AAEb,SAAS,SAAS,QAAwB;AACxC,QAAM,SAAS,WAAW,QAAQ,aAAa;AAC/C,MAAI,WAAW,QAAW;AACxB,WAAO,GAAG,MAAM,IAAI,MAAM;AAAA,EAC5B;AACA,YAAU;AACV,SAAO,GAAG,MAAM,IAAI,OAAO,SAAS,EAAE,CAAC;AACzC;AAMA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":["toolResults","parts","attachment"]}
|
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
InMemoryVectorStore,
|
|
3
3
|
createTool
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import {
|
|
6
|
-
compact
|
|
7
|
-
} from "./chunk-MMHG7WAM.js";
|
|
8
|
-
import {
|
|
9
|
-
embedDocuments
|
|
10
|
-
} from "./chunk-JS5MGVNM.js";
|
|
4
|
+
} from "./chunk-I7TM7TKX.js";
|
|
11
5
|
import {
|
|
12
6
|
isToolResultContentArray,
|
|
13
7
|
serializeToolResultOutput
|
|
14
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-CNTGKNZ3.js";
|
|
9
|
+
import {
|
|
10
|
+
embedDocuments
|
|
11
|
+
} from "./chunk-YBBD4HZ3.js";
|
|
15
12
|
|
|
16
13
|
// src/tool/errors.ts
|
|
17
14
|
var ToolCallError = class extends Error {
|
|
@@ -131,12 +128,14 @@ async function embedTools(model, tools, options = {}) {
|
|
|
131
128
|
const content = options.content?.(tool, definition) ?? defaultToolEmbeddingText(definition);
|
|
132
129
|
const texts = Array.isArray(content) ? content : [content];
|
|
133
130
|
const metadata = options.metadata?.(tool, definition);
|
|
134
|
-
const document =
|
|
131
|
+
const document = {
|
|
135
132
|
toolName: tool.name,
|
|
136
133
|
definition,
|
|
137
|
-
text: texts.join("\n")
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
text: texts.join("\n")
|
|
135
|
+
};
|
|
136
|
+
if (metadata !== void 0) {
|
|
137
|
+
document.metadata = metadata;
|
|
138
|
+
}
|
|
140
139
|
return { tool, document, texts, metadata };
|
|
141
140
|
});
|
|
142
141
|
return embedDocuments(model, documents, {
|
|
@@ -225,4 +224,4 @@ export {
|
|
|
225
224
|
createToolMiddleware,
|
|
226
225
|
createThinkTool
|
|
227
226
|
};
|
|
228
|
-
//# sourceMappingURL=chunk-
|
|
227
|
+
//# sourceMappingURL=chunk-WHHQWT7D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tool/errors.ts","../src/tool/tool.ts","../src/tool/tool-set.ts","../src/tool/dynamic-tools.ts","../src/tool/middleware.ts","../src/tool/think-tool.ts"],"sourcesContent":["export class ToolCallError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"ToolCallError\";\n }\n}\n\nexport class ToolNotFoundError extends Error {\n constructor(readonly toolName: string) {\n super(`Tool not found: ${toolName}`);\n this.name = \"ToolNotFoundError\";\n }\n}\n\nexport class ToolJsonError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"ToolJsonError\";\n }\n}\n","import type { JsonObject, JsonValue, ToolDefinition, ToolResultContent } from \"../completion/types\";\nimport {\n isToolResultContentArray,\n serializeToolResultOutput as serializeToolOutput,\n} from \"../completion/types\";\n\nexport type ToolApprovalRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string;\n metadata?: JsonObject;\n};\n\nexport type ToolApprovalContext<Args = unknown> = {\n toolName: string;\n args: Args;\n rawArgs: string;\n toolCallId?: string;\n internalCallId: string;\n run: ToolApprovalRunContext;\n};\n\nexport type ToolApprovalPolicy<Args = unknown> = {\n when(ctx: ToolApprovalContext<Args>): boolean | Promise<boolean>;\n reason?: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>);\n rejectMessage?: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>);\n};\n\nexport type ToolApprovalRequest<Args = unknown> = ToolApprovalContext<Args> & {\n reason?: string;\n rejectMessage?: string;\n};\n\nexport type ToolApprovalDecision =\n | boolean\n | { approved: true; reason?: string }\n | { approved: false; reason?: string; rejectMessage?: string };\n\nexport type ToolApprovalsOptions = {\n handler(request: ToolApprovalRequest): ToolApprovalDecision | Promise<ToolApprovalDecision>;\n};\n\nexport type ToolCallStreamEvent = {\n agentId: string;\n agentName?: string | undefined;\n event: unknown;\n};\n\nexport type ToolCallContext = {\n emitStreamEvent?(event: ToolCallStreamEvent): void | Promise<void>;\n};\n\nexport interface Tool<Args = unknown, Output = unknown> {\n readonly name: string;\n readonly approval?: ToolApprovalPolicy<Args>;\n definition(prompt: string): ToolDefinition | Promise<ToolDefinition>;\n call(args: Args, context?: ToolCallContext): Output | Promise<Output>;\n parseApprovalArgs?(args: unknown): Args;\n}\n\nexport type AnyTool = Omit<Tool<unknown, unknown>, \"approval\"> & {\n readonly approval?: unknown;\n};\n\nexport type NormalizedToolOutput = string | ToolResultContent[];\n\nexport const ToolOutput = {\n content(content: ToolResultContent[]): ToolResultContent[] {\n return content;\n },\n};\n\nexport { isToolResultContentArray, serializeToolOutput };\n\nexport function normalizeToolResultOutput(output: unknown): NormalizedToolOutput {\n return isToolResultContentArray(output) ? output : serializeToolOutput(output);\n}\n\nexport function toolResultContentToText(content: ToolResultContent[]): string {\n return content\n .map((item) => (item.type === \"text\" ? item.text : `[image:${item.mediaType ?? \"image/png\"}]`))\n .join(\"\\n\");\n}\n\nexport function parseToolArgs(args: string): JsonValue {\n if (args.trim() === \"\") {\n return {};\n }\n\n return JSON.parse(args) as JsonValue;\n}\n","import type { ToolDefinition } from \"../completion/types\";\nimport { ToolCallError, ToolJsonError, ToolNotFoundError } from \"./errors\";\nimport {\n type AnyTool,\n type NormalizedToolOutput,\n normalizeToolResultOutput,\n parseToolArgs,\n type ToolCallContext,\n} from \"./tool\";\n\nexport class ToolSet {\n private readonly tools = new Map<string, AnyTool>();\n\n static fromTools(tools: AnyTool[]): ToolSet {\n const toolSet = new ToolSet();\n for (const tool of tools) {\n toolSet.addTool(tool);\n }\n return toolSet;\n }\n\n addTool(tool: AnyTool): this {\n this.tools.set(tool.name, tool);\n return this;\n }\n\n addTools(tools: AnyTool[] | ToolSet): this {\n const values = Array.isArray(tools) ? tools : tools.values();\n for (const tool of values) {\n this.addTool(tool);\n }\n return this;\n }\n\n deleteTool(toolName: string): boolean {\n return this.tools.delete(toolName);\n }\n\n contains(toolName: string): boolean {\n return this.tools.has(toolName);\n }\n\n get(toolName: string): AnyTool | undefined {\n return this.tools.get(toolName);\n }\n\n values(): AnyTool[] {\n return [...this.tools.values()];\n }\n\n async getToolDefinitions(prompt = \"\"): Promise<ToolDefinition[]> {\n const defs: ToolDefinition[] = [];\n for (const tool of this.tools.values()) {\n defs.push(await tool.definition(prompt));\n }\n return defs;\n }\n\n async call(\n toolName: string,\n args: string,\n context?: ToolCallContext,\n ): Promise<NormalizedToolOutput> {\n const tool = this.tools.get(toolName);\n if (tool === undefined) {\n throw new ToolNotFoundError(toolName);\n }\n\n let parsedArgs: unknown;\n try {\n parsedArgs = parseToolArgs(args);\n } catch (error) {\n throw new ToolJsonError(`Invalid JSON arguments for tool ${toolName}`, error);\n }\n\n try {\n const output = await tool.call(parsedArgs, context);\n return normalizeToolResultOutput(output);\n } catch (error) {\n if (error instanceof Error) {\n throw new ToolCallError(error.message, error);\n }\n throw new ToolCallError(`Tool ${toolName} failed`, error);\n }\n }\n}\n","import type { ToolDefinition } from \"../completion\";\nimport type { EmbeddedDocument, EmbeddingModel, VectorMetadata } from \"../embeddings\";\nimport { embedDocuments } from \"../embeddings\";\nimport type {\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n} from \"../vector-store\";\nimport {\n InMemoryVectorStore,\n type VectorSearchIndex,\n type VectorSearchRequest,\n} from \"../vector-store\";\nimport type { AnyTool, Tool } from \"./tool\";\nimport { ToolSet } from \"./tool-set\";\n\nexport type ToolSearchDocument<Metadata extends VectorMetadata = VectorMetadata> = {\n toolName: string;\n definition: ToolDefinition;\n text: string;\n metadata?: Metadata | undefined;\n};\n\nexport type EmbedToolsOptions<Metadata extends VectorMetadata = VectorMetadata> = {\n content?: ((tool: AnyTool, definition: ToolDefinition) => string | string[]) | undefined;\n metadata?: ((tool: AnyTool, definition: ToolDefinition) => Metadata | undefined) | undefined;\n concurrency?: number | undefined;\n};\n\nexport interface DynamicToolIndex<Metadata extends VectorMetadata = VectorMetadata>\n extends VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata> {\n readonly toolSet: ToolSet;\n}\n\nexport async function embedTools<Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n tools: AnyTool[] | ToolSet,\n options: EmbedToolsOptions<Metadata> = {},\n): Promise<Array<EmbeddedDocument<ToolSearchDocument<Metadata>, Metadata>>> {\n const toolList = Array.isArray(tools) ? tools : tools.values();\n const definitions = await Promise.all(\n toolList.map(async (tool) => ({ tool, definition: await tool.definition(\"\") })),\n );\n const documents = definitions.map(({ tool, definition }) => {\n const content = options.content?.(tool, definition) ?? defaultToolEmbeddingText(definition);\n const texts = Array.isArray(content) ? content : [content];\n const metadata = options.metadata?.(tool, definition);\n const document: ToolSearchDocument<Metadata> = {\n toolName: tool.name,\n definition,\n text: texts.join(\"\\n\"),\n };\n if (metadata !== undefined) {\n document.metadata = metadata;\n }\n return { tool, document, texts, metadata };\n });\n\n return embedDocuments(model, documents, {\n id: (item) => item.tool.name,\n content: (item) => item.texts,\n metadata: (item) => item.metadata,\n concurrency: options.concurrency,\n }).then((embedded) =>\n embedded.map((item) => ({\n ...item,\n document: item.document.document,\n })),\n );\n}\n\nexport async function createToolIndex<Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n tools: AnyTool[] | ToolSet,\n options: EmbedToolsOptions<Metadata> = {},\n): Promise<DynamicToolIndex<Metadata>> {\n const toolSet = Array.isArray(tools) ? ToolSet.fromTools(tools) : tools;\n const embedded = await embedTools(model, toolSet, options);\n const index = InMemoryVectorStore.fromDocuments(embedded).index(model);\n return new DynamicToolSearchIndex(index, toolSet);\n}\n\nexport function isDynamicToolIndex(value: unknown): value is DynamicToolIndex {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"toolSet\" in value &&\n (value as { toolSet?: unknown }).toolSet instanceof ToolSet\n );\n}\n\nclass DynamicToolSearchIndex<Metadata extends VectorMetadata>\n implements DynamicToolIndex<Metadata>\n{\n readonly inspect?: (\n request: VectorInspectRequest,\n ) => Promise<VectorInspectPage<ToolSearchDocument<Metadata>, Metadata>>;\n\n constructor(\n private readonly index: VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata>,\n readonly toolSet: ToolSet,\n ) {\n if (index.inspect !== undefined) {\n this.inspect = (request) =>\n index.inspect?.(request) as Promise<\n VectorInspectPage<ToolSearchDocument<Metadata>, Metadata>\n >;\n }\n }\n\n search(\n request: VectorSearchRequest,\n ): Promise<Array<VectorSearchResult<ToolSearchDocument<Metadata>, Metadata>>> {\n return this.index.search(request);\n }\n\n searchIds(request: VectorSearchRequest): Promise<Array<{ score: number; id: string }>> {\n return this.index.searchIds(request);\n }\n\n asTool(options: VectorSearchToolOptions): Tool<{ query: string; topK?: number }, unknown> {\n return this.index.asTool(options);\n }\n}\n\nfunction defaultToolEmbeddingText(definition: ToolDefinition): string[] {\n return [definition.name, definition.description, JSON.stringify(definition.parameters)];\n}\n","import type {\n CompletionRequest,\n CompletionResponse,\n JsonValue,\n ToolResultContent,\n} from \"../completion\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type CompletionRequestMiddlewareArgs = {\n turn: number;\n request: CompletionRequest;\n originalRequest: CompletionRequest;\n};\n\nexport type CompletionRequestMiddlewareResult =\n | {\n request: CompletionRequest;\n }\n | undefined;\n\nexport type CompletionResponseMiddlewareArgs<RawResponse = unknown> = {\n turn: number;\n request: CompletionRequest;\n response: CompletionResponse<RawResponse>;\n originalResponse: CompletionResponse<RawResponse>;\n};\n\nexport type CompletionResponseMiddlewareResult<RawResponse = unknown> =\n | {\n response: CompletionResponse<RawResponse>;\n }\n | undefined;\n\nexport type ToolInputMiddlewareArgs = {\n toolName: string;\n args: string;\n originalArgs: string;\n turn: number;\n toolCallId?: string | undefined;\n internalCallId: string;\n};\n\nexport type ToolInputMiddlewareResult =\n | {\n args: JsonValue | string;\n }\n | undefined;\n\nexport type ToolResultMiddlewareArgs = {\n toolName: string;\n args: string;\n result: string;\n originalResult: string;\n structuredResult?: ToolResultContent[] | undefined;\n originalStructuredResult?: ToolResultContent[] | undefined;\n turn: number;\n toolCallId?: string | undefined;\n internalCallId: string;\n};\n\nexport type ToolOutputMiddlewareArgs = ToolResultMiddlewareArgs;\n\nexport type ToolOutputMiddlewareResult =\n | string\n | {\n result?: string | undefined;\n structuredResult?: ToolResultContent[] | undefined;\n }\n | undefined;\n\nexport interface AgentMiddleware<RawResponse = unknown> {\n onCompletionRequest?(\n args: CompletionRequestMiddlewareArgs,\n ): MaybePromise<CompletionRequestMiddlewareResult>;\n onCompletionResponse?(\n args: CompletionResponseMiddlewareArgs<RawResponse>,\n ): MaybePromise<CompletionResponseMiddlewareResult<RawResponse>>;\n onToolInput?(args: ToolInputMiddlewareArgs): MaybePromise<ToolInputMiddlewareResult>;\n onToolOutput?(args: ToolOutputMiddlewareArgs): MaybePromise<ToolOutputMiddlewareResult>;\n /**\n * @deprecated Use `onToolOutput` instead.\n */\n onResult?(args: ToolResultMiddlewareArgs): string | undefined | Promise<string | undefined>;\n}\n\n/**\n * @deprecated Use `AgentMiddleware` instead.\n */\nexport type ToolMiddleware<RawResponse = unknown> = AgentMiddleware<RawResponse>;\n\nexport function createMiddleware<RawResponse = unknown>(\n middleware: AgentMiddleware<RawResponse>,\n): AgentMiddleware<RawResponse> {\n return middleware;\n}\n\n/**\n * @deprecated Use `createMiddleware` instead.\n */\nexport function createToolMiddleware<RawResponse = unknown>(\n middleware: ToolMiddleware<RawResponse>,\n): ToolMiddleware<RawResponse> {\n return middleware;\n}\n","import { z } from \"zod\";\nimport { createTool } from \"./create-tool\";\n\nconst defaultThinkToolDescription =\n \"Use this tool to record a thought while reasoning through a complex task. It does not retrieve information, store memory, or change external state.\";\n\nconst thinkToolInput = z.object({\n thought: z.string().describe(\"A thought to record while reasoning through a task.\"),\n});\n\nexport type CreateThinkToolOptions = {\n name?: string;\n description?: string;\n};\n\nexport function createThinkTool(options: CreateThinkToolOptions = {}) {\n return createTool({\n name: options.name ?? \"think\",\n description: options.description ?? defaultThinkToolDescription,\n input: thinkToolInput,\n output: z.string(),\n execute: (args) => args.thought,\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAAO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACE,SACS,OACT;AACA,UAAM,OAAO;AAFJ;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EAJW;AAKb;AAEO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAqB,UAAkB;AACrC,UAAM,mBAAmB,QAAQ,EAAE;AADhB;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAEO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACE,SACS,OACT;AACA,UAAM,OAAO;AAFJ;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EAJW;AAKb;;;ACyCO,IAAM,aAAa;AAAA,EACxB,QAAQ,SAAmD;AACzD,WAAO;AAAA,EACT;AACF;AAIO,SAAS,0BAA0B,QAAuC;AAC/E,SAAO,yBAAyB,MAAM,IAAI,SAAS,0BAAoB,MAAM;AAC/E;AAEO,SAAS,wBAAwB,SAAsC;AAC5E,SAAO,QACJ,IAAI,CAAC,SAAU,KAAK,SAAS,SAAS,KAAK,OAAO,UAAU,KAAK,aAAa,WAAW,GAAI,EAC7F,KAAK,IAAI;AACd;AAEO,SAAS,cAAc,MAAyB;AACrD,MAAI,KAAK,KAAK,MAA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