@anvia/core 1.0.0-rc.2 → 1.0.0-rc.3
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 +69 -9
- package/dist/agent/index.d.ts +20 -13
- package/dist/agent/index.js +36 -15
- package/dist/{agent-yBG8e9Jj.d.ts → agent-CXScUOpX.d.ts} +12 -15
- package/dist/{chunk-77AIYARB.js → chunk-3CMWKK32.js} +28 -19
- package/dist/chunk-3CMWKK32.js.map +1 -0
- package/dist/chunk-3RM57ZT2.js +31 -0
- package/dist/chunk-3RM57ZT2.js.map +1 -0
- package/dist/{chunk-EINTGEGY.js → chunk-5MK3BISB.js} +101 -26
- package/dist/chunk-5MK3BISB.js.map +1 -0
- package/dist/{chunk-KIDGIJM7.js → chunk-AZB6N7P4.js} +94 -86
- package/dist/chunk-AZB6N7P4.js.map +1 -0
- package/dist/{chunk-DBSCKTUL.js → chunk-BY4OMNIU.js} +1746 -840
- package/dist/chunk-BY4OMNIU.js.map +1 -0
- package/dist/{chunk-KR3RCCHJ.js → chunk-D2ECOWN5.js} +26 -11
- package/dist/chunk-D2ECOWN5.js.map +1 -0
- package/dist/{chunk-FMHLROPQ.js → chunk-GQL5KRAH.js} +13 -33
- package/dist/chunk-GQL5KRAH.js.map +1 -0
- package/dist/{chunk-OJH6HWHX.js → chunk-KFR4CDGK.js} +8 -2
- package/dist/chunk-KFR4CDGK.js.map +1 -0
- package/dist/{chunk-D37WMSP6.js → chunk-KV6QCRQ4.js} +50 -10
- package/dist/chunk-KV6QCRQ4.js.map +1 -0
- package/dist/{chunk-XKYYBABH.js → chunk-LXMAFD23.js} +2 -2
- package/dist/{chunk-TIZYTPJO.js → chunk-PK5LKOFL.js} +33 -2
- package/dist/chunk-PK5LKOFL.js.map +1 -0
- package/dist/chunk-TRQ3XRFD.js +54 -0
- package/dist/chunk-TRQ3XRFD.js.map +1 -0
- package/dist/{chunk-CWM7B2OO.js → chunk-VKYZZXP5.js} +10 -2
- package/dist/chunk-VKYZZXP5.js.map +1 -0
- package/dist/{chunk-4WI3VGZK.js → chunk-ZCPOIDAQ.js} +3 -3
- package/dist/{client-B8DT1vUG.d.ts → client-DvUatElp.d.ts} +4 -3
- package/dist/completion/index.d.ts +3 -3
- package/dist/completion/index.js +2 -2
- package/dist/documents/index.d.ts +34 -0
- package/dist/documents/index.js +315 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/{dynamic-tools-KwEGRbHp.d.ts → dynamic-tools-AEBOTgu1.d.ts} +3 -3
- package/dist/embeddings/index.js +2 -1
- package/dist/evals/index.d.ts +19 -11
- package/dist/evals/index.js +88 -55
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +1 -1
- package/dist/extractor/index.js +3 -3
- package/dist/guardrails/index.d.ts +6 -129
- package/dist/guardrails/index.js +1 -1
- package/dist/image-generation/index.d.ts +1 -1
- package/dist/index.d.ts +15 -14
- package/dist/index.js +40 -19
- package/dist/interactions-csssHYcN.d.ts +174 -0
- package/dist/internal/agent.d.ts +18 -22
- package/dist/internal/agent.js +45 -14
- package/dist/internal/agent.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +6 -5
- package/dist/memory/index.d.ts +3 -3
- package/dist/memory/index.js +3 -3
- package/dist/{message-schema-Cn7ezRfJ.d.ts → message-schema-B2M7AYzR.d.ts} +1 -1
- package/dist/observability/index.d.ts +8 -7
- package/dist/observability/index.js +3 -3
- package/dist/pipeline/index.d.ts +18 -18
- package/dist/pipeline/index.js +20 -29
- package/dist/pipeline/index.js.map +1 -1
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +6 -5
- package/dist/speech-generation/index.d.ts +1 -1
- package/dist/text-C_6eKrbC.d.ts +32 -0
- package/dist/{think-tool-6H2QNQzQ.d.ts → think-tool-D8frXxwV.d.ts} +16 -2
- package/dist/tool/index.d.ts +6 -6
- package/dist/tool/index.js +9 -4
- package/dist/{tool--Mz4v1eL.d.ts → tool-r62gf3QY.d.ts} +3 -2
- package/dist/transcription/index.d.ts +1 -1
- package/dist/{types-Dld1TpWj.d.ts → types-C3gv9EX6.d.ts} +1 -1
- package/dist/{types-3x3mOLHU.d.ts → types-CElwurHZ.d.ts} +56 -35
- package/dist/types-CIPaIbZo.d.ts +105 -0
- package/dist/{types-CQ_ioXWK.d.ts → types-D9rKQ_as.d.ts} +24 -2
- package/dist/{types-BVzM4RsC.d.ts → types-DbolvLtZ.d.ts} +1 -1
- package/dist/{types-DiJqJejp.d.ts → types-RT3cuyRk.d.ts} +1 -1
- package/dist/vector-store/index.d.ts +4 -4
- package/dist/vector-store/index.js +4 -3
- package/package.json +6 -6
- package/dist/chunk-77AIYARB.js.map +0 -1
- package/dist/chunk-CWM7B2OO.js.map +0 -1
- package/dist/chunk-D37WMSP6.js.map +0 -1
- package/dist/chunk-DBSCKTUL.js.map +0 -1
- package/dist/chunk-EINTGEGY.js.map +0 -1
- package/dist/chunk-FMHLROPQ.js.map +0 -1
- package/dist/chunk-KIDGIJM7.js.map +0 -1
- package/dist/chunk-KR3RCCHJ.js.map +0 -1
- package/dist/chunk-OJH6HWHX.js.map +0 -1
- package/dist/chunk-TIZYTPJO.js.map +0 -1
- package/dist/loaders/index.d.ts +0 -87
- package/dist/loaders/index.js +0 -299
- package/dist/loaders/index.js.map +0 -1
- package/dist/middleware-C7PdmKF7.d.ts +0 -56
- /package/dist/{chunk-XKYYBABH.js.map → chunk-LXMAFD23.js.map} +0 -0
- /package/dist/{chunk-4WI3VGZK.js.map → chunk-ZCPOIDAQ.js.map} +0 -0
package/README.md
CHANGED
|
@@ -202,16 +202,37 @@ await agent.generate({
|
|
|
202
202
|
```
|
|
203
203
|
|
|
204
204
|
Agent results are discriminated by `status`. Completed results include typed `output` and `text`;
|
|
205
|
-
guardrail blocks return `status: "blocked"`, `stage`, and `text`; tool
|
|
206
|
-
`status: "
|
|
205
|
+
guardrail blocks return `status: "blocked"`, `stage`, and `text`; tool approvals and first-class
|
|
206
|
+
questions return a JSON-safe `status: "suspended"` result.
|
|
207
207
|
|
|
208
208
|
```ts
|
|
209
209
|
const result = await agent.generate({ prompt: "Help with this request." });
|
|
210
210
|
|
|
211
211
|
if (result.status === "completed") console.log(result.output);
|
|
212
212
|
if (result.status === "blocked") console.log(result.stage, result.text);
|
|
213
|
+
if (result.status === "suspended") {
|
|
214
|
+
const resumed = await agent.generate({
|
|
215
|
+
continuation: result.continuation,
|
|
216
|
+
response:
|
|
217
|
+
result.interaction.type === "tool-approval"
|
|
218
|
+
? { type: "tool-approval", approved: true }
|
|
219
|
+
: {
|
|
220
|
+
type: "tool-question",
|
|
221
|
+
answers: result.interaction.questions.map((question) => ({
|
|
222
|
+
questionId: question.id,
|
|
223
|
+
value: "application-provided answer",
|
|
224
|
+
})),
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
console.log(resumed.status, resumed.resumedFrom);
|
|
228
|
+
}
|
|
213
229
|
```
|
|
214
230
|
|
|
231
|
+
Keep continuations server-side. A resumed phase receives a new `runId`; Core validates the
|
|
232
|
+
continuation and current Agent/tool registration but does not provide a durable continuation store
|
|
233
|
+
or exactly-once execution. Use `createQuestionTool({ name, description })` when a model must ask for
|
|
234
|
+
structured free-text or choice answers.
|
|
235
|
+
|
|
215
236
|
An Agent with `outputSchema` carries that output type through `generate`, `stream`, `asTool`, and
|
|
216
237
|
Pipeline Agent stages. Agent stream finals use the same result shape:
|
|
217
238
|
|
|
@@ -344,7 +365,7 @@ const pipeline = new Pipeline({ id: "support-flow", inputSchema: z.string() })
|
|
|
344
365
|
.agent({
|
|
345
366
|
id: "draft",
|
|
346
367
|
agent,
|
|
347
|
-
|
|
368
|
+
suspension: "reject",
|
|
348
369
|
request: ({ input }) => ({ prompt: `Draft a reply for this ticket:\n\n${input}` }),
|
|
349
370
|
})
|
|
350
371
|
.extract({
|
|
@@ -359,6 +380,37 @@ const { runId, output } = await pipeline.run({
|
|
|
359
380
|
});
|
|
360
381
|
```
|
|
361
382
|
|
|
383
|
+
## Documents
|
|
384
|
+
|
|
385
|
+
Applications own file discovery, file reads, source metadata, and per-file error policy. Core only
|
|
386
|
+
provides deterministic in-memory chunking and scoped PDF text extraction:
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
import { readFile } from "node:fs/promises";
|
|
390
|
+
import { chunkText, extractPdfText } from "@anvia/core/documents";
|
|
391
|
+
|
|
392
|
+
const text = await readFile("guide.txt", "utf8");
|
|
393
|
+
const chunks = chunkText({
|
|
394
|
+
text,
|
|
395
|
+
strategy: "recursive",
|
|
396
|
+
maxSize: 1_000,
|
|
397
|
+
overlap: 100,
|
|
398
|
+
separators: ["\n\n", "\n", " "],
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
const { pages } = await extractPdfText({
|
|
402
|
+
data: new Uint8Array(await readFile("guide.pdf")),
|
|
403
|
+
abortSignal,
|
|
404
|
+
});
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
Use `strategy: "fixed"` for deterministic sliding windows. Recursive chunking requires an explicit
|
|
408
|
+
separator order and falls back to fixed-size splitting when none of those separators can divide an
|
|
409
|
+
oversized section. Chunk offsets use JavaScript string indices and always identify the exact source
|
|
410
|
+
slice. PDF pages are one-based, and the parser task is disposed before extraction settles.
|
|
411
|
+
If parsing or abort handling fails together with parser cleanup, extraction rejects with an
|
|
412
|
+
`AggregateError` containing the operation failure first and the cleanup failure second.
|
|
413
|
+
|
|
362
414
|
## Media
|
|
363
415
|
|
|
364
416
|
Media helpers follow the same one-object API and share `providerOptions`, `retries`, and
|
|
@@ -414,7 +466,7 @@ const github = new McpClient({
|
|
|
414
466
|
transport: {
|
|
415
467
|
type: "streamableHttp",
|
|
416
468
|
url: "https://mcp.example.com/mcp",
|
|
417
|
-
|
|
469
|
+
headers: { authorization: `Bearer ${process.env.MCP_TOKEN}` },
|
|
418
470
|
},
|
|
419
471
|
tools: { prefix: "github_" },
|
|
420
472
|
});
|
|
@@ -431,13 +483,21 @@ try {
|
|
|
431
483
|
|
|
432
484
|
Construction performs no I/O. `connect()` discovers every tool page once and returns a frozen
|
|
433
485
|
registration snapshot. Reconnect and rebuild the Agent to adopt changed remote tools. Built-in
|
|
434
|
-
Streamable HTTP connections enforce Anvia URL safety and do not accept a custom `fetch
|
|
435
|
-
|
|
436
|
-
|
|
486
|
+
Streamable HTTP connections enforce Anvia URL safety by default and do not accept a custom `fetch`.
|
|
487
|
+
Static request headers are explicit transport configuration; arbitrary Fetch `RequestInit` fields
|
|
488
|
+
are not exposed because the MCP transport owns its HTTP method, body, abort signal, session, and
|
|
489
|
+
protocol headers. Configured headers are sent only to the exact MCP endpoint, are not attached to
|
|
490
|
+
OAuth requests, and cause endpoint redirects to fail instead of forwarding credentials. A static
|
|
491
|
+
`authorization` header cannot be combined with `authProvider`.
|
|
492
|
+
For an intentionally local or private-network server, set `ssrfProtection: "disabled"` on that
|
|
493
|
+
transport. This disables hostname and DNS restrictions for the complete transport, including
|
|
494
|
+
redirects and OAuth discovery, while still requiring HTTP(S). Use it only when the application owns
|
|
495
|
+
and trusts that network boundary. MCP server instructions remain inspectable metadata and are not
|
|
496
|
+
added to Agent instructions.
|
|
437
497
|
|
|
438
498
|
## Public Areas
|
|
439
499
|
|
|
440
|
-
- `agent`: typed Agent runtime,
|
|
500
|
+
- `agent`: typed Agent runtime, continuations, interactions, retries, and stream events
|
|
441
501
|
- `tool`: typed tool creation and tool sets
|
|
442
502
|
- `completion`: direct completion helpers and provider-neutral model contracts
|
|
443
503
|
- `memory`: durable session memory interfaces and in-memory store
|
|
@@ -450,7 +510,7 @@ MCP server instructions remain inspectable metadata and are not added to Agent i
|
|
|
450
510
|
- `skills`: local skill loading
|
|
451
511
|
- `observability`: observer interfaces for runs, generations, and tool calls
|
|
452
512
|
- `evals`: evaluation helpers and reporters
|
|
453
|
-
- `
|
|
513
|
+
- `documents`: in-memory text chunking and PDF text extraction
|
|
454
514
|
- `speech-generation`, `image-generation`, `transcription`: provider-neutral media interfaces
|
|
455
515
|
|
|
456
516
|
## Development
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
export { M as ModelCallOptions } from '../model-call-options-CZkSw_xN.js';
|
|
2
2
|
export { R as RetryContext, a as RetryOptions, b as RetrySetting } from '../retry-CjvSlKGW.js';
|
|
3
|
-
export { A as Agent, a as AgentContextInput, b as AgentMemory, c as AgentMemoryOptions, d as AgentOptions, e as AgentToolInput, f as AgentToolOptions, C as CreateHybridVectorContextOptions, g as CreateVectorContextOptions, V as VectorContext, h as VectorContextBaseOptions, i as createVectorContext, j as isVectorContext } from '../agent-
|
|
4
|
-
import { M as Message } from '../types-
|
|
5
|
-
import {
|
|
6
|
-
export {
|
|
3
|
+
export { A as Agent, a as AgentContextInput, b as AgentMemory, c as AgentMemoryOptions, d as AgentOptions, e as AgentToolInput, f as AgentToolOptions, C as CreateHybridVectorContextOptions, g as CreateVectorContextOptions, V as VectorContext, h as VectorContextBaseOptions, i as createVectorContext, j as isVectorContext } from '../agent-CXScUOpX.js';
|
|
4
|
+
import { M as Message } from '../types-D9rKQ_as.js';
|
|
5
|
+
import { A as AgentBlockedResult, t as AgentSuspendedResult } from '../types-CElwurHZ.js';
|
|
6
|
+
export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, g as AgentLifecycle, h as AgentMemoryCompactionEvent, i as AgentPrompt, j as AgentResponse, k as AgentResult, l as AgentRunOptions, m as AgentRunSettings, n as AgentStartEvent, o as AgentSteerInput, p as AgentSteerReceipt, q as AgentStepFinishEvent, r as AgentStream, s as AgentStreamEvent, u as AgentToolCallDeltaEvent, v as AgentToolFinishEvent, w as AgentToolStartEvent } from '../types-CElwurHZ.js';
|
|
7
|
+
export { A as AgentContinuation, a as AgentInteractionRequest, b as AgentInteractionResponse, d as AgentQuestionAnswer, e as AgentQuestionChoice, f as AgentQuestionPrompt, g as AgentToolApprovalRequest, h as AgentToolQuestionRequest, p as agentContinuationSchema, q as agentInteractionRequestSchema, r as agentInteractionResponseSchema, w as assertAgentInteractionResponse, t as parseAgentContinuation, u as parseAgentInteractionRequest, v as parseAgentInteractionResponse } from '../interactions-csssHYcN.js';
|
|
7
8
|
import '../zod-schema-C7F4clpm.js';
|
|
8
9
|
import 'zod';
|
|
9
|
-
import '../
|
|
10
|
+
import '../types-CIPaIbZo.js';
|
|
10
11
|
import '../type-utils-CtHVDRn_.js';
|
|
11
|
-
import '../client-
|
|
12
|
+
import '../client-DvUatElp.js';
|
|
12
13
|
import 'node:child_process';
|
|
13
14
|
import 'node:stream';
|
|
14
15
|
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
15
16
|
import '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
16
17
|
import '@modelcontextprotocol/sdk/shared/transport.js';
|
|
17
|
-
import '../tool
|
|
18
|
-
import '../
|
|
19
|
-
import '../types-
|
|
20
|
-
import '../
|
|
21
|
-
import '../dynamic-tools-KwEGRbHp.js';
|
|
18
|
+
import '../tool-r62gf3QY.js';
|
|
19
|
+
import '../types-DbolvLtZ.js';
|
|
20
|
+
import '../types-RT3cuyRk.js';
|
|
21
|
+
import '../dynamic-tools-AEBOTgu1.js';
|
|
22
22
|
import '../types-Cr4uiYo5.js';
|
|
23
|
-
import '../types-
|
|
23
|
+
import '../types-C3gv9EX6.js';
|
|
24
24
|
|
|
25
25
|
declare class MaxTurnsError extends Error {
|
|
26
26
|
readonly maxTurns: number;
|
|
@@ -37,5 +37,12 @@ declare class AgentRunBlockedError extends Error {
|
|
|
37
37
|
readonly result: AgentBlockedResult;
|
|
38
38
|
constructor(result: AgentBlockedResult);
|
|
39
39
|
}
|
|
40
|
+
declare class AgentStreamClosedError extends Error {
|
|
41
|
+
constructor();
|
|
42
|
+
}
|
|
43
|
+
declare class AgentToolSuspensionError extends Error {
|
|
44
|
+
readonly result: AgentSuspendedResult;
|
|
45
|
+
constructor(result: AgentSuspendedResult);
|
|
46
|
+
}
|
|
40
47
|
|
|
41
|
-
export { AgentBlockedResult, AgentRunBlockedError, AgentRunCancelledError, MaxTurnsError };
|
|
48
|
+
export { AgentBlockedResult, AgentRunBlockedError, AgentRunCancelledError, AgentStreamClosedError, AgentSuspendedResult, AgentToolSuspensionError, MaxTurnsError };
|
package/dist/agent/index.js
CHANGED
|
@@ -1,30 +1,51 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
agentContinuationSchema,
|
|
4
|
+
agentInteractionRequestSchema,
|
|
5
|
+
agentInteractionResponseSchema,
|
|
6
|
+
assertAgentInteractionResponse,
|
|
6
7
|
createVectorContext,
|
|
7
|
-
isVectorContext
|
|
8
|
-
|
|
8
|
+
isVectorContext,
|
|
9
|
+
parseAgentContinuation,
|
|
10
|
+
parseAgentInteractionRequest,
|
|
11
|
+
parseAgentInteractionResponse
|
|
12
|
+
} from "../chunk-BY4OMNIU.js";
|
|
9
13
|
import "../chunk-YK4WAAS4.js";
|
|
10
|
-
import "../chunk-
|
|
14
|
+
import "../chunk-5MK3BISB.js";
|
|
11
15
|
import "../chunk-CQNNSZPG.js";
|
|
12
|
-
import "../chunk-
|
|
13
|
-
import "../chunk-
|
|
14
|
-
import "../chunk-
|
|
15
|
-
import "../chunk-
|
|
16
|
-
import
|
|
16
|
+
import "../chunk-KV6QCRQ4.js";
|
|
17
|
+
import "../chunk-3CMWKK32.js";
|
|
18
|
+
import "../chunk-KFR4CDGK.js";
|
|
19
|
+
import "../chunk-VKYZZXP5.js";
|
|
20
|
+
import {
|
|
21
|
+
AgentRunBlockedError,
|
|
22
|
+
AgentRunCancelledError,
|
|
23
|
+
AgentStreamClosedError,
|
|
24
|
+
AgentToolSuspensionError,
|
|
25
|
+
MaxTurnsError
|
|
26
|
+
} from "../chunk-TRQ3XRFD.js";
|
|
27
|
+
import "../chunk-GQL5KRAH.js";
|
|
28
|
+
import "../chunk-3RM57ZT2.js";
|
|
17
29
|
import "../chunk-MGNTXGTX.js";
|
|
18
|
-
import "../chunk-
|
|
19
|
-
import "../chunk-
|
|
20
|
-
import "../chunk-KIDGIJM7.js";
|
|
30
|
+
import "../chunk-D2ECOWN5.js";
|
|
31
|
+
import "../chunk-PK5LKOFL.js";
|
|
21
32
|
import "../chunk-FN7HLLAZ.js";
|
|
33
|
+
import "../chunk-AZB6N7P4.js";
|
|
22
34
|
export {
|
|
23
35
|
Agent,
|
|
24
36
|
AgentRunBlockedError,
|
|
25
37
|
AgentRunCancelledError,
|
|
38
|
+
AgentStreamClosedError,
|
|
39
|
+
AgentToolSuspensionError,
|
|
26
40
|
MaxTurnsError,
|
|
41
|
+
agentContinuationSchema,
|
|
42
|
+
agentInteractionRequestSchema,
|
|
43
|
+
agentInteractionResponseSchema,
|
|
44
|
+
assertAgentInteractionResponse,
|
|
27
45
|
createVectorContext,
|
|
28
|
-
isVectorContext
|
|
46
|
+
isVectorContext,
|
|
47
|
+
parseAgentContinuation,
|
|
48
|
+
parseAgentInteractionRequest,
|
|
49
|
+
parseAgentInteractionResponse
|
|
29
50
|
};
|
|
30
51
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { b as RetrySetting } from './retry-CjvSlKGW.js';
|
|
2
|
-
import { D as Document, C as CompletionModel, P as ProviderTool, J as JsonObject, u as ToolChoice } from './types-
|
|
2
|
+
import { D as Document, C as CompletionModel, P as ProviderTool, J as JsonObject, u as ToolChoice } from './types-D9rKQ_as.js';
|
|
3
3
|
import { Z as ZodSchema } from './zod-schema-C7F4clpm.js';
|
|
4
|
-
import { GuardrailPolicyInput, GuardrailPolicy } from './
|
|
5
|
-
import { a as McpServer } from './client-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool
|
|
9
|
-
import { D as MemoryStore, y as MemorySavePolicy, m as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, x as MemoryOptions } from './types-
|
|
10
|
-
import { a as SkillSet } from './types-
|
|
11
|
-
import { T as ToolIndex } from './dynamic-tools-
|
|
4
|
+
import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-CIPaIbZo.js';
|
|
5
|
+
import { a as McpServer } from './client-DvUatElp.js';
|
|
6
|
+
import { g as AgentLifecycle, E as AgentObservabilityOptions, l as AgentRunOptions, k as AgentResult, r as AgentStream, s as AgentStreamEvent } from './types-CElwurHZ.js';
|
|
7
|
+
import { c as AgentMiddleware } from './interactions-csssHYcN.js';
|
|
8
|
+
import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-r62gf3QY.js';
|
|
9
|
+
import { D as MemoryStore, y as MemorySavePolicy, m as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, x as MemoryOptions } from './types-DbolvLtZ.js';
|
|
10
|
+
import { a as SkillSet } from './types-RT3cuyRk.js';
|
|
11
|
+
import { T as ToolIndex } from './dynamic-tools-AEBOTgu1.js';
|
|
12
12
|
import { E as EmbeddingModel, c as SparseEmbeddingModel } from './types-Cr4uiYo5.js';
|
|
13
|
-
import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-
|
|
13
|
+
import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-C3gv9EX6.js';
|
|
14
14
|
|
|
15
15
|
type VectorContextBaseOptions<T = unknown> = {
|
|
16
16
|
topK: number;
|
|
@@ -109,6 +109,7 @@ type ResolvedAgentOptions<Output = string, M extends CompletionModel = Completio
|
|
|
109
109
|
};
|
|
110
110
|
type AgentToolOptions = {
|
|
111
111
|
name: string;
|
|
112
|
+
suspension: "reject";
|
|
112
113
|
description?: string | undefined;
|
|
113
114
|
maxTurns?: number | undefined;
|
|
114
115
|
stream?: boolean | undefined;
|
|
@@ -139,15 +140,11 @@ declare class Agent<Output = string, M extends CompletionModel = CompletionModel
|
|
|
139
140
|
constructor(options: AgentOptions<Output, M, ContextDocument>);
|
|
140
141
|
generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentResult<Output>>;
|
|
141
142
|
stream(options: AgentRunOptions<Output, RawResponseOf<M>>): AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>>;
|
|
142
|
-
resume(pending: AgentApprovalRequiredResult, decision: AgentApprovalDecision): Promise<AgentResult<Output>>;
|
|
143
|
-
resume(pending: AgentApprovalRequiredEvent, decision: AgentApprovalDecision): AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>>;
|
|
144
143
|
asTool(options: AgentToolOptions): Tool<{
|
|
145
144
|
prompt: string;
|
|
146
145
|
}, Output>;
|
|
147
146
|
getTool(toolName: string): AnyTool | undefined;
|
|
148
147
|
callTool(toolName: string, args: string, context?: ToolCallContext): Promise<NormalizedToolOutput>;
|
|
149
148
|
}
|
|
150
|
-
declare function createResolvedAgent<Output = string, M extends CompletionModel = CompletionModel, ContextDocument = unknown>(options: ResolvedAgentOptions<Output, M, ContextDocument>): Agent<Output, M, ContextDocument>;
|
|
151
|
-
declare function getResolvedAgentOptions<Output, M extends CompletionModel, ContextDocument>(agent: Agent<Output, M, ContextDocument>): ResolvedAgentOptions<Output, M, ContextDocument>;
|
|
152
149
|
|
|
153
|
-
export { Agent as A, type CreateHybridVectorContextOptions as C, type ResolvedAgentOptions as R, type VectorContext as V, type AgentContextInput as a, type AgentMemory as b, type AgentMemoryOptions as c, type AgentOptions as d, type AgentToolInput as e, type AgentToolOptions as f, type CreateVectorContextOptions as g, type VectorContextBaseOptions as h, createVectorContext as i, isVectorContext as j
|
|
150
|
+
export { Agent as A, type CreateHybridVectorContextOptions as C, type ResolvedAgentOptions as R, type VectorContext as V, type AgentContextInput as a, type AgentMemory as b, type AgentMemoryOptions as c, type AgentOptions as d, type AgentToolInput as e, type AgentToolOptions as f, type CreateVectorContextOptions as g, type VectorContextBaseOptions as h, createVectorContext as i, isVectorContext as j };
|
|
@@ -2,12 +2,12 @@ import {
|
|
|
2
2
|
cosineSimilarity,
|
|
3
3
|
embedSparseQuery,
|
|
4
4
|
embedText
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-GQL5KRAH.js";
|
|
6
6
|
import {
|
|
7
7
|
isJsonValue,
|
|
8
8
|
parseMessage,
|
|
9
9
|
toProviderJsonSchema
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-PK5LKOFL.js";
|
|
11
11
|
import {
|
|
12
12
|
resolveRetryOptions,
|
|
13
13
|
runWithRetries,
|
|
@@ -113,6 +113,7 @@ function normalizeToolResultOutput(output) {
|
|
|
113
113
|
});
|
|
114
114
|
if (message.role !== "tool") throw new TypeError("Unexpected message role");
|
|
115
115
|
const result = message.content[0];
|
|
116
|
+
if (result?.type !== "tool-result") throw new TypeError("Unexpected tool result part");
|
|
116
117
|
if (result?.output.type !== "content") throw new TypeError("Unexpected tool output");
|
|
117
118
|
return result.output;
|
|
118
119
|
} catch {
|
|
@@ -176,6 +177,9 @@ function prepareToolCall(tool, args) {
|
|
|
176
177
|
} catch (error) {
|
|
177
178
|
throw asToolCallError(tool.name, error);
|
|
178
179
|
}
|
|
180
|
+
return prepareToolCallFromInput(tool, input);
|
|
181
|
+
}
|
|
182
|
+
function prepareToolCallFromInput(tool, input) {
|
|
179
183
|
return {
|
|
180
184
|
input,
|
|
181
185
|
async call(context) {
|
|
@@ -472,14 +476,15 @@ var InMemoryVectorStore = class _InMemoryVectorStore {
|
|
|
472
476
|
if (score === void 0 || request.minScore !== void 0 && score < request.minScore) {
|
|
473
477
|
return [];
|
|
474
478
|
}
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
}
|
|
482
|
-
|
|
479
|
+
let result = {
|
|
480
|
+
score,
|
|
481
|
+
id: document.id,
|
|
482
|
+
document: document.document
|
|
483
|
+
};
|
|
484
|
+
if (document.metadata !== void 0) {
|
|
485
|
+
result = { ...result, metadata: document.metadata };
|
|
486
|
+
}
|
|
487
|
+
return [result];
|
|
483
488
|
}).sort((left, right) => right.score - left.score).slice(0, request.topK);
|
|
484
489
|
throwIfAborted2(request.abortSignal);
|
|
485
490
|
return results;
|
|
@@ -494,13 +499,16 @@ var InMemoryVectorStore = class _InMemoryVectorStore {
|
|
|
494
499
|
const page = documents.slice(start, start + limit);
|
|
495
500
|
const nextOffset = start + page.length;
|
|
496
501
|
const result = {
|
|
497
|
-
items: page.map(
|
|
498
|
-
|
|
502
|
+
items: page.map((document) => {
|
|
503
|
+
let item = {
|
|
499
504
|
id: document.id,
|
|
500
|
-
document: document.document
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
505
|
+
document: document.document
|
|
506
|
+
};
|
|
507
|
+
if (document.metadata !== void 0) {
|
|
508
|
+
item = { ...item, metadata: document.metadata };
|
|
509
|
+
}
|
|
510
|
+
return item;
|
|
511
|
+
}),
|
|
504
512
|
totalCount: documents.length
|
|
505
513
|
};
|
|
506
514
|
if (nextOffset < documents.length) result.nextCursor = String(nextOffset);
|
|
@@ -634,8 +642,6 @@ function assertFiniteVector(vector, id) {
|
|
|
634
642
|
export {
|
|
635
643
|
toolMayRequireApproval,
|
|
636
644
|
assertToolApprovalRequirement,
|
|
637
|
-
assertPositiveSearchLimit,
|
|
638
|
-
assertFiniteMinScore,
|
|
639
645
|
ToolCallError,
|
|
640
646
|
ToolNotFoundError,
|
|
641
647
|
ToolJsonError,
|
|
@@ -645,10 +651,13 @@ export {
|
|
|
645
651
|
toolResultContentToText,
|
|
646
652
|
parseToolArgs,
|
|
647
653
|
prepareToolCall,
|
|
654
|
+
prepareToolCallFromInput,
|
|
648
655
|
createTool,
|
|
656
|
+
assertPositiveSearchLimit,
|
|
657
|
+
assertFiniteMinScore,
|
|
649
658
|
vectorFilter,
|
|
650
659
|
retrieveDocuments,
|
|
651
660
|
InMemoryVectorStore,
|
|
652
661
|
createVectorSearchTool
|
|
653
662
|
};
|
|
654
|
-
//# sourceMappingURL=chunk-
|
|
663
|
+
//# sourceMappingURL=chunk-3CMWKK32.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vector-store/index.ts","../src/internal/vector-search-options.ts","../src/internal/agent-runtime/approval-requirement.ts","../src/tool/errors.ts","../src/tool/tool.ts","../src/internal/agent-runtime/prepared-tool-call.ts","../src/tool/create-tool.ts","../src/vector-store/filter.ts","../src/vector-store/lsh.ts","../src/vector-store/retrieve.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n cosineSimilarity,\n type EmbeddedDocument,\n type Embedding,\n type VectorMetadata,\n} from \"../embeddings\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool } from \"../tool/tool\";\nimport { matchesVectorFilter } from \"./filter\";\nimport { LshIndex } from \"./lsh\";\nimport { retrieveDocuments } from \"./retrieve\";\nimport type {\n IndexStrategy,\n VectorInspectItem,\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n VectorStore,\n VectorStoreUpsertOptions,\n} from \"./types\";\n\nexport { vectorFilter } from \"./filter\";\nexport { retrieveDocuments } from \"./retrieve\";\nexport type * from \"./types\";\n\ntype StoredDocument<T, Metadata extends VectorMetadata> = EmbeddedDocument<T, Metadata>;\n\nexport type InMemoryVectorStoreOptions = {\n dimensions?: number | undefined;\n index?: IndexStrategy | undefined;\n};\n\nexport type InMemoryVectorStoreFromDocumentsOptions<\n T,\n Metadata extends VectorMetadata = VectorMetadata,\n> = InMemoryVectorStoreOptions & {\n documents: Array<EmbeddedDocument<T, Metadata>>;\n};\n\nexport class InMemoryVectorStore<T, Metadata extends VectorMetadata = VectorMetadata>\n implements VectorStore<T, Metadata>\n{\n private readonly documents = new Map<string, StoredDocument<T, Metadata>>();\n private readonly indexStrategy: IndexStrategy;\n private lshIndex: LshIndex | undefined;\n private embeddingDimension: number | undefined;\n\n constructor(options: InMemoryVectorStoreOptions = {}) {\n this.indexStrategy = options.index ?? { type: \"bruteForce\" };\n if (\n options.dimensions !== undefined &&\n (!Number.isSafeInteger(options.dimensions) || options.dimensions < 1)\n ) {\n throw new RangeError(\"Vector dimensions must be a positive safe integer.\");\n }\n this.embeddingDimension = options.dimensions;\n }\n\n static fromDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: InMemoryVectorStoreFromDocumentsOptions<T, Metadata>,\n ): InMemoryVectorStore<T, Metadata> {\n const store = new InMemoryVectorStore<T, Metadata>(options);\n store.replaceDocuments(options.documents);\n return store;\n }\n\n async ensure(): Promise<void> {}\n async validate(): Promise<void> {}\n\n async upsert(options: VectorStoreUpsertOptions<T, Metadata>): Promise<void> {\n this.replaceDocuments(options.documents);\n }\n\n get(options: { id: string }): StoredDocument<T, Metadata> | undefined {\n return this.documents.get(options.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 async search(request: VectorSearchRequest): Promise<Array<VectorSearchResult<T, Metadata>>> {\n throwIfAborted(request.abortSignal);\n assertPositiveSearchLimit(request.topK);\n assertFiniteMinScore(request.minScore);\n const queryEmbedding: Embedding = { document: \"\", vector: request.vector };\n const results = this.candidates(queryEmbedding)\n .filter((document) => matchesVectorFilter(document.metadata, request.filter))\n .flatMap((document) => {\n const score = bestScore(queryEmbedding, document.embeddings);\n if (score === undefined || (request.minScore !== undefined && score < request.minScore)) {\n return [];\n }\n let result: VectorSearchResult<T, Metadata> = {\n score,\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n result = { ...result, metadata: document.metadata };\n }\n return [result];\n })\n .sort((left, right) => right.score - left.score)\n .slice(0, request.topK);\n throwIfAborted(request.abortSignal);\n return results;\n }\n\n async inspect(request: VectorInspectRequest): Promise<VectorInspectPage<T, Metadata>> {\n throwIfAborted(request.abortSignal);\n const limit = assertPositiveSearchLimit(request.limit);\n const start = Math.max(0, Math.trunc(Number(request.cursor ?? \"0\")));\n const documents = this.values().filter((document) =>\n matchesVectorFilter(document.metadata, request.filter),\n );\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): VectorInspectItem<T, Metadata> => {\n let item: VectorInspectItem<T, Metadata> = {\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n item = { ...item, metadata: document.metadata };\n }\n return item;\n }),\n totalCount: documents.length,\n };\n if (nextOffset < documents.length) result.nextCursor = String(nextOffset);\n throwIfAborted(request.abortSignal);\n return result;\n }\n\n private replaceDocuments(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n const ids = new Set<string>();\n for (const document of documents) {\n if (ids.has(document.id)) throw new TypeError(`Duplicate vector document id: ${document.id}`);\n ids.add(document.id);\n if (document.embeddings.length === 0) {\n throw new TypeError(`Vector document ${document.id} must contain at least one embedding.`);\n }\n for (const embedding of document.embeddings)\n assertFiniteVector(embedding.vector, document.id);\n }\n this.validateDocumentDimensions(documents);\n for (const document of documents) this.documents.set(document.id, document);\n this.rebuildLshIndex();\n }\n\n private candidates(queryEmbedding: Embedding): Array<StoredDocument<T, Metadata>> {\n this.validateQueryDimension(queryEmbedding);\n if (this.indexStrategy.type !== \"lsh\" || this.lshIndex === undefined) return this.values();\n const candidateIds = this.lshIndex.query(queryEmbedding.vector);\n if (candidateIds.size === 0) return this.values();\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 const firstEmbedding = this.values().flatMap((document) => document.embeddings)[0];\n if (firstEmbedding === undefined) {\n this.lshIndex = undefined;\n return;\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) index.insert(document.id, embedding.vector);\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 validateEmbeddingDimension(this.embeddingDimension, queryEmbedding, \"query\");\n }\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n const error = new Error(\"The operation was aborted.\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function createVectorSearchTool<T, Metadata extends VectorMetadata>(\n options: VectorSearchToolOptions<T, Metadata>,\n): Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>> {\n const configuredTopK = assertPositiveSearchLimit(options.topK ?? 5);\n assertFiniteMinScore(options.minScore);\n return createTool({\n name: options.name,\n description:\n options.description ?? \"Search a vector store for documents relevant to the provided query.\",\n inputSchema: z.object({\n query: z.string().min(1).describe(\"The query string to search for relevant documents.\"),\n topK: z.number().int().positive().optional().describe(\"The maximum number of results.\"),\n }),\n outputSchema: 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 }, context) => {\n const request = {\n query,\n topK: topK ?? configuredTopK,\n minScore: options.minScore,\n filter: options.filter,\n retries: options.retries,\n abortSignal: context.abortSignal,\n };\n return \"models\" in options && options.models !== undefined\n ? retrieveDocuments({\n ...request,\n store: options.store,\n models: options.models,\n fusion: options.fusion,\n })\n : retrieveDocuments({ ...request, store: options.store, model: options.model });\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 assertFiniteVector(embedding.vector, id);\n if (expectedDimension === undefined) return embedding.vector.length;\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\nfunction assertFiniteVector(vector: number[], id: string): void {\n if (vector.length === 0) throw new TypeError(`Vector for ${id} must not be empty.`);\n if (!vector.every(Number.isFinite)) {\n throw new TypeError(`Vector for ${id} must contain only finite numbers.`);\n }\n}\n","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 assertFiniteMinScore(\n value: number | undefined,\n name = \"minScore\",\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 { ToolApprovalRequirement } from \"../../tool/tool\";\n\nexport function toolMayRequireApproval(requirement: unknown): boolean {\n return requirement !== undefined && requirement !== false;\n}\n\nexport function assertToolApprovalRequirement(\n requirement: unknown,\n options: { allowFunction: boolean },\n): asserts requirement is boolean | ToolApprovalRequirement | ((...args: never[]) => unknown) {\n if (typeof requirement === \"boolean\") {\n return;\n }\n if (options.allowFunction && typeof requirement === \"function\") {\n return;\n }\n if (typeof requirement !== \"object\" || requirement === null || Array.isArray(requirement)) {\n throw new TypeError(\n 'Tool \"requiresApproval\" must be a boolean, a function, or an object with an optional string reason.',\n );\n }\n const reason = (requirement as { reason?: unknown }).reason;\n if (reason !== undefined && typeof reason !== \"string\") {\n throw new TypeError('Tool \"requiresApproval.reason\" must be a string.');\n }\n}\n","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 { isJsonValue } from \"../completion/json\";\nimport { parseMessage } from \"../completion/message-schema\";\nimport type {\n JsonObject,\n JsonValue,\n ToolDefinition,\n ToolResultContentPart,\n ToolResultOutput,\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 callId?: string;\n internalCallId: string;\n run: ToolApprovalRunContext;\n};\n\nexport type ToolApprovalRequirement = {\n reason?: string | undefined;\n};\n\nexport type ToolRequiresApproval<Args = unknown> =\n | boolean\n | ToolApprovalRequirement\n | ((\n args: Args,\n context: ToolApprovalContext<Args>,\n ) => boolean | ToolApprovalRequirement | Promise<boolean | ToolApprovalRequirement>);\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 abortSignal?: AbortSignal | undefined;\n};\n\nexport interface Tool<Args = unknown, Output = unknown> {\n readonly name: string;\n readonly requiresApproval?: ToolRequiresApproval<Args>;\n definition(prompt: string): ToolDefinition | Promise<ToolDefinition>;\n call(args: Args, context?: ToolCallContext): Output | Promise<Output>;\n parseInput?(args: JsonValue): Args;\n}\n\nexport type AnyTool = Omit<Tool<unknown, unknown>, \"requiresApproval\"> & {\n readonly requiresApproval?: unknown;\n};\n\nconst richToolOutput = Symbol(\"anvia.tool-output.content\");\n\nexport type RichToolOutput = Readonly<{\n [richToolOutput]: true;\n content: readonly ToolResultContentPart[];\n}>;\n\nexport type NormalizedToolOutput = ToolResultOutput;\n\nexport class ToolResultSerializationError extends TypeError {\n constructor(readonly output: unknown) {\n super(\"Tool output must be a string, a strict JSON value, or ToolOutput.content(...).\");\n this.name = \"ToolResultSerializationError\";\n }\n}\n\nexport const ToolOutput = {\n content(content: readonly ToolResultContentPart[]): RichToolOutput {\n return { [richToolOutput]: true, content };\n },\n};\n\nexport function normalizeToolResultOutput(output: unknown): NormalizedToolOutput {\n if (typeof output === \"string\") {\n return { type: \"text\", value: output };\n }\n if (isRichToolOutput(output)) {\n try {\n const message = parseMessage({\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: \"validation\",\n toolName: \"validation\",\n output: { type: \"content\", value: output.content },\n },\n ],\n });\n if (message.role !== \"tool\") throw new TypeError(\"Unexpected message role\");\n const result = message.content[0];\n if (result?.type !== \"tool-result\") throw new TypeError(\"Unexpected tool result part\");\n if (result?.output.type !== \"content\") throw new TypeError(\"Unexpected tool output\");\n return result.output;\n } catch {\n throw new ToolResultSerializationError(output);\n }\n }\n if (isJsonValue(output)) {\n return { type: \"json\", value: output };\n }\n throw new ToolResultSerializationError(output);\n}\n\nexport function toolResultContentToText(content: readonly ToolResultContentPart[]): string {\n return content\n .map((item) => (item.type === \"text\" ? item.text : `[file:${item.mediaType}]`))\n .join(\"\\n\");\n}\n\nfunction isRichToolOutput(value: unknown): value is RichToolOutput {\n return typeof value === \"object\" && value !== null && richToolOutput in value;\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 { ToolCallError, ToolJsonError } from \"../../tool/errors\";\nimport {\n type AnyTool,\n type NormalizedToolOutput,\n normalizeToolResultOutput,\n parseToolArgs,\n type ToolCallContext,\n} from \"../../tool/tool\";\n\nconst preparedToolInputSymbol = Symbol(\"preparedToolInput\");\nconst preparedToolOwnerSymbol = Symbol(\"preparedToolOwner\");\n\nexport type PreparedToolCall = {\n input: unknown;\n call(context: ToolCallContext): Promise<NormalizedToolOutput>;\n};\n\ntype PreparedToolCallContext = ToolCallContext & {\n [preparedToolInputSymbol]?: { owner: object; input: unknown };\n};\n\ntype ToolWithPreparedOwner = AnyTool & {\n [preparedToolOwnerSymbol]?: object;\n};\n\nexport function attachPreparedToolOwner<T extends AnyTool>(tool: T, owner: object): T {\n Object.defineProperty(tool, preparedToolOwnerSymbol, {\n configurable: false,\n enumerable: true,\n value: owner,\n writable: false,\n });\n return tool;\n}\n\nexport function preparedToolInput(\n context: ToolCallContext | undefined,\n owner: object,\n): { input: unknown } | undefined {\n if (context === undefined || !(preparedToolInputSymbol in context)) {\n return undefined;\n }\n const prepared = (context as PreparedToolCallContext)[preparedToolInputSymbol];\n return prepared?.owner === owner ? { input: prepared.input } : undefined;\n}\n\nexport function withoutPreparedToolInput(context: ToolCallContext): ToolCallContext {\n if (!(preparedToolInputSymbol in context)) {\n return context;\n }\n const { [preparedToolInputSymbol]: _prepared, ...publicContext } =\n context as PreparedToolCallContext;\n return publicContext;\n}\n\nexport function prepareToolCall(tool: AnyTool, args: string): PreparedToolCall {\n let rawInput: ReturnType<typeof parseToolArgs>;\n try {\n rawInput = parseToolArgs(args);\n } catch (error) {\n throw new ToolJsonError(`Invalid JSON arguments for tool ${tool.name}`, error);\n }\n\n let input: unknown;\n try {\n input = tool.parseInput === undefined ? rawInput : tool.parseInput(rawInput);\n } catch (error) {\n throw asToolCallError(tool.name, error);\n }\n\n return prepareToolCallFromInput(tool, input);\n}\n\nexport function prepareToolCallFromInput(tool: AnyTool, input: unknown): PreparedToolCall {\n return {\n input,\n async call(context) {\n try {\n const owner = (tool as ToolWithPreparedOwner)[preparedToolOwnerSymbol];\n return normalizeToolResultOutput(\n await tool.call(\n input,\n owner === undefined ? context : withPreparedToolInput(context, owner, input),\n ),\n );\n } catch (error) {\n throw asToolCallError(tool.name, error);\n }\n },\n };\n}\n\nfunction withPreparedToolInput(\n context: ToolCallContext,\n owner: object,\n input: unknown,\n): ToolCallContext {\n const preparedContext: PreparedToolCallContext = { ...context };\n Object.defineProperty(preparedContext, preparedToolInputSymbol, {\n configurable: false,\n enumerable: true,\n value: { owner, input },\n writable: false,\n });\n return preparedContext;\n}\n\nfunction asToolCallError(toolName: string, error: unknown): ToolCallError {\n if (error instanceof ToolCallError) {\n return error;\n }\n return error instanceof Error\n ? new ToolCallError(error.message, error)\n : new ToolCallError(`Tool ${toolName} failed`, error);\n}\n","import type { z } from \"zod\";\nimport { assertToolApprovalRequirement } from \"../internal/agent-runtime/approval-requirement\";\nimport {\n attachPreparedToolOwner,\n preparedToolInput,\n withoutPreparedToolInput,\n} from \"../internal/agent-runtime/prepared-tool-call\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { Tool, ToolCallContext, ToolRequiresApproval } 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 inputSchema: InputSchema;\n outputSchema?: OutputSchema;\n requiresApproval?: ToolRequiresApproval<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> & { outputSchema?: 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 { name, description, inputSchema, outputSchema, execute } = options;\n const requiresApproval = snapshotApprovalRequirement(options.requiresApproval);\n if (requiresApproval !== undefined) {\n assertToolApprovalRequirement(requiresApproval, { allowFunction: true });\n }\n const parameters = toProviderJsonSchema(inputSchema);\n const preparedInputOwner = {};\n const definition = () => ({\n name,\n description,\n parameters: globalThis.structuredClone(parameters),\n });\n const call = async (\n args: z.output<InputSchema>,\n context: ToolCallContext = {},\n ): Promise<CreateToolOutput<OutputSchema, Output>> => {\n const prepared = preparedToolInput(context, preparedInputOwner);\n const parsedArgs =\n prepared === undefined ? inputSchema.parse(args) : (prepared.input as z.output<InputSchema>);\n const executionContext = prepared === undefined ? context : withoutPreparedToolInput(context);\n const result = await execute(parsedArgs, executionContext);\n return (outputSchema === undefined ? result : outputSchema.parse(result)) as CreateToolOutput<\n OutputSchema,\n Output\n >;\n };\n const parseInput = (args: unknown): z.output<InputSchema> => inputSchema.parse(args);\n\n const tool: Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> = {\n name,\n definition,\n call,\n parseInput,\n };\n if (requiresApproval !== undefined) {\n Object.defineProperty(tool, \"requiresApproval\", {\n configurable: false,\n enumerable: true,\n value: requiresApproval,\n writable: false,\n });\n }\n return attachPreparedToolOwner(tool, preparedInputOwner);\n}\n\nfunction snapshotApprovalRequirement<Args>(\n requirement: ToolRequiresApproval<Args> | undefined,\n): ToolRequiresApproval<Args> | undefined {\n return typeof requirement === \"object\" && requirement !== null\n ? Object.freeze({ ...requirement })\n : requirement;\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","import { embedSparseQuery, embedText, type VectorMetadata } from \"../embeddings\";\nimport { throwIfAborted } from \"../internal/abort\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { type ResolvedRetryOptions, resolveRetryOptions, runWithRetries } from \"../retry\";\nimport type {\n RetrieveDocumentsOptions,\n RetrieveHybridDocumentsOptions,\n VectorSearchResult,\n} from \"./types\";\n\nexport function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>>;\nexport function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveHybridDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>>;\nexport async function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveDocumentsOptions<T, Metadata> | RetrieveHybridDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>> {\n assertPositiveSearchLimit(options.topK);\n assertFiniteMinScore(options.minScore);\n throwIfAborted(options.abortSignal);\n const retries = resolveRetries(options.retries);\n const search = (operation: () => Promise<Array<VectorSearchResult<T, Metadata>>>) =>\n runWithRetries(operation, retries, {\n streaming: false,\n abortSignal: options.abortSignal,\n });\n\n if (\"model\" in options && options.model !== undefined) {\n const { embedding } = await embedText({\n model: options.model,\n text: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n });\n return deduplicateResults(\n await search(() =>\n options.store.search({\n vector: embedding.vector,\n topK: options.topK,\n minScore: options.minScore,\n filter: options.filter,\n abortSignal: options.abortSignal,\n }),\n ),\n );\n }\n\n const [{ embedding: dense }, { embedding: sparse }] = await Promise.all([\n embedText({\n model: options.models.dense,\n text: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n }),\n embedSparseQuery({\n model: options.models.sparse,\n query: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n }),\n ]);\n return deduplicateResults(\n await search(() =>\n options.store.searchHybrid({\n vector: dense.vector,\n sparseVector: sparse.vector,\n fusion: options.fusion,\n topK: options.topK,\n minScore: options.minScore,\n filter: options.filter,\n abortSignal: options.abortSignal,\n }),\n ),\n );\n}\n\nfunction deduplicateResults<T, Metadata extends VectorMetadata>(\n results: Array<VectorSearchResult<T, Metadata>>,\n): Array<VectorSearchResult<T, Metadata>> {\n const bestById = new Map<string, VectorSearchResult<T, Metadata>>();\n for (const result of results) {\n const current = bestById.get(result.id);\n if (current === undefined || result.score > current.score) bestById.set(result.id, result);\n }\n return [...bestById.values()].sort((left, right) => right.score - left.score);\n}\n\nfunction resolveRetries(\n setting: RetrieveDocumentsOptions<unknown>[\"retries\"],\n): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(set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AAO,OAAO,QAAQ,MAAM,CAAC;AAAA,IAClF;AAAA,EACF,CAAC;AACH;AAEA,SAAS,UAAU,gBAA2B,YAA6C;AACzF,MAAI;AACJ,aAAW,aAAa,YAAY;AAClC,UAAM,QAAQ,iBAAiB,eAAe,QAAQ,UAAU,MAAM;AACtE,WAAO,SAAS,SAAY,QAAQ,KAAK,IAAI,MAAM,KAAK;AAAA,EAC1D;AACA,SAAO;AACT;AAEA,SAAS,2BACP,mBACA,WACA,IACQ;AACR,qBAAmB,UAAU,QAAQ,EAAE;AACvC,MAAI,sBAAsB,OAAW,QAAO,UAAU,OAAO;AAC7D,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;AAEA,SAAS,mBAAmB,QAAkB,IAAkB;AAC9D,MAAI,OAAO,WAAW,EAAG,OAAM,IAAI,UAAU,cAAc,EAAE,qBAAqB;AAClF,MAAI,CAAC,OAAO,MAAM,OAAO,QAAQ,GAAG;AAClC,UAAM,IAAI,UAAU,cAAc,EAAE,oCAAoC;AAAA,EAC1E;AACF;","names":["throwIfAborted"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// src/internal/concurrency.ts
|
|
2
|
+
async function mapWithConcurrency(inputs, concurrency, mapper) {
|
|
3
|
+
if (!Number.isSafeInteger(concurrency) || concurrency <= 0) {
|
|
4
|
+
throw new RangeError("concurrency must be a positive safe integer.");
|
|
5
|
+
}
|
|
6
|
+
const limit = concurrency;
|
|
7
|
+
const results = new Array(inputs.length);
|
|
8
|
+
let nextIndex = 0;
|
|
9
|
+
let firstFailure;
|
|
10
|
+
async function worker() {
|
|
11
|
+
while (firstFailure === void 0 && nextIndex < inputs.length) {
|
|
12
|
+
const index = nextIndex;
|
|
13
|
+
nextIndex += 1;
|
|
14
|
+
try {
|
|
15
|
+
results[index] = await mapper(inputs[index]);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
firstFailure ??= { error };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
await Promise.all(Array.from({ length: Math.min(limit, inputs.length) }, () => worker()));
|
|
22
|
+
if (firstFailure !== void 0) {
|
|
23
|
+
throw firstFailure.error;
|
|
24
|
+
}
|
|
25
|
+
return results;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
mapWithConcurrency
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=chunk-3RM57ZT2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/concurrency.ts"],"sourcesContent":["export async function mapWithConcurrency<Input, Output>(\n inputs: readonly 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"],"mappings":";AAAA,eAAsB,mBACpB,QACA,aACA,QACmB;AACnB,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,GAAG;AAC1D,UAAM,IAAI,WAAW,8CAA8C;AAAA,EACrE;AACA,QAAM,QAAQ;AACd,QAAM,UAAU,IAAI,MAAc,OAAO,MAAM;AAC/C,MAAI,YAAY;AAChB,MAAI;AAEJ,iBAAe,SAAwB;AACrC,WAAO,iBAAiB,UAAa,YAAY,OAAO,QAAQ;AAC9D,YAAM,QAAQ;AACd,mBAAa;AACb,UAAI;AACF,gBAAQ,KAAK,IAAI,MAAM,OAAO,OAAO,KAAK,CAAU;AAAA,MACtD,SAAS,OAAO;AACd,yBAAiB,EAAE,MAAM;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AAEA,QAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,OAAO,OAAO,MAAM,EAAE,GAAG,MAAM,OAAO,CAAC,CAAC;AACxF,MAAI,iBAAiB,QAAW;AAC9B,UAAM,aAAa;AAAA,EACrB;AACA,SAAO;AACT;","names":[]}
|