@anvia/core 0.26.0 → 1.0.0-rc.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/README.md +21 -11
- package/dist/agent/index.d.ts +26 -68
- package/dist/agent/index.js +20 -17
- package/dist/agent-DGYY_onS.d.ts +145 -0
- package/dist/audio-generation/index.d.ts +12 -14
- package/dist/audio-generation/index.js +5 -39
- package/dist/audio-generation/index.js.map +1 -1
- package/dist/{chunk-MRQLEK2B.js → chunk-5XKDW36Z.js} +30 -7
- package/dist/chunk-5XKDW36Z.js.map +1 -0
- package/dist/chunk-6WGGTJE6.js +139 -0
- package/dist/chunk-6WGGTJE6.js.map +1 -0
- package/dist/chunk-A3UBYTJT.js +157 -0
- package/dist/chunk-A3UBYTJT.js.map +1 -0
- package/dist/{chunk-NCPN4SJR.js → chunk-DMPUP4R3.js} +10 -10
- package/dist/chunk-DMPUP4R3.js.map +1 -0
- package/dist/{chunk-MNWK2USR.js → chunk-DZ3CKYTH.js} +29 -5
- package/dist/chunk-DZ3CKYTH.js.map +1 -0
- package/dist/{chunk-CWUJUSOS.js → chunk-FNQB2JEH.js} +1 -1
- package/dist/chunk-FNQB2JEH.js.map +1 -0
- package/dist/chunk-I6G7BC42.js +41 -0
- package/dist/chunk-I6G7BC42.js.map +1 -0
- package/dist/{chunk-BALBBVI3.js → chunk-IL3ZSNJI.js} +2720 -1704
- package/dist/chunk-IL3ZSNJI.js.map +1 -0
- package/dist/chunk-J6GNQART.js +122 -0
- package/dist/chunk-J6GNQART.js.map +1 -0
- package/dist/{chunk-MC3CCKEB.js → chunk-M3IOWB4Y.js} +124 -65
- package/dist/chunk-M3IOWB4Y.js.map +1 -0
- package/dist/chunk-QY5GZ7HR.js +39 -0
- package/dist/chunk-QY5GZ7HR.js.map +1 -0
- package/dist/{chunk-MELYDKWQ.js → chunk-R2LJSQUW.js} +190 -20
- package/dist/chunk-R2LJSQUW.js.map +1 -0
- package/dist/{chunk-WQKHFADH.js → chunk-RFDVKCIE.js} +3 -3
- package/dist/chunk-RFDVKCIE.js.map +1 -0
- package/dist/chunk-RMUBRRSK.js +34 -0
- package/dist/chunk-RMUBRRSK.js.map +1 -0
- package/dist/{chunk-I6XOQ4LK.js → chunk-RXKHOYEH.js} +1 -1
- package/dist/chunk-RXKHOYEH.js.map +1 -0
- package/dist/chunk-XDRSPSR7.js +38 -0
- package/dist/chunk-XDRSPSR7.js.map +1 -0
- package/dist/completion/index.d.ts +5 -36
- package/dist/completion/index.js +4 -5
- package/dist/dynamic-tools-i9woysFa.d.ts +33 -0
- package/dist/embeddings/index.d.ts +2 -2
- package/dist/embeddings/index.js +1 -2
- package/dist/{errors-2moLDuuN.d.ts → errors-CYKUcU89.d.ts} +2 -2
- package/dist/evals/index.d.ts +22 -15
- package/dist/evals/index.js +57 -35
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +23 -35
- package/dist/extractor/index.js +7 -21
- package/dist/guardrails/index.d.ts +2 -2
- package/dist/guardrails/index.js +1 -1
- package/dist/image-generation/index.d.ts +12 -14
- package/dist/image-generation/index.js +5 -39
- package/dist/image-generation/index.js.map +1 -1
- package/dist/index-DxB74ybJ.d.ts +349 -0
- package/dist/index.d.ts +20 -17
- package/dist/index.js +31 -36
- package/dist/internal/agent.d.ts +152 -9
- package/dist/internal/agent.js +22 -17
- package/dist/{json-BVPssigK.d.ts → json-Zo7K3xmt.d.ts} +12 -11
- package/dist/loaders/index.d.ts +5 -10
- package/dist/loaders/index.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/memory/index.d.ts +4 -4
- package/dist/memory/index.js +6 -7
- package/dist/middleware-KynLg_RW.d.ts +56 -0
- package/dist/observability/index.d.ts +6 -3
- package/dist/observability/index.js.map +1 -1
- package/dist/pipeline/index.d.ts +40 -47
- package/dist/pipeline/index.js +99 -99
- package/dist/pipeline/index.js.map +1 -1
- package/dist/retry-D3Ruy-ba.d.ts +15 -0
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +5 -6
- package/dist/streaming/index.js +37 -3
- package/dist/streaming/index.js.map +1 -1
- package/dist/{think-tool-DfCMuO8e.d.ts → think-tool-DZqZj2LV.d.ts} +5 -5
- package/dist/tool/index.d.ts +8 -6
- package/dist/tool/index.js +12 -15
- package/dist/tool-C_8GudXn.d.ts +49 -0
- package/dist/transcription/index.d.ts +14 -16
- package/dist/transcription/index.js +5 -57
- package/dist/transcription/index.js.map +1 -1
- package/dist/type-utils-CtHVDRn_.d.ts +6 -0
- package/dist/{types-G12i56s2.d.ts → types-B3A4YxaA.d.ts} +1 -1
- package/dist/{types-BrLbKnEz.d.ts → types-BBEGKB9m.d.ts} +1 -1
- package/dist/{types-O-abTIin.d.ts → types-DT3nEemY.d.ts} +3 -3
- package/dist/{types-04LqWrmy.d.ts → types-DhQfwiZn.d.ts} +1 -1
- package/dist/{types-JJCxRnaZ.d.ts → types-DulRCYdB.d.ts} +2 -2
- package/dist/{types-BCTRUGex.d.ts → types-p55Jc-sr.d.ts} +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +1 -1
- package/dist/vector-store/index.d.ts +5 -5
- package/dist/vector-store/index.js +4 -4
- package/package.json +2 -10
- package/dist/agent-x3YTyv5i.d.ts +0 -222
- package/dist/chunk-2ODTMRHP.js +0 -54
- package/dist/chunk-2ODTMRHP.js.map +0 -1
- package/dist/chunk-BALBBVI3.js.map +0 -1
- package/dist/chunk-CWUJUSOS.js.map +0 -1
- package/dist/chunk-DALYP4PX.js +0 -225
- package/dist/chunk-DALYP4PX.js.map +0 -1
- package/dist/chunk-HYUYZEAJ.js +0 -223
- package/dist/chunk-HYUYZEAJ.js.map +0 -1
- package/dist/chunk-I6XOQ4LK.js.map +0 -1
- package/dist/chunk-JI5YZWNT.js +0 -220
- package/dist/chunk-JI5YZWNT.js.map +0 -1
- package/dist/chunk-MC3CCKEB.js.map +0 -1
- package/dist/chunk-MELYDKWQ.js.map +0 -1
- package/dist/chunk-MNWK2USR.js.map +0 -1
- package/dist/chunk-MRQLEK2B.js.map +0 -1
- package/dist/chunk-NCPN4SJR.js.map +0 -1
- package/dist/chunk-OIMLU4SF.js +0 -20
- package/dist/chunk-OIMLU4SF.js.map +0 -1
- package/dist/chunk-Q25IWLBT.js +0 -138
- package/dist/chunk-Q25IWLBT.js.map +0 -1
- package/dist/chunk-UQX6EXWG.js +0 -33
- package/dist/chunk-UQX6EXWG.js.map +0 -1
- package/dist/chunk-WQKHFADH.js.map +0 -1
- package/dist/chunk-XUUY2L2D.js +0 -42
- package/dist/chunk-XUUY2L2D.js.map +0 -1
- package/dist/chunk-YLMDBQO4.js +0 -141
- package/dist/chunk-YLMDBQO4.js.map +0 -1
- package/dist/hooks/index.d.ts +0 -12
- package/dist/hooks/index.js +0 -17
- package/dist/hooks/index.js.map +0 -1
- package/dist/index-BxSbmOMr.d.ts +0 -257
- package/dist/middleware-Dp3d_pxi.d.ts +0 -90
- package/dist/request/index.d.ts +0 -28
- package/dist/request/index.js +0 -25
- package/dist/request/index.js.map +0 -1
- package/dist/tool-Cohdv5GC.d.ts +0 -65
- package/dist/types-D9JpeAPF.d.ts +0 -114
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InMemoryVectorStore,
|
|
3
|
+
createTool
|
|
4
|
+
} from "./chunk-R2LJSQUW.js";
|
|
5
|
+
import {
|
|
6
|
+
embedDocuments
|
|
7
|
+
} from "./chunk-DZ3CKYTH.js";
|
|
8
|
+
|
|
9
|
+
// src/internal/vector-search-options.ts
|
|
10
|
+
function assertPositiveSearchLimit(value, name = "topK") {
|
|
11
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
12
|
+
throw new RangeError(`${name} must be a positive safe integer.`);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function assertFiniteSearchThreshold(value, name = "threshold") {
|
|
17
|
+
if (value !== void 0 && !Number.isFinite(value)) {
|
|
18
|
+
throw new RangeError(`${name} must be a finite number.`);
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/tool/dynamic-tools.ts
|
|
24
|
+
async function embedTools(model, tools, options = {}) {
|
|
25
|
+
const toolList = dedupeTools(tools);
|
|
26
|
+
const definitions = await Promise.all(
|
|
27
|
+
toolList.map(async (tool) => ({ tool, definition: await tool.definition("") }))
|
|
28
|
+
);
|
|
29
|
+
const documents = definitions.map(({ tool, definition }) => {
|
|
30
|
+
const content = options.content?.(tool, definition) ?? defaultToolEmbeddingText(definition);
|
|
31
|
+
const texts = Array.isArray(content) ? content : [content];
|
|
32
|
+
const metadata = options.metadata?.(tool, definition);
|
|
33
|
+
const document = {
|
|
34
|
+
toolName: tool.name,
|
|
35
|
+
definition,
|
|
36
|
+
text: texts.join("\n")
|
|
37
|
+
};
|
|
38
|
+
if (metadata !== void 0) {
|
|
39
|
+
document.metadata = metadata;
|
|
40
|
+
}
|
|
41
|
+
return { tool, document, texts, metadata };
|
|
42
|
+
});
|
|
43
|
+
return embedDocuments(model, documents, {
|
|
44
|
+
id: (item) => item.tool.name,
|
|
45
|
+
content: (item) => item.texts,
|
|
46
|
+
metadata: (item) => item.metadata,
|
|
47
|
+
concurrency: options.concurrency
|
|
48
|
+
}).then(
|
|
49
|
+
(embedded) => embedded.map((item) => ({
|
|
50
|
+
...item,
|
|
51
|
+
document: item.document.document
|
|
52
|
+
}))
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
async function createToolIndex(model, tools, options) {
|
|
56
|
+
assertPositiveSearchLimit(options.topK);
|
|
57
|
+
assertFiniteSearchThreshold(options.threshold);
|
|
58
|
+
const toolList = dedupeTools(tools);
|
|
59
|
+
const embedded = await embedTools(model, toolList, options);
|
|
60
|
+
const index = InMemoryVectorStore.fromDocuments(embedded).index(model);
|
|
61
|
+
return new ToolSearchIndex(index, toolList, options);
|
|
62
|
+
}
|
|
63
|
+
function isToolIndex(value) {
|
|
64
|
+
if (typeof value !== "object" || value === null) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const candidate = value;
|
|
68
|
+
return candidate.kind === "tool-index" && Array.isArray(candidate.tools) && typeof candidate.topK === "number" && typeof candidate.search === "function" && typeof candidate.searchIds === "function" && typeof candidate.asTool === "function";
|
|
69
|
+
}
|
|
70
|
+
var ToolSearchIndex = class {
|
|
71
|
+
constructor(index, tools, options) {
|
|
72
|
+
this.index = index;
|
|
73
|
+
this.tools = Object.freeze([...tools]);
|
|
74
|
+
this.topK = options.topK;
|
|
75
|
+
this.threshold = options.threshold;
|
|
76
|
+
this.filter = options.filter;
|
|
77
|
+
if (index.inspect !== void 0) {
|
|
78
|
+
this.inspect = (request) => index.inspect?.(request);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
index;
|
|
82
|
+
kind = "tool-index";
|
|
83
|
+
tools;
|
|
84
|
+
topK;
|
|
85
|
+
threshold;
|
|
86
|
+
filter;
|
|
87
|
+
inspect;
|
|
88
|
+
search(request) {
|
|
89
|
+
return this.index.search(request);
|
|
90
|
+
}
|
|
91
|
+
searchIds(request) {
|
|
92
|
+
return this.index.searchIds(request);
|
|
93
|
+
}
|
|
94
|
+
asTool(options) {
|
|
95
|
+
return this.index.asTool(options);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
function dedupeTools(tools) {
|
|
99
|
+
const byName = /* @__PURE__ */ new Map();
|
|
100
|
+
for (const tool of tools) {
|
|
101
|
+
byName.set(tool.name, tool);
|
|
102
|
+
}
|
|
103
|
+
return [...byName.values()];
|
|
104
|
+
}
|
|
105
|
+
function defaultToolEmbeddingText(definition) {
|
|
106
|
+
return [definition.name, definition.description, JSON.stringify(definition.parameters)];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/tool/middleware.ts
|
|
110
|
+
function createMiddleware(middleware) {
|
|
111
|
+
return middleware;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// src/tool/think-tool.ts
|
|
115
|
+
import { z } from "zod";
|
|
116
|
+
var defaultThinkToolDescription = "Use this tool to record a thought while reasoning through a complex task. It does not retrieve information, store memory, or change external state.";
|
|
117
|
+
var thinkToolInput = z.object({
|
|
118
|
+
thought: z.string().describe("A thought to record while reasoning through a task.")
|
|
119
|
+
});
|
|
120
|
+
function createThinkTool(options = {}) {
|
|
121
|
+
return createTool({
|
|
122
|
+
name: options.name ?? "think",
|
|
123
|
+
description: options.description ?? defaultThinkToolDescription,
|
|
124
|
+
inputSchema: thinkToolInput,
|
|
125
|
+
outputSchema: z.string(),
|
|
126
|
+
execute: (args) => args.thought
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export {
|
|
131
|
+
assertPositiveSearchLimit,
|
|
132
|
+
assertFiniteSearchThreshold,
|
|
133
|
+
embedTools,
|
|
134
|
+
createToolIndex,
|
|
135
|
+
isToolIndex,
|
|
136
|
+
createMiddleware,
|
|
137
|
+
createThinkTool
|
|
138
|
+
};
|
|
139
|
+
//# sourceMappingURL=chunk-6WGGTJE6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/vector-search-options.ts","../src/tool/dynamic-tools.ts","../src/tool/middleware.ts","../src/tool/think-tool.ts"],"sourcesContent":["export function assertPositiveSearchLimit(value: number, name = \"topK\"): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RangeError(`${name} must be a positive safe integer.`);\n }\n return value;\n}\n\nexport function assertFiniteSearchThreshold(\n value: number | undefined,\n name = \"threshold\",\n): number | undefined {\n if (value !== undefined && !Number.isFinite(value)) {\n throw new RangeError(`${name} must be a finite number.`);\n }\n return value;\n}\n","import type { ToolDefinition } from \"../completion\";\nimport type { EmbeddedDocument, EmbeddingModel, VectorMetadata } from \"../embeddings\";\nimport { embedDocuments } from \"../embeddings\";\nimport {\n assertFiniteSearchThreshold,\n assertPositiveSearchLimit,\n} from \"../internal/vector-search-options\";\nimport type {\n VectorFilter,\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\";\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 type CreateToolIndexOptions<Metadata extends VectorMetadata = VectorMetadata> =\n EmbedToolsOptions<Metadata> & {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n };\n\nexport interface ToolIndex<Metadata extends VectorMetadata = VectorMetadata>\n extends VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata> {\n readonly kind: \"tool-index\";\n readonly tools: readonly AnyTool[];\n readonly topK: number;\n readonly threshold?: number | undefined;\n readonly filter?: VectorFilter | undefined;\n}\n\nexport async function embedTools<Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n tools: readonly AnyTool[],\n options: EmbedToolsOptions<Metadata> = {},\n): Promise<Array<EmbeddedDocument<ToolSearchDocument<Metadata>, Metadata>>> {\n const toolList = dedupeTools(tools);\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: readonly AnyTool[],\n options: CreateToolIndexOptions<Metadata>,\n): Promise<ToolIndex<Metadata>> {\n assertPositiveSearchLimit(options.topK);\n assertFiniteSearchThreshold(options.threshold);\n const toolList = dedupeTools(tools);\n const embedded = await embedTools(model, toolList, options);\n const index = InMemoryVectorStore.fromDocuments(embedded).index(model);\n return new ToolSearchIndex(index, toolList, options);\n}\n\nexport function isToolIndex(value: unknown): value is ToolIndex {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as {\n kind?: unknown;\n tools?: unknown;\n topK?: unknown;\n search?: unknown;\n searchIds?: unknown;\n asTool?: unknown;\n };\n return (\n candidate.kind === \"tool-index\" &&\n Array.isArray(candidate.tools) &&\n typeof candidate.topK === \"number\" &&\n typeof candidate.search === \"function\" &&\n typeof candidate.searchIds === \"function\" &&\n typeof candidate.asTool === \"function\"\n );\n}\n\nclass ToolSearchIndex<Metadata extends VectorMetadata> implements ToolIndex<Metadata> {\n readonly kind = \"tool-index\" as const;\n readonly tools: readonly AnyTool[];\n readonly topK: number;\n readonly threshold: number | undefined;\n readonly filter: VectorFilter | undefined;\n readonly inspect?: (\n request: VectorInspectRequest,\n ) => Promise<VectorInspectPage<ToolSearchDocument<Metadata>, Metadata>>;\n\n constructor(\n private readonly index: VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata>,\n tools: readonly AnyTool[],\n options: CreateToolIndexOptions<Metadata>,\n ) {\n this.tools = Object.freeze([...tools]);\n this.topK = options.topK;\n this.threshold = options.threshold;\n this.filter = options.filter;\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 dedupeTools(tools: readonly AnyTool[]): AnyTool[] {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n byName.set(tool.name, tool);\n }\n return [...byName.values()];\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\";\nimport type { MaybePromise } from \"../internal/type-utils\";\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\nexport function createMiddleware<RawResponse = unknown>(\n middleware: AgentMiddleware<RawResponse>,\n): AgentMiddleware<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 inputSchema: thinkToolInput,\n outputSchema: z.string(),\n execute: (args) => args.thought,\n });\n}\n"],"mappings":";;;;;;;;;AAAO,SAAS,0BAA0B,OAAe,OAAO,QAAgB;AAC9E,MAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI,WAAW,GAAG,IAAI,mCAAmC;AAAA,EACjE;AACA,SAAO;AACT;AAEO,SAAS,4BACd,OACA,OAAO,aACa;AACpB,MAAI,UAAU,UAAa,CAAC,OAAO,SAAS,KAAK,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WAAW,MAAM,WAAW,aAAa,KAAK,UAAU,WAAW,UAAU,CAAC;AACxF;;;AC7FO,SAAS,iBACd,YAC8B;AAC9B,SAAO;AACT;;;ACrFA,SAAS,SAAS;AAGlB,IAAM,8BACJ;AAEF,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,SAAS,EAAE,OAAO,EAAE,SAAS,qDAAqD;AACpF,CAAC;AAOM,SAAS,gBAAgB,UAAkC,CAAC,GAAG;AACpE,SAAO,WAAW;AAAA,IAChB,MAAM,QAAQ,QAAQ;AAAA,IACtB,aAAa,QAAQ,eAAe;AAAA,IACpC,aAAa;AAAA,IACb,cAAc,EAAE,OAAO;AAAA,IACvB,SAAS,CAAC,SAAS,KAAK;AAAA,EAC1B,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// src/retry.ts
|
|
2
|
+
var DEFAULT_MAX_ATTEMPTS = 3;
|
|
3
|
+
var DEFAULT_INITIAL_DELAY_MS = 100;
|
|
4
|
+
var DEFAULT_MAX_DELAY_MS = 1e3;
|
|
5
|
+
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
6
|
+
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 409, 425, 429]);
|
|
7
|
+
var RETRYABLE_NUMERIC_ERROR_CODES = /* @__PURE__ */ new Set([4, 8, 14]);
|
|
8
|
+
var RETRYABLE_ERROR_NAMES = /* @__PURE__ */ new Set([
|
|
9
|
+
"APIConnectionError",
|
|
10
|
+
"APIConnectionTimeoutError",
|
|
11
|
+
"TimeoutError"
|
|
12
|
+
]);
|
|
13
|
+
var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
14
|
+
"DEADLINE_EXCEEDED",
|
|
15
|
+
"EAI_AGAIN",
|
|
16
|
+
"ECONNREFUSED",
|
|
17
|
+
"ECONNRESET",
|
|
18
|
+
"EHOSTUNREACH",
|
|
19
|
+
"ENETDOWN",
|
|
20
|
+
"ENETUNREACH",
|
|
21
|
+
"EPIPE",
|
|
22
|
+
"ETIMEDOUT",
|
|
23
|
+
"RESOURCE_EXHAUSTED",
|
|
24
|
+
"UNAVAILABLE",
|
|
25
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
26
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
27
|
+
"UND_ERR_SOCKET"
|
|
28
|
+
]);
|
|
29
|
+
function resolveRetryOptions(options) {
|
|
30
|
+
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
31
|
+
const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
|
|
32
|
+
const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
|
33
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {
|
|
34
|
+
throw new RangeError("Retry maxAttempts must be a positive integer.");
|
|
35
|
+
}
|
|
36
|
+
assertDelay(initialDelayMs, "initialDelayMs");
|
|
37
|
+
assertDelay(maxDelayMs, "maxDelayMs");
|
|
38
|
+
if (maxDelayMs < initialDelayMs) {
|
|
39
|
+
throw new RangeError("Retry maxDelayMs must be greater than or equal to initialDelayMs.");
|
|
40
|
+
}
|
|
41
|
+
if (options.shouldRetry !== void 0 && typeof options.shouldRetry !== "function") {
|
|
42
|
+
throw new TypeError("Retry shouldRetry must be a function.");
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
maxAttempts,
|
|
46
|
+
initialDelayMs,
|
|
47
|
+
maxDelayMs,
|
|
48
|
+
shouldRetry: options.shouldRetry ?? defaultShouldRetry
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function retryDelayMs(options, failedAttempt) {
|
|
52
|
+
const exponentialDelay = options.initialDelayMs * 2 ** (failedAttempt - 1);
|
|
53
|
+
const cappedDelay = Math.min(options.maxDelayMs, exponentialDelay);
|
|
54
|
+
return Math.random() * cappedDelay;
|
|
55
|
+
}
|
|
56
|
+
function retryErrorAttributes(error) {
|
|
57
|
+
const errors = errorChain(error);
|
|
58
|
+
const errorName = errors.map((candidate) => stringProperty(candidate, "name")).find((value) => value !== void 0);
|
|
59
|
+
const statusCode = firstStatusCode(errors);
|
|
60
|
+
const errorCode = errors.map((candidate) => errorCodeProperty(candidate)).find((value) => value !== void 0);
|
|
61
|
+
return { errorName, statusCode, errorCode };
|
|
62
|
+
}
|
|
63
|
+
async function waitForRetry(delayMs) {
|
|
64
|
+
if (delayMs === 0) return;
|
|
65
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
66
|
+
}
|
|
67
|
+
function retryOptionsForFailure(options, context) {
|
|
68
|
+
if (options === void 0 || context.attempt >= options.maxAttempts) return void 0;
|
|
69
|
+
return options.shouldRetry({ ...context, maxAttempts: options.maxAttempts }) ? options : void 0;
|
|
70
|
+
}
|
|
71
|
+
async function runWithRetries(operation, options, context) {
|
|
72
|
+
let attempt = 1;
|
|
73
|
+
while (true) {
|
|
74
|
+
try {
|
|
75
|
+
return await operation();
|
|
76
|
+
} catch (error) {
|
|
77
|
+
const retryOptions = retryOptionsForFailure(options, { error, attempt, ...context });
|
|
78
|
+
if (retryOptions === void 0) throw error;
|
|
79
|
+
await waitForRetry(retryDelayMs(retryOptions, attempt));
|
|
80
|
+
attempt += 1;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function defaultShouldRetry(context) {
|
|
85
|
+
const errors = errorChain(context.error);
|
|
86
|
+
if (errors.some((error) => stringProperty(error, "name") === "AbortError")) return false;
|
|
87
|
+
const statusCode = firstStatusCode(errors);
|
|
88
|
+
if (statusCode !== void 0) {
|
|
89
|
+
return RETRYABLE_STATUS_CODES.has(statusCode) || statusCode >= 500 && statusCode <= 599;
|
|
90
|
+
}
|
|
91
|
+
return errors.some((error) => {
|
|
92
|
+
const name = stringProperty(error, "name");
|
|
93
|
+
if (name !== void 0 && RETRYABLE_ERROR_NAMES.has(name)) return true;
|
|
94
|
+
const code = stringProperty(error, "code")?.toUpperCase();
|
|
95
|
+
if (code !== void 0 && RETRYABLE_ERROR_CODES.has(code)) return true;
|
|
96
|
+
const numericCode = numberProperty(error, "code");
|
|
97
|
+
return numericCode !== void 0 && RETRYABLE_NUMERIC_ERROR_CODES.has(numericCode);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function firstStatusCode(errors) {
|
|
101
|
+
for (const error of errors) {
|
|
102
|
+
const status = numberProperty(error, "status");
|
|
103
|
+
if (status !== void 0 && status >= 100 && status <= 599) return status;
|
|
104
|
+
const statusCode = numberProperty(error, "statusCode");
|
|
105
|
+
if (statusCode !== void 0 && statusCode >= 100 && statusCode <= 599) return statusCode;
|
|
106
|
+
const code = numberProperty(error, "code");
|
|
107
|
+
if (code !== void 0 && code >= 100 && code <= 599) return code;
|
|
108
|
+
}
|
|
109
|
+
return void 0;
|
|
110
|
+
}
|
|
111
|
+
function errorChain(error) {
|
|
112
|
+
const errors = [];
|
|
113
|
+
const seen = /* @__PURE__ */ new Set();
|
|
114
|
+
let current = error;
|
|
115
|
+
while (isObject(current) && !seen.has(current)) {
|
|
116
|
+
seen.add(current);
|
|
117
|
+
errors.push(current);
|
|
118
|
+
current = property(current, "cause");
|
|
119
|
+
}
|
|
120
|
+
return errors;
|
|
121
|
+
}
|
|
122
|
+
function assertDelay(value, name) {
|
|
123
|
+
if (!Number.isFinite(value) || value < 0 || value > MAX_TIMER_DELAY_MS) {
|
|
124
|
+
throw new RangeError(`Retry ${name} must be between 0 and ${MAX_TIMER_DELAY_MS} milliseconds.`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function numberProperty(value, name) {
|
|
128
|
+
const candidate = property(value, name);
|
|
129
|
+
return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : void 0;
|
|
130
|
+
}
|
|
131
|
+
function stringProperty(value, name) {
|
|
132
|
+
const candidate = property(value, name);
|
|
133
|
+
return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
|
|
134
|
+
}
|
|
135
|
+
function errorCodeProperty(value) {
|
|
136
|
+
return stringProperty(value, "code") ?? numberProperty(value, "code");
|
|
137
|
+
}
|
|
138
|
+
function property(value, name) {
|
|
139
|
+
try {
|
|
140
|
+
return value[name];
|
|
141
|
+
} catch {
|
|
142
|
+
return void 0;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function isObject(value) {
|
|
146
|
+
return typeof value === "object" && value !== null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export {
|
|
150
|
+
resolveRetryOptions,
|
|
151
|
+
retryDelayMs,
|
|
152
|
+
retryErrorAttributes,
|
|
153
|
+
waitForRetry,
|
|
154
|
+
retryOptionsForFailure,
|
|
155
|
+
runWithRetries
|
|
156
|
+
};
|
|
157
|
+
//# sourceMappingURL=chunk-A3UBYTJT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/retry.ts"],"sourcesContent":["import type { JsonValue } from \"./completion/types\";\n\nexport type RetryContext = {\n error: unknown;\n attempt: number;\n maxAttempts: number;\n streaming: boolean;\n turn?: number | undefined;\n};\n\nexport type RetryOptions = {\n maxAttempts?: number | undefined;\n initialDelayMs?: number | undefined;\n maxDelayMs?: number | undefined;\n shouldRetry?: ((context: RetryContext) => boolean) | undefined;\n};\n\nexport type ResolvedRetryOptions = {\n maxAttempts: number;\n initialDelayMs: number;\n maxDelayMs: number;\n shouldRetry: (context: RetryContext) => boolean;\n};\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 100;\nconst DEFAULT_MAX_DELAY_MS = 1_000;\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\nconst RETRYABLE_STATUS_CODES = new Set([408, 409, 425, 429]);\nconst RETRYABLE_NUMERIC_ERROR_CODES = new Set([4, 8, 14]);\nconst RETRYABLE_ERROR_NAMES = new Set([\n \"APIConnectionError\",\n \"APIConnectionTimeoutError\",\n \"TimeoutError\",\n]);\nconst RETRYABLE_ERROR_CODES = new Set([\n \"DEADLINE_EXCEEDED\",\n \"EAI_AGAIN\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"ENETUNREACH\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"RESOURCE_EXHAUSTED\",\n \"UNAVAILABLE\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n]);\n\nexport function resolveRetryOptions(options: RetryOptions): ResolvedRetryOptions {\n const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n\n if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {\n throw new RangeError(\"Retry maxAttempts must be a positive integer.\");\n }\n assertDelay(initialDelayMs, \"initialDelayMs\");\n assertDelay(maxDelayMs, \"maxDelayMs\");\n if (maxDelayMs < initialDelayMs) {\n throw new RangeError(\"Retry maxDelayMs must be greater than or equal to initialDelayMs.\");\n }\n if (options.shouldRetry !== undefined && typeof options.shouldRetry !== \"function\") {\n throw new TypeError(\"Retry shouldRetry must be a function.\");\n }\n\n return {\n maxAttempts,\n initialDelayMs,\n maxDelayMs,\n shouldRetry: options.shouldRetry ?? defaultShouldRetry,\n };\n}\n\nexport function retryDelayMs(options: ResolvedRetryOptions, failedAttempt: number): number {\n const exponentialDelay = options.initialDelayMs * 2 ** (failedAttempt - 1);\n const cappedDelay = Math.min(options.maxDelayMs, exponentialDelay);\n return Math.random() * cappedDelay;\n}\n\nexport function retryErrorAttributes(error: unknown): Record<string, JsonValue | undefined> {\n const errors = errorChain(error);\n const errorName = errors\n .map((candidate) => stringProperty(candidate, \"name\"))\n .find((value) => value !== undefined);\n const statusCode = firstStatusCode(errors);\n const errorCode = errors\n .map((candidate) => errorCodeProperty(candidate))\n .find((value) => value !== undefined);\n\n return { errorName, statusCode, errorCode };\n}\n\nexport async function waitForRetry(delayMs: number): Promise<void> {\n if (delayMs === 0) return;\n await new Promise<void>((resolve) => setTimeout(resolve, delayMs));\n}\n\nexport function retryOptionsForFailure(\n options: ResolvedRetryOptions | undefined,\n context: Omit<RetryContext, \"maxAttempts\">,\n): ResolvedRetryOptions | undefined {\n if (options === undefined || context.attempt >= options.maxAttempts) return undefined;\n return options.shouldRetry({ ...context, maxAttempts: options.maxAttempts })\n ? options\n : undefined;\n}\n\nexport async function runWithRetries<T>(\n operation: () => Promise<T>,\n options: ResolvedRetryOptions | undefined,\n context: { streaming: boolean; turn?: number | undefined },\n): Promise<T> {\n let attempt = 1;\n while (true) {\n try {\n return await operation();\n } catch (error) {\n const retryOptions = retryOptionsForFailure(options, { error, attempt, ...context });\n if (retryOptions === undefined) throw error;\n await waitForRetry(retryDelayMs(retryOptions, attempt));\n attempt += 1;\n }\n }\n}\n\nfunction defaultShouldRetry(context: RetryContext): boolean {\n const errors = errorChain(context.error);\n if (errors.some((error) => stringProperty(error, \"name\") === \"AbortError\")) return false;\n\n const statusCode = firstStatusCode(errors);\n if (statusCode !== undefined) {\n return RETRYABLE_STATUS_CODES.has(statusCode) || (statusCode >= 500 && statusCode <= 599);\n }\n\n return errors.some((error) => {\n const name = stringProperty(error, \"name\");\n if (name !== undefined && RETRYABLE_ERROR_NAMES.has(name)) return true;\n const code = stringProperty(error, \"code\")?.toUpperCase();\n if (code !== undefined && RETRYABLE_ERROR_CODES.has(code)) return true;\n const numericCode = numberProperty(error, \"code\");\n return numericCode !== undefined && RETRYABLE_NUMERIC_ERROR_CODES.has(numericCode);\n });\n}\n\nfunction firstStatusCode(errors: Record<string, unknown>[]): number | undefined {\n for (const error of errors) {\n const status = numberProperty(error, \"status\");\n if (status !== undefined && status >= 100 && status <= 599) return status;\n const statusCode = numberProperty(error, \"statusCode\");\n if (statusCode !== undefined && statusCode >= 100 && statusCode <= 599) return statusCode;\n const code = numberProperty(error, \"code\");\n if (code !== undefined && code >= 100 && code <= 599) return code;\n }\n return undefined;\n}\n\nfunction errorChain(error: unknown): Record<string, unknown>[] {\n const errors: Record<string, unknown>[] = [];\n const seen = new Set<object>();\n let current = error;\n while (isObject(current) && !seen.has(current)) {\n seen.add(current);\n errors.push(current);\n current = property(current, \"cause\");\n }\n return errors;\n}\n\nfunction assertDelay(value: number, name: string): void {\n if (!Number.isFinite(value) || value < 0 || value > MAX_TIMER_DELAY_MS) {\n throw new RangeError(`Retry ${name} must be between 0 and ${MAX_TIMER_DELAY_MS} milliseconds.`);\n }\n}\n\nfunction numberProperty(value: Record<string, unknown>, name: string): number | undefined {\n const candidate = property(value, name);\n return typeof candidate === \"number\" && Number.isFinite(candidate) ? candidate : undefined;\n}\n\nfunction stringProperty(value: Record<string, unknown>, name: string): string | undefined {\n const candidate = property(value, name);\n return typeof candidate === \"string\" && candidate.length > 0 ? candidate : undefined;\n}\n\nfunction errorCodeProperty(value: Record<string, unknown>): string | number | undefined {\n return stringProperty(value, \"code\") ?? numberProperty(value, \"code\");\n}\n\nfunction property(value: Record<string, unknown>, name: string): unknown {\n try {\n return value[name];\n } catch {\n return undefined;\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"],"mappings":";AAwBA,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AACjC,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB;AAE3B,IAAM,yBAAyB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAC3D,IAAM,gCAAgC,oBAAI,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AACxD,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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ChD;","names":[]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-YK4WAAS4.js";
|
|
7
7
|
import {
|
|
8
8
|
createTool
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-R2LJSQUW.js";
|
|
10
10
|
|
|
11
11
|
// src/skills/instructions.ts
|
|
12
12
|
function skillInstructions(skills) {
|
|
@@ -52,10 +52,10 @@ function createSkillTools(skills) {
|
|
|
52
52
|
createTool({
|
|
53
53
|
name: "get_skill_instructions",
|
|
54
54
|
description: "Load the full SKILL.md instructions for an Agent Skill.",
|
|
55
|
-
|
|
55
|
+
inputSchema: z.object({
|
|
56
56
|
skillName: z.string().describe("The name of the skill to load.")
|
|
57
57
|
}),
|
|
58
|
-
|
|
58
|
+
outputSchema: z.string(),
|
|
59
59
|
execute: ({ skillName }) => registry.get(skillName).instructions
|
|
60
60
|
})
|
|
61
61
|
),
|
|
@@ -63,11 +63,11 @@ function createSkillTools(skills) {
|
|
|
63
63
|
createTool({
|
|
64
64
|
name: "get_skill_reference",
|
|
65
65
|
description: "Read a reference file from an Agent Skill.",
|
|
66
|
-
|
|
66
|
+
inputSchema: z.object({
|
|
67
67
|
skillName: z.string().describe("The name of the skill."),
|
|
68
68
|
referencePath: z.string().describe("A path listed in the skill references.")
|
|
69
69
|
}),
|
|
70
|
-
|
|
70
|
+
outputSchema: z.string(),
|
|
71
71
|
execute: ({ skillName, referencePath }) => registry.readReference(skillName, referencePath)
|
|
72
72
|
})
|
|
73
73
|
),
|
|
@@ -75,11 +75,11 @@ function createSkillTools(skills) {
|
|
|
75
75
|
createTool({
|
|
76
76
|
name: "get_skill_script",
|
|
77
77
|
description: "Read a script file from an Agent Skill.",
|
|
78
|
-
|
|
78
|
+
inputSchema: z.object({
|
|
79
79
|
skillName: z.string().describe("The name of the skill."),
|
|
80
80
|
scriptPath: z.string().describe("A path listed in the skill scripts.")
|
|
81
81
|
}),
|
|
82
|
-
|
|
82
|
+
outputSchema: z.string(),
|
|
83
83
|
execute: ({ skillName, scriptPath }) => registry.readScript(skillName, scriptPath)
|
|
84
84
|
})
|
|
85
85
|
),
|
|
@@ -87,13 +87,13 @@ function createSkillTools(skills) {
|
|
|
87
87
|
createTool({
|
|
88
88
|
name: "run_skill_script",
|
|
89
89
|
description: "Execute a script from an Agent Skill with optional arguments.",
|
|
90
|
-
|
|
90
|
+
inputSchema: z.object({
|
|
91
91
|
skillName: z.string().describe("The name of the skill."),
|
|
92
92
|
scriptPath: z.string().describe("A path listed in the skill scripts."),
|
|
93
93
|
args: z.array(z.string()).optional().describe("Arguments passed to the script."),
|
|
94
94
|
timeoutMs: z.number().int().positive().optional().describe("Execution timeout in ms.")
|
|
95
95
|
}),
|
|
96
|
-
|
|
96
|
+
outputSchema: z.string(),
|
|
97
97
|
execute: ({ skillName, scriptPath, args = [], timeoutMs = DEFAULT_TIMEOUT_MS }) => registry.runScript(skillName, scriptPath, args, timeoutMs)
|
|
98
98
|
})
|
|
99
99
|
)
|
|
@@ -395,4 +395,4 @@ export {
|
|
|
395
395
|
SkillValidationError,
|
|
396
396
|
skill
|
|
397
397
|
};
|
|
398
|
-
//# sourceMappingURL=chunk-
|
|
398
|
+
//# sourceMappingURL=chunk-DMPUP4R3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/skills/instructions.ts","../src/skills/tools.ts","../src/skills/load.ts","../src/skills/local.ts","../src/skills/types.ts"],"sourcesContent":["import type { Skill } from \"./types\";\n\nexport function skillInstructions(skills: Skill[]): string {\n if (skills.length === 0) {\n return \"\";\n }\n\n return [\n \"You have access to Agent Skills.\",\n \"Skills are compact capability packages. Use the skill tools to load full instructions, references, or scripts only when a skill is relevant.\",\n \"\",\n \"Available skills:\",\n ...skills.map(formatSkill),\n \"\",\n \"Skill tools:\",\n \"- get_skill_instructions: load full SKILL.md guidance for a skill.\",\n \"- get_skill_reference: read a reference file from a skill.\",\n \"- get_skill_script: read a script file from a skill.\",\n \"- run_skill_script: execute a script from a skill with arguments.\",\n ].join(\"\\n\");\n}\n\nfunction formatSkill(skill: Skill): string {\n const lines = [`- ${skill.name}: ${skill.description}`];\n if (skill.references.length > 0) {\n lines.push(` references: ${skill.references.join(\", \")}`);\n }\n if (skill.scripts.length > 0) {\n lines.push(` scripts: ${skill.scripts.join(\", \")}`);\n }\n return lines.join(\"\\n\");\n}\n","import { spawn } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { type AnyTool, createTool } from \"../tool\";\nimport { markSkillTool } from \"../tool/skill-tool-marker\";\nimport type { Skill } from \"./types\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_OUTPUT_CHARS = 20_000;\n\nexport function createSkillTools(skills: Skill[]): AnyTool[] {\n const registry = new SkillRegistry(skills);\n\n return [\n markSkillTool(\n createTool({\n name: \"get_skill_instructions\",\n description: \"Load the full SKILL.md instructions for an Agent Skill.\",\n inputSchema: z.object({\n skillName: z.string().describe(\"The name of the skill to load.\"),\n }),\n outputSchema: z.string(),\n execute: ({ skillName }) => registry.get(skillName).instructions,\n }),\n ),\n markSkillTool(\n createTool({\n name: \"get_skill_reference\",\n description: \"Read a reference file from an Agent Skill.\",\n inputSchema: z.object({\n skillName: z.string().describe(\"The name of the skill.\"),\n referencePath: z.string().describe(\"A path listed in the skill references.\"),\n }),\n outputSchema: z.string(),\n execute: ({ skillName, referencePath }) => registry.readReference(skillName, referencePath),\n }),\n ),\n markSkillTool(\n createTool({\n name: \"get_skill_script\",\n description: \"Read a script file from an Agent Skill.\",\n inputSchema: z.object({\n skillName: z.string().describe(\"The name of the skill.\"),\n scriptPath: z.string().describe(\"A path listed in the skill scripts.\"),\n }),\n outputSchema: z.string(),\n execute: ({ skillName, scriptPath }) => registry.readScript(skillName, scriptPath),\n }),\n ),\n markSkillTool(\n createTool({\n name: \"run_skill_script\",\n description: \"Execute a script from an Agent Skill with optional arguments.\",\n inputSchema: z.object({\n skillName: z.string().describe(\"The name of the skill.\"),\n scriptPath: z.string().describe(\"A path listed in the skill scripts.\"),\n args: z.array(z.string()).optional().describe(\"Arguments passed to the script.\"),\n timeoutMs: z.number().int().positive().optional().describe(\"Execution timeout in ms.\"),\n }),\n outputSchema: z.string(),\n execute: ({ skillName, scriptPath, args = [], timeoutMs = DEFAULT_TIMEOUT_MS }) =>\n registry.runScript(skillName, scriptPath, args, timeoutMs),\n }),\n ),\n ];\n}\n\nclass SkillRegistry {\n private readonly skills = new Map<string, Skill>();\n\n constructor(skills: Skill[]) {\n for (const skill of skills) {\n this.skills.set(skill.name, skill);\n }\n }\n\n get(skillName: string): Skill {\n const skill = this.skills.get(skillName);\n if (skill === undefined) {\n throw new Error(`Skill not found: ${skillName}`);\n }\n return skill;\n }\n\n async readReference(skillName: string, referencePath: string): Promise<string> {\n const skill = this.get(skillName);\n const path = this.resolveContainedPath(skill, \"references\", referencePath);\n if (!skill.references.includes(referencePath)) {\n throw new Error(`Skill reference not found: ${skillName}/${referencePath}`);\n }\n return readFile(path, \"utf8\");\n }\n\n async readScript(skillName: string, scriptPath: string): Promise<string> {\n const skill = this.get(skillName);\n const path = this.resolveContainedPath(skill, \"scripts\", scriptPath);\n if (!skill.scripts.includes(scriptPath)) {\n throw new Error(`Skill script not found: ${skillName}/${scriptPath}`);\n }\n return readFile(path, \"utf8\");\n }\n\n async runScript(\n skillName: string,\n scriptPath: string,\n args: string[],\n timeoutMs: number,\n ): Promise<string> {\n const skill = this.get(skillName);\n const script = this.resolveContainedPath(skill, \"scripts\", scriptPath);\n if (!skill.scripts.includes(scriptPath)) {\n throw new Error(`Skill script not found: ${skillName}/${scriptPath}`);\n }\n return runExecutable(script, args, skill.directory, timeoutMs);\n }\n\n private resolveContainedPath(\n skill: Skill,\n section: \"references\" | \"scripts\",\n requestedPath: string,\n ): string {\n if (requestedPath.length === 0 || isAbsolute(requestedPath)) {\n throw new Error(`Invalid skill path: ${requestedPath}`);\n }\n\n const root = resolve(skill.directory, section);\n const resolved = resolve(root, requestedPath);\n const rel = relative(root, resolved);\n if (rel === \"..\" || rel.startsWith(`..${\"/\"}`) || rel.startsWith(`..${\"\\\\\"}`)) {\n throw new Error(`Invalid skill path: ${requestedPath}`);\n }\n\n return resolved;\n }\n}\n\nfunction runExecutable(\n command: string,\n args: string[],\n cwd: string,\n timeoutMs: number,\n): Promise<string> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timeout = setTimeout(() => {\n timedOut = true;\n child.kill();\n }, timeoutMs);\n\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout = appendLimited(stdout, chunk);\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr = appendLimited(stderr, chunk);\n });\n child.on(\"error\", (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n child.on(\"close\", (code, signal) => {\n clearTimeout(timeout);\n if (timedOut) {\n reject(new Error(`Skill script timed out after ${timeoutMs}ms`));\n return;\n }\n\n const output = formatProcessOutput(stdout, stderr);\n if (code !== 0) {\n reject(new Error(`Skill script exited with code ${code ?? \"unknown\"}: ${output}`));\n return;\n }\n if (signal !== null) {\n reject(new Error(`Skill script exited with signal ${signal}: ${output}`));\n return;\n }\n\n resolvePromise(output);\n });\n });\n}\n\nfunction formatProcessOutput(stdout: string, stderr: string): string {\n const parts: string[] = [];\n if (stdout.length > 0) {\n parts.push(`stdout:\\n${stdout}`);\n }\n if (stderr.length > 0) {\n parts.push(`stderr:\\n${stderr}`);\n }\n return parts.length === 0 ? \"\" : parts.join(\"\\n\\n\");\n}\n\nfunction appendLimited(current: string, chunk: string): string {\n const next = current + chunk;\n if (next.length <= MAX_OUTPUT_CHARS) {\n return next;\n }\n return `${next.slice(0, MAX_OUTPUT_CHARS)}\\n[truncated]`;\n}\n","import { skillInstructions } from \"./instructions\";\nimport { createSkillTools } from \"./tools\";\nimport type { Skill, SkillLoader, SkillSet } from \"./types\";\n\nexport async function loadSkills(loaders: SkillLoader | SkillLoader[]): Promise<SkillSet> {\n const ordered = Array.isArray(loaders) ? loaders : [loaders];\n const byName = new Map<string, Skill>();\n\n for (const loader of ordered) {\n for (const loaded of await loader.load()) {\n byName.delete(loaded.name);\n byName.set(loaded.name, loaded);\n }\n }\n\n const skills = [...byName.values()];\n return {\n skills,\n instructions: skillInstructions(skills),\n tools: skills.length === 0 ? [] : createSkillTools(skills),\n };\n}\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { basename, join, relative, resolve, sep } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { isRecord } from \"../internal/record\";\nimport type { Skill, SkillLoader, SkillValidationIssue } from \"./types\";\nimport { SkillValidationError } from \"./types\";\n\ntype SkillFrontmatter = {\n name?: unknown;\n description?: unknown;\n license?: unknown;\n metadata?: unknown;\n};\n\nconst NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst MAX_NAME_LENGTH = 64;\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\nexport const skill = {\n local(path: string): SkillLoader {\n return {\n load: () => loadLocalSkills(path),\n };\n },\n};\n\nasync function loadLocalSkills(path: string): Promise<Skill[]> {\n const root = resolve(path);\n if (await hasSkillFile(root)) {\n return [await readSkill(root)];\n }\n\n const entries = await readdir(root, { withFileTypes: true });\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) {\n continue;\n }\n const directory = join(root, entry.name);\n if (await hasSkillFile(directory)) {\n skills.push(await readSkill(directory));\n }\n }\n return skills;\n}\n\nasync function hasSkillFile(directory: string): Promise<boolean> {\n try {\n const info = await stat(join(directory, \"SKILL.md\"));\n return info.isFile();\n } catch {\n return false;\n }\n}\n\nasync function readSkill(directory: string): Promise<Skill> {\n const skillPath = join(directory, \"SKILL.md\");\n const markdown = await readFile(skillPath, \"utf8\");\n const parsed = parseSkillMarkdown(markdown, skillPath);\n validateSkillFrontmatter(parsed.frontmatter, directory, skillPath);\n\n const name = parsed.frontmatter.name as string;\n const description = parsed.frontmatter.description as string;\n const license =\n typeof parsed.frontmatter.license === \"string\" ? parsed.frontmatter.license : undefined;\n const metadata = isRecord(parsed.frontmatter.metadata) ? parsed.frontmatter.metadata : undefined;\n\n return {\n name,\n description,\n instructions: parsed.body.trim(),\n directory,\n references: await listRelativeFiles(join(directory, \"references\")),\n scripts: await listRelativeFiles(join(directory, \"scripts\")),\n license,\n metadata,\n };\n}\n\nfunction parseSkillMarkdown(\n markdown: string,\n path: string,\n): { frontmatter: SkillFrontmatter; body: string } {\n if (!markdown.startsWith(\"---\\n\") && !markdown.startsWith(\"---\\r\\n\")) {\n throw new SkillValidationError(\"Skill validation failed\", [\n { path, message: \"SKILL.md must start with YAML frontmatter\" },\n ]);\n }\n\n const newline = markdown.startsWith(\"---\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const marker = `${newline}---${newline}`;\n const end = markdown.indexOf(marker, 3);\n if (end === -1) {\n throw new SkillValidationError(\"Skill validation failed\", [\n { path, message: \"SKILL.md frontmatter must end with ---\" },\n ]);\n }\n\n const rawFrontmatter = markdown.slice(3 + newline.length, end);\n const body = markdown.slice(end + marker.length);\n const parsed = parseYaml(rawFrontmatter);\n if (!isRecord(parsed)) {\n throw new SkillValidationError(\"Skill validation failed\", [\n { path, message: \"SKILL.md frontmatter must be a YAML object\" },\n ]);\n }\n\n return { frontmatter: parsed, body };\n}\n\nfunction validateSkillFrontmatter(\n frontmatter: SkillFrontmatter,\n directory: string,\n path: string,\n): void {\n const issues: SkillValidationIssue[] = [];\n const name = frontmatter.name;\n const description = frontmatter.description;\n\n if (typeof name !== \"string\" || name.length === 0) {\n issues.push({ path, message: \"name is required\" });\n } else {\n if (name.length > MAX_NAME_LENGTH) {\n issues.push({ path, message: `name must be at most ${MAX_NAME_LENGTH} characters` });\n }\n if (!NAME_PATTERN.test(name)) {\n issues.push({\n path,\n message: \"name must contain lowercase letters, numbers, and hyphens only\",\n });\n }\n if (basename(directory) !== name) {\n issues.push({ path, message: \"name must match the skill directory name\" });\n }\n }\n\n if (typeof description !== \"string\" || description.length === 0) {\n issues.push({ path, message: \"description is required\" });\n } else if (description.length > MAX_DESCRIPTION_LENGTH) {\n issues.push({\n path,\n message: `description must be at most ${MAX_DESCRIPTION_LENGTH} characters`,\n });\n }\n\n if (issues.length > 0) {\n throw new SkillValidationError(\"Skill validation failed\", issues);\n }\n}\n\nasync function listRelativeFiles(directory: string): Promise<string[]> {\n try {\n const info = await stat(directory);\n if (!info.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const files: string[] = [];\n await collectFiles(directory, directory, files);\n return files.sort();\n}\n\nasync function collectFiles(root: string, directory: string, files: string[]): Promise<void> {\n const entries = await readdir(directory, { withFileTypes: true });\n for (const entry of entries) {\n const path = join(directory, entry.name);\n if (entry.isDirectory()) {\n await collectFiles(root, path, files);\n } else if (entry.isFile()) {\n files.push(toPortablePath(relative(root, path)));\n }\n }\n}\n\nfunction toPortablePath(path: string): string {\n return sep === \"/\" ? path : path.split(sep).join(\"/\");\n}\n","import type { AnyTool } from \"../tool\";\n\nexport type Skill = {\n readonly name: string;\n readonly description: string;\n readonly instructions: string;\n readonly directory: string;\n readonly references: string[];\n readonly scripts: string[];\n readonly license?: string | undefined;\n readonly metadata?: Record<string, unknown> | undefined;\n};\n\nexport type SkillLoader = {\n load(): Promise<Skill[]>;\n};\n\nexport type SkillSet = {\n readonly skills: Skill[];\n readonly tools: AnyTool[];\n readonly instructions: string;\n};\n\nexport type SkillValidationIssue = {\n path: string;\n message: string;\n};\n\nexport class SkillValidationError extends Error {\n readonly issues: SkillValidationIssue[];\n\n constructor(message: string, issues: SkillValidationIssue[]) {\n super(message);\n this.name = \"SkillValidationError\";\n this.issues = issues;\n }\n}\n"],"mappings":";;;;;;;;;;;AAEO,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AQ,WAAW,EAAE,eAAe,KAAK,CAAC;AAChE,aAAW,SAAS,SAAS;AAC3B,UAAM,OAAO,KAAK,WAAW,MAAM,IAAI;AACvC,QAAI,MAAM,YAAY,GAAG;AACvB,YAAM,aAAa,MAAM,MAAM,KAAK;AAAA,IACtC,WAAW,MAAM,OAAO,GAAG;AACzB,YAAM,KAAK,eAAeC,UAAS,MAAM,IAAI,CAAC,CAAC;AAAA,IACjD;AAAA,EACF;AACF;AAEA,SAAS,eAAe,MAAsB;AAC5C,SAAO,QAAQ,MAAM,OAAO,KAAK,MAAM,GAAG,EAAE,KAAK,GAAG;AACtD;","names":["skill","skill","readFile","relative","resolve","resolve","readFile","relative"]}
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
mapWithConcurrency
|
|
3
|
-
} from "./chunk-OIMLU4SF.js";
|
|
4
|
-
|
|
5
1
|
// src/embeddings/distance.ts
|
|
6
2
|
function dotProduct(left, right) {
|
|
7
3
|
assertSameDimensions(left, right);
|
|
@@ -46,6 +42,33 @@ function assertSameDimensions(left, right) {
|
|
|
46
42
|
}
|
|
47
43
|
}
|
|
48
44
|
|
|
45
|
+
// src/internal/concurrency.ts
|
|
46
|
+
async function mapWithConcurrency(inputs, concurrency, mapper) {
|
|
47
|
+
if (!Number.isSafeInteger(concurrency) || concurrency <= 0) {
|
|
48
|
+
throw new RangeError("concurrency must be a positive safe integer.");
|
|
49
|
+
}
|
|
50
|
+
const limit = concurrency;
|
|
51
|
+
const results = new Array(inputs.length);
|
|
52
|
+
let nextIndex = 0;
|
|
53
|
+
let firstFailure;
|
|
54
|
+
async function worker() {
|
|
55
|
+
while (firstFailure === void 0 && nextIndex < inputs.length) {
|
|
56
|
+
const index = nextIndex;
|
|
57
|
+
nextIndex += 1;
|
|
58
|
+
try {
|
|
59
|
+
results[index] = await mapper(inputs[index]);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
firstFailure ??= { error };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
await Promise.all(Array.from({ length: Math.min(limit, inputs.length) }, () => worker()));
|
|
66
|
+
if (firstFailure !== void 0) {
|
|
67
|
+
throw firstFailure.error;
|
|
68
|
+
}
|
|
69
|
+
return results;
|
|
70
|
+
}
|
|
71
|
+
|
|
49
72
|
// src/embeddings/embed.ts
|
|
50
73
|
async function embedText(model, text) {
|
|
51
74
|
const embeddings = await embedTexts(model, [text]);
|
|
@@ -233,6 +256,7 @@ export {
|
|
|
233
256
|
euclideanDistance,
|
|
234
257
|
manhattanDistance,
|
|
235
258
|
chebyshevDistance,
|
|
259
|
+
mapWithConcurrency,
|
|
236
260
|
embedText,
|
|
237
261
|
embedTexts,
|
|
238
262
|
embedSparseTexts,
|
|
@@ -240,4 +264,4 @@ export {
|
|
|
240
264
|
embedDocuments,
|
|
241
265
|
embedHybridDocuments
|
|
242
266
|
};
|
|
243
|
-
//# sourceMappingURL=chunk-
|
|
267
|
+
//# sourceMappingURL=chunk-DZ3CKYTH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/embeddings/distance.ts","../src/internal/concurrency.ts","../src/embeddings/embed.ts"],"sourcesContent":["export function dotProduct(left: number[], right: number[]): number {\n assertSameDimensions(left, right);\n return left.reduce((sum, value, index) => sum + value * (right[index] as number), 0);\n}\n\nexport function cosineSimilarity(left: number[], right: number[]): number {\n assertSameDimensions(left, right);\n const leftMagnitude = magnitude(left);\n const rightMagnitude = magnitude(right);\n if (leftMagnitude === 0 || rightMagnitude === 0) {\n return 0;\n }\n return dotProduct(left, right) / (leftMagnitude * rightMagnitude);\n}\n\nexport function angularDistance(left: number[], right: number[]): number {\n const similarity = Math.max(-1, Math.min(1, cosineSimilarity(left, right)));\n return Math.acos(similarity) / Math.PI;\n}\n\nexport function euclideanDistance(left: number[], right: number[]): number {\n assertSameDimensions(left, right);\n return Math.sqrt(\n left.reduce((sum, value, index) => sum + (value - (right[index] as number)) ** 2, 0),\n );\n}\n\nexport function manhattanDistance(left: number[], right: number[]): number {\n assertSameDimensions(left, right);\n return left.reduce((sum, value, index) => sum + Math.abs(value - (right[index] as number)), 0);\n}\n\nexport function chebyshevDistance(left: number[], right: number[]): number {\n assertSameDimensions(left, right);\n return left.reduce(\n (max, value, index) => Math.max(max, Math.abs(value - (right[index] as number))),\n 0,\n );\n}\n\nfunction magnitude(vector: number[]): number {\n return Math.sqrt(vector.reduce((sum, value) => sum + value ** 2, 0));\n}\n\nfunction assertSameDimensions(left: number[], right: number[]): void {\n if (left.length !== right.length) {\n throw new Error(`Vector dimension mismatch: ${left.length} !== ${right.length}`);\n }\n}\n","export async function mapWithConcurrency<Input, Output>(\n inputs: Input[],\n concurrency: number,\n mapper: (input: Input) => Promise<Output>,\n): Promise<Output[]> {\n if (!Number.isSafeInteger(concurrency) || concurrency <= 0) {\n throw new RangeError(\"concurrency must be a positive safe integer.\");\n }\n const limit = concurrency;\n const results = new Array<Output>(inputs.length);\n let nextIndex = 0;\n let firstFailure: { error: unknown } | undefined;\n\n async function worker(): Promise<void> {\n while (firstFailure === undefined && nextIndex < inputs.length) {\n const index = nextIndex;\n nextIndex += 1;\n try {\n results[index] = await mapper(inputs[index] as Input);\n } catch (error) {\n firstFailure ??= { error };\n }\n }\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, inputs.length) }, () => worker()));\n if (firstFailure !== undefined) {\n throw firstFailure.error;\n }\n return results;\n}\n","import { mapWithConcurrency } from \"../internal/concurrency\";\nimport type {\n EmbedDocumentsOptions,\n EmbeddedDocument,\n Embedding,\n EmbeddingModel,\n EmbedHybridDocumentsOptions,\n SparseEmbedding,\n SparseEmbeddingModel,\n VectorMetadata,\n} from \"./types\";\n\nexport async function embedText(model: EmbeddingModel, text: string): Promise<Embedding> {\n const embeddings = await embedTexts(model, [text]);\n const embedding = embeddings[0];\n if (embedding === undefined) {\n throw new Error(\"Embedding model returned no embeddings\");\n }\n return embedding;\n}\n\nexport async function embedTexts(model: EmbeddingModel, texts: string[]): Promise<Embedding[]> {\n if (texts.length === 0) {\n return [];\n }\n\n const maxBatchSize = Math.max(1, Math.trunc(model.maxBatchSize ?? texts.length));\n const batches: string[][] = [];\n for (let index = 0; index < texts.length; index += maxBatchSize) {\n batches.push(texts.slice(index, index + maxBatchSize));\n }\n\n const results = await mapWithConcurrency(batches, 1, (batch) => model.embedTexts(batch));\n const embeddings = results.flat();\n if (embeddings.length !== texts.length) {\n throw new Error(\n `Embedding model returned ${embeddings.length} embeddings for ${texts.length} texts`,\n );\n }\n return embeddings;\n}\n\nexport async function embedSparseTexts(\n model: SparseEmbeddingModel,\n texts: string[],\n): Promise<SparseEmbedding[]> {\n if (texts.length === 0) {\n return [];\n }\n\n const maxBatchSize = Math.max(1, Math.trunc(model.maxBatchSize ?? texts.length));\n const batches: string[][] = [];\n for (let index = 0; index < texts.length; index += maxBatchSize) {\n batches.push(texts.slice(index, index + maxBatchSize));\n }\n\n const results = await mapWithConcurrency(batches, 1, (batch) => model.embedTexts(batch));\n const embeddings = results.flat();\n if (embeddings.length !== texts.length) {\n throw new Error(\n `Sparse embedding model returned ${embeddings.length} embeddings for ${texts.length} texts`,\n );\n }\n return embeddings;\n}\n\nexport async function embedSparseQuery(\n model: SparseEmbeddingModel,\n query: string,\n): Promise<SparseEmbedding> {\n return model.embedQuery(query);\n}\n\nexport async function embedDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n documents: T[],\n options: EmbedDocumentsOptions<T, Metadata>,\n): Promise<Array<EmbeddedDocument<T, Metadata>>> {\n const prepared = prepareDocuments(documents, options);\n\n const flatTexts = prepared.flatMap((item, documentIndex) =>\n item.texts.map((text) => ({ documentIndex, text })),\n );\n const embeddings = await mapWithConcurrency(\n chunk(flatTexts, Math.max(1, Math.trunc(model.maxBatchSize ?? (flatTexts.length || 1)))),\n Math.max(1, Math.trunc(options.concurrency ?? 1)),\n async (batch) => {\n const batchEmbeddings = await model.embedTexts(batch.map((item) => item.text));\n if (batchEmbeddings.length !== batch.length) {\n throw new Error(\n `Embedding model returned ${batchEmbeddings.length} embeddings for ${batch.length} texts`,\n );\n }\n return batch.map((item, index) => ({\n documentIndex: item.documentIndex,\n embedding: batchEmbeddings[index] as Embedding,\n }));\n },\n );\n\n const byDocument = new Map<number, Embedding[]>();\n for (const item of embeddings.flat()) {\n const list = byDocument.get(item.documentIndex) ?? [];\n list.push(item.embedding);\n byDocument.set(item.documentIndex, list);\n }\n\n return prepared.map((item, index) => {\n const documentEmbeddings = byDocument.get(index) ?? [];\n if (item.metadata === undefined) {\n return { id: item.id, document: item.document, embeddings: documentEmbeddings };\n }\n return {\n id: item.id,\n document: item.document,\n metadata: item.metadata,\n embeddings: documentEmbeddings,\n };\n });\n}\n\nexport async function embedHybridDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n models: EmbedHybridDocumentsOptions,\n documents: T[],\n options: EmbedDocumentsOptions<T, Metadata>,\n): Promise<Array<EmbeddedDocument<T, Metadata>>> {\n const prepared = prepareDocuments(documents, options);\n const flatTexts = prepared.flatMap((item, documentIndex) =>\n item.texts.map((text) => ({ documentIndex, text })),\n );\n const concurrency = Math.max(1, Math.trunc(options.concurrency ?? 1));\n\n const denseBatches = chunk(\n flatTexts,\n Math.max(1, Math.trunc(models.dense.maxBatchSize ?? (flatTexts.length || 1))),\n );\n const sparseBatches = chunk(\n flatTexts,\n Math.max(1, Math.trunc(models.sparse.maxBatchSize ?? (flatTexts.length || 1))),\n );\n\n const [denseResults, sparseResults] = await Promise.all([\n mapWithConcurrency(denseBatches, concurrency, async (batch) => {\n const batchEmbeddings = await models.dense.embedTexts(batch.map((item) => item.text));\n if (batchEmbeddings.length !== batch.length) {\n throw new Error(\n `Embedding model returned ${batchEmbeddings.length} embeddings for ${batch.length} texts`,\n );\n }\n return batch.map((item, index) => ({\n documentIndex: item.documentIndex,\n embedding: batchEmbeddings[index] as Embedding,\n }));\n }),\n mapWithConcurrency(sparseBatches, concurrency, async (batch) => {\n const batchEmbeddings = await models.sparse.embedTexts(batch.map((item) => item.text));\n if (batchEmbeddings.length !== batch.length) {\n throw new Error(\n `Sparse embedding model returned ${batchEmbeddings.length} embeddings for ${batch.length} texts`,\n );\n }\n return batch.map((item, index) => ({\n documentIndex: item.documentIndex,\n embedding: batchEmbeddings[index] as SparseEmbedding,\n }));\n }),\n ]);\n\n const denseByDocument = new Map<number, Embedding[]>();\n for (const item of denseResults.flat()) {\n const list = denseByDocument.get(item.documentIndex) ?? [];\n list.push(item.embedding);\n denseByDocument.set(item.documentIndex, list);\n }\n\n const sparseByDocument = new Map<number, SparseEmbedding[]>();\n for (const item of sparseResults.flat()) {\n const list = sparseByDocument.get(item.documentIndex) ?? [];\n list.push(item.embedding);\n sparseByDocument.set(item.documentIndex, list);\n }\n\n return prepared.map((item, index) => {\n const embeddings = denseByDocument.get(index) ?? [];\n const sparseEmbeddings = sparseByDocument.get(index) ?? [];\n if (embeddings.length !== sparseEmbeddings.length) {\n throw new Error(\n `Hybrid embedding produced ${embeddings.length} dense and ${sparseEmbeddings.length} sparse vectors for document ${item.id}`,\n );\n }\n if (item.metadata === undefined) {\n return { id: item.id, document: item.document, embeddings, sparseEmbeddings };\n }\n return {\n id: item.id,\n document: item.document,\n metadata: item.metadata,\n embeddings,\n sparseEmbeddings,\n };\n });\n}\n\nfunction prepareDocuments<T, Metadata extends VectorMetadata>(\n documents: T[],\n options: EmbedDocumentsOptions<T, Metadata>,\n) {\n return documents.map((document, index) => {\n const content = options.content(document, index);\n const texts = Array.isArray(content) ? content : [content];\n return {\n id: options.id?.(document, index) ?? `doc${index}`,\n document,\n metadata: options.metadata?.(document, index),\n texts,\n };\n });\n}\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n}\n"],"mappings":";AAAO,SAAS,WAAW,MAAgB,OAAyB;AAClE,uBAAqB,MAAM,KAAK;AAChC,SAAO,KAA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A,UAAU,QAAQ,WAAW,UAAU,KAAK;AAAA,MAC5C;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,SAAS,MAAS,OAAY,MAAqB;AACjD,QAAM,SAAgB,CAAC;AACvB,WAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,MAAM;AACvD,WAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,IAAI,CAAC;AAAA,EAC9C;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/guardrails/index.ts"],"sourcesContent":["import type { JsonObject, Message, Usage } from \"../completion\";\nimport type { MaybePromise } from \"../internal/type-utils\";\n\nexport type GuardrailMode = \"enforce\" | \"observe\";\n\nexport type GuardrailBoundary = \"input\" | \"output\";\n\nexport type GuardrailRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailDecisionRecord = {\n policyId: string;\n guardrailId: string;\n boundary: GuardrailBoundary;\n mode: GuardrailMode;\n action: GuardrailActionName;\n applied: boolean;\n reason?: string | undefined;\n message?: string | undefined;\n metadata?: JsonObject | undefined;\n latencyMs: number;\n};\n\nexport type GuardrailActionName = \"allow\" | \"block\" | \"rewrite\" | \"error\";\n\nexport type GuardrailActionBase = {\n reason?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailAllow = GuardrailActionBase & {\n action: \"allow\";\n};\n\nexport type GuardrailBlock = GuardrailActionBase & {\n action: \"block\";\n reason: string;\n message?: string | undefined;\n};\n\nexport type InputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n prompt?: Message | undefined;\n inputText?: string | undefined;\n};\n\nexport type OutputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n outputText: string;\n};\n\nexport type InputGuardrailResult = GuardrailAllow | GuardrailBlock | InputGuardrailRewrite;\nexport type OutputGuardrailResult = GuardrailAllow | GuardrailBlock | OutputGuardrailRewrite;\n\nexport type GuardrailCommonActions = {\n allow(options?: GuardrailActionBase): GuardrailAllow;\n block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock;\n};\n\nexport type InputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<InputGuardrailRewrite, \"action\">): InputGuardrailRewrite;\n};\n\nexport type OutputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<OutputGuardrailRewrite, \"action\">): OutputGuardrailRewrite;\n};\n\nexport type InputGuardrailContext = {\n prompt: Message;\n history: Message[];\n inputText: string;\n run: GuardrailRunContext;\n};\n\nexport type OutputGuardrailContext = {\n outputText: string;\n messages: Message[];\n usage: Usage;\n run: GuardrailRunContext;\n};\n\nexport type InputGuardrail = {\n id: string;\n check(\n context: InputGuardrailContext,\n actions: InputGuardrailActions,\n ): MaybePromise<InputGuardrailResult | undefined>;\n};\n\nexport type OutputGuardrail = {\n id: string;\n check(\n context: OutputGuardrailContext,\n actions: OutputGuardrailActions,\n ): MaybePromise<OutputGuardrailResult | undefined>;\n};\n\nexport type GuardrailPolicy = {\n id: string;\n mode: GuardrailMode;\n input: InputGuardrail[];\n output: OutputGuardrail[];\n};\n\nexport type GuardrailPolicyOptions = {\n id: string;\n mode?: GuardrailMode | undefined;\n input?: InputGuardrail[] | undefined;\n output?: OutputGuardrail[] | undefined;\n};\n\nexport type GuardrailPolicyInput = GuardrailPolicy | GuardrailPolicy[];\n\nexport type InputGuardrailRunResult = {\n prompt: Message;\n inputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport type OutputGuardrailRunResult = {\n outputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport function defineGuardrailPolicy(options: GuardrailPolicyOptions): GuardrailPolicy {\n return {\n id: options.id,\n mode: options.mode ?? \"enforce\",\n input: options.input ?? [],\n output: options.output ?? [],\n };\n}\n\nexport function defineInputGuardrail(guardrail: InputGuardrail): InputGuardrail {\n return guardrail;\n}\n\nexport function defineOutputGuardrail(guardrail: OutputGuardrail): OutputGuardrail {\n return guardrail;\n}\n\nexport function allow(options: GuardrailActionBase = {}): GuardrailAllow {\n return { action: \"allow\", ...options };\n}\n\nexport function block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock {\n return { action: \"block\", ...options };\n}\n\nexport const guardrails = {\n blockText,\n redactText,\n};\n\nexport function normalizeGuardrailPolicies(\n policies: GuardrailPolicyInput | undefined,\n): GuardrailPolicy[] {\n if (policies === undefined) {\n return [];\n }\n return Array.isArray(policies) ? policies : [policies];\n}\n\nexport function appendGuardrailPolicies(\n current: GuardrailPolicy[],\n next: GuardrailPolicyInput,\n): GuardrailPolicy[] {\n return [...current, ...normalizeGuardrailPolicies(next)];\n}\n\nexport function hasEnforcedOutputGuardrails(policies: GuardrailPolicy[]): boolean {\n return policies.some((policy) => policy.mode === \"enforce\" && policy.output.length > 0);\n}\n\nexport async function runInputGuardrails(\n policies: GuardrailPolicy[],\n context: InputGuardrailContext,\n): Promise<InputGuardrailRunResult> {\n let prompt = context.prompt;\n let inputText = context.inputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.input) {\n const currentContext = { ...context, prompt, inputText };\n const result = await runGuardrail(policy, guardrail.id, \"input\", () =>\n guardrail.check(currentContext, inputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n prompt,\n inputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n if (result.action.prompt !== undefined) {\n prompt = result.action.prompt;\n inputText = textFromMessage(prompt);\n } else if (result.action.inputText !== undefined) {\n inputText = result.action.inputText;\n prompt = rewriteMessageText(prompt, inputText);\n }\n }\n }\n }\n\n return { prompt, inputText, blocked: false, decisions };\n}\n\nexport async function runOutputGuardrails(\n policies: GuardrailPolicy[],\n context: OutputGuardrailContext,\n): Promise<OutputGuardrailRunResult> {\n let outputText = context.outputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.output) {\n const currentContext = { ...context, outputText };\n const result = await runGuardrail(policy, guardrail.id, \"output\", () =>\n guardrail.check(currentContext, outputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n outputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n outputText = result.action.outputText;\n }\n }\n }\n\n return { outputText, blocked: false, decisions };\n}\n\ntype RunGuardrailResult<TAction extends { action: GuardrailActionName }> = {\n action: TAction;\n decision: GuardrailDecisionRecord;\n};\n\nasync function runGuardrail<TAction extends { action: GuardrailActionName } & GuardrailActionBase>(\n policy: GuardrailPolicy,\n guardrailId: string,\n boundary: GuardrailBoundary,\n run: () => MaybePromise<TAction | undefined>,\n): Promise<RunGuardrailResult<TAction | GuardrailAllow>> {\n const startedAt = Date.now();\n try {\n const action = (await run()) ?? allow();\n return {\n action,\n decision: decisionRecord({\n policy,\n guardrailId,\n boundary,\n action,\n latencyMs: Date.now() - startedAt,\n }),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (policy.mode === \"observe\") {\n return {\n action: allow(),\n decision: {\n policyId: policy.id,\n guardrailId,\n boundary,\n mode: policy.mode,\n action: \"error\",\n applied: false,\n reason: message,\n latencyMs: Date.now() - startedAt,\n },\n };\n }\n throw error;\n }\n}\n\nfunction decisionRecord(args: {\n policy: GuardrailPolicy;\n guardrailId: string;\n boundary: GuardrailBoundary;\n action: GuardrailAllow | GuardrailBlock | ({ action: GuardrailActionName } & GuardrailActionBase);\n latencyMs: number;\n}): GuardrailDecisionRecord {\n const applied = args.policy.mode === \"enforce\" && args.action.action !== \"allow\";\n const record: GuardrailDecisionRecord = {\n policyId: args.policy.id,\n guardrailId: args.guardrailId,\n boundary: args.boundary,\n mode: args.policy.mode,\n action: args.action.action,\n applied,\n latencyMs: args.latencyMs,\n };\n if (args.action.reason !== undefined) record.reason = args.action.reason;\n if (\"message\" in args.action && typeof args.action.message === \"string\") {\n record.message = args.action.message;\n }\n if (args.action.metadata !== undefined) record.metadata = args.action.metadata;\n return record;\n}\n\nconst commonActions: GuardrailCommonActions = {\n allow,\n block,\n};\n\nconst inputActions: InputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\nconst outputActions: OutputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\ntype TextPatternBoundary = \"input\" | \"output\";\n\ntype TextPatternGuardrailFor<Boundary extends TextPatternBoundary> = Boundary extends \"input\"\n ? InputGuardrail\n : OutputGuardrail;\n\ntype TextPatternGuardrailOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> = {\n id: string;\n boundary: Boundary;\n patterns: Array<string | RegExp>;\n reason: string;\n message?: string | undefined;\n};\n\ntype TextPatternRedactOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> =\n TextPatternGuardrailOptions<Boundary> & { replacement?: string | undefined };\n\nfunction blockText<Boundary extends TextPatternBoundary>(\n options: TextPatternGuardrailOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"block\");\n}\n\nfunction redactText<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"rewrite\");\n}\n\nfunction textPatternGuardrail<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n action: \"block\" | \"rewrite\",\n): TextPatternGuardrailFor<Boundary> {\n if (options.boundary === \"input\") {\n return defineInputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.inputText, options, action, (value) =>\n actions.rewrite({ inputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n }\n return defineOutputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.outputText, options, action, (value) =>\n actions.rewrite({ outputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n}\n\nfunction textPatternAction<TRewrite>(\n text: string,\n options: TextPatternGuardrailOptions & { replacement?: string | undefined },\n action: \"block\" | \"rewrite\",\n rewrite: (value: string) => TRewrite,\n): GuardrailAllow | GuardrailBlock | TRewrite {\n const matched = options.patterns.some((pattern) => textPatternMatches(text, pattern));\n if (!matched) {\n return allow();\n }\n if (action === \"block\") {\n return block({\n reason: options.reason,\n message: options.message,\n });\n }\n let current = text;\n for (const pattern of options.patterns) {\n current = replaceTextPattern(current, pattern, options.replacement ?? \"[redacted]\");\n }\n return rewrite(current);\n}\n\nfunction textPatternMatches(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.includes(pattern);\n }\n pattern.lastIndex = 0;\n const matched = pattern.test(text);\n pattern.lastIndex = 0;\n return matched;\n}\n\nfunction replaceTextPattern(text: string, pattern: string | RegExp, replacement: string): string {\n if (typeof pattern === \"string\") {\n return text.split(pattern).join(replacement);\n }\n pattern.lastIndex = 0;\n const flags = pattern.flags.replace(\"y\", \"\");\n const globalFlags = flags.includes(\"g\") ? flags : `${flags}g`;\n return text.replace(new RegExp(pattern.source, globalFlags), replacement);\n}\n\nfunction textFromMessage(message: Message): string {\n if (message.role === \"system\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"document\" && content.source.type === \"text\") {\n return [content.source.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction rewriteMessageText(message: Message, text: string): Message {\n if (message.role === \"system\") {\n return { ...message, content: text };\n }\n if (message.role === \"user\") {\n return {\n ...message,\n content: [\n { type: \"text\", text },\n ...message.content.filter(\n (item) =>\n item.type !== \"text\" && !(item.type === \"document\" && item.source.type === \"text\"),\n ),\n ],\n };\n }\n if (message.role === \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