@anvia/core 1.0.7 → 1.0.9

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.
Files changed (62) hide show
  1. package/README.md +168 -3
  2. package/dist/agent/index.d.ts +12 -12
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/interactions/index.d.ts +1 -1
  5. package/dist/{agent-B-3jCRmI.d.ts → agent-DTmzs1Qr.d.ts} +16 -13
  6. package/dist/chunk-4UQALF5Y.js +117 -0
  7. package/dist/chunk-4UQALF5Y.js.map +1 -0
  8. package/dist/{chunk-HNRNTFMQ.js → chunk-GAOZ263Y.js} +15 -4
  9. package/dist/chunk-GAOZ263Y.js.map +1 -0
  10. package/dist/{chunk-XMVOBX43.js → chunk-JLJMVRRE.js} +2 -2
  11. package/dist/{chunk-DHJL44R2.js → chunk-JTJU56ZV.js} +2 -2
  12. package/dist/{chunk-TB5EKZM7.js → chunk-OI3LSMJG.js} +30 -1
  13. package/dist/chunk-OI3LSMJG.js.map +1 -0
  14. package/dist/{chunk-34EDX4ZL.js → chunk-Q5BCNYED.js} +2 -2
  15. package/dist/completion/index.d.ts +3 -3
  16. package/dist/completion/index.js +10 -2
  17. package/dist/{dynamic-tools-aIZlg5x1.d.ts → dynamic-tools-CNHSPXr1.d.ts} +3 -3
  18. package/dist/evals/index.d.ts +195 -49
  19. package/dist/evals/index.js +617 -126
  20. package/dist/evals/index.js.map +1 -1
  21. package/dist/extractor/index.d.ts +1 -1
  22. package/dist/extractor/index.js +3 -3
  23. package/dist/guardrails/index.d.ts +4 -4
  24. package/dist/image-generation/index.d.ts +1 -1
  25. package/dist/index.d.ts +14 -14
  26. package/dist/index.js +10 -5
  27. package/dist/internal/agent.d.ts +11 -11
  28. package/dist/internal/agent.js +6 -5
  29. package/dist/internal/agent.js.map +1 -1
  30. package/dist/mcp/index.d.ts +4 -4
  31. package/dist/memory/index.d.ts +3 -3
  32. package/dist/memory/index.js +2 -2
  33. package/dist/{middleware-kcF8AusP.d.ts → middleware-mY_lpjDp.d.ts} +1 -1
  34. package/dist/observability/index.d.ts +6 -6
  35. package/dist/observability/index.js +3 -3
  36. package/dist/pipeline/index.d.ts +12 -12
  37. package/dist/pipeline/index.js +3 -3
  38. package/dist/pipeline/index.js.map +1 -1
  39. package/dist/{provider-output-error-BEwDgVv3.d.ts → provider-output-error-OQ4fjw5W.d.ts} +10 -2
  40. package/dist/skills/index.d.ts +4 -4
  41. package/dist/speech-generation/index.d.ts +1 -1
  42. package/dist/{text-ZLECpQE7.d.ts → text-CmjXxakS.d.ts} +1 -1
  43. package/dist/{think-tool-BwCsJ365.d.ts → think-tool-YWsV98I5.d.ts} +1 -1
  44. package/dist/tool/index.d.ts +6 -6
  45. package/dist/{tool-BpqpoRSE.d.ts → tool-DQMZpZSS.d.ts} +1 -1
  46. package/dist/transcription/index.d.ts +1 -1
  47. package/dist/{types-DC1U1XwW.d.ts → types-C1xYKXF2.d.ts} +1 -1
  48. package/dist/{types-CXNE592e.d.ts → types-CODGMHnp.d.ts} +1 -1
  49. package/dist/{types-DL7wX6hJ.d.ts → types-CRda8x7p.d.ts} +8 -7
  50. package/dist/{types-DmzRCbU5.d.ts → types-CafU6Ux5.d.ts} +1 -1
  51. package/dist/{types-DgvozfPc.d.ts → types-CiHjqE6J.d.ts} +19 -3
  52. package/dist/{types-DjqRHeAi.d.ts → types-DfRPfehE.d.ts} +2 -2
  53. package/dist/{types-DhkodEft.d.ts → types-h0EL6Xn0.d.ts} +1 -1
  54. package/dist/vector-store/index.d.ts +4 -4
  55. package/package.json +1 -1
  56. package/dist/chunk-D4PACGPA.js +0 -37
  57. package/dist/chunk-D4PACGPA.js.map +0 -1
  58. package/dist/chunk-HNRNTFMQ.js.map +0 -1
  59. package/dist/chunk-TB5EKZM7.js.map +0 -1
  60. /package/dist/{chunk-XMVOBX43.js.map → chunk-JLJMVRRE.js.map} +0 -0
  61. /package/dist/{chunk-DHJL44R2.js.map → chunk-JTJU56ZV.js.map} +0 -0
  62. /package/dist/{chunk-34EDX4ZL.js.map → chunk-Q5BCNYED.js.map} +0 -0
package/README.md CHANGED
@@ -202,14 +202,27 @@ const result = await generateCompletion({
202
202
  prompt: "Summarize this incident.",
203
203
  retries: { maxAttempts: 3, initialDelayMs: 100, maxDelayMs: 1_000 },
204
204
  abortSignal: controller.signal,
205
- providerOptions: { reasoning: { effort: "medium" } },
205
+ controls: { reasoningEffort: "medium" },
206
206
  });
207
207
  ```
208
208
 
209
- `providerOptions` contains a strict JSON object passed to an adapter. Runtime values such as
209
+ Completion models can advertise typed, provider-neutral `controls`. Reasoning-capable adapters use
210
+ the `reasoningEffort` select control, so supported values are inferred from the model returned by
211
+ `completionModel()`. An Agent can set control defaults, and a generate or stream call can override
212
+ them for that run:
213
+
214
+ ```ts
215
+ const agent = new Agent({ model, controls: { reasoningEffort: "medium" } });
216
+ await agent.generate({ prompt: "Solve this.", controls: { reasoningEffort: "high" } });
217
+ ```
218
+
219
+ Omitting a control means “Default”: the Agent default applies when configured, otherwise the
220
+ provider chooses. Invalid control names and values are rejected before the provider call.
221
+
222
+ `providerOptions` remains the escape hatch for a strict JSON object passed to an adapter. Runtime values such as
210
223
  `undefined`, non-finite numbers, cycles, a top-level array, and class instances are rejected rather
211
224
  than coerced. Nested arrays are valid JSON. Canonical Anvia fields such as model, input,
212
- temperature, tools, dimensions, text, and voice take precedence over conflicting provider keys.
225
+ temperature, tools, controls, dimensions, text, and voice take precedence over conflicting provider keys.
213
226
  Cancellation is forwarded to provider SDK calls and is never retried.
214
227
 
215
228
  ## Agents
@@ -649,6 +662,158 @@ Import `McpClient` and `McpClientGroup` from `@anvia/mcp`, connect them, and pas
649
662
  `servers` to `new Agent({ mcpServers })`. See the `@anvia/mcp` README for transport configuration,
650
663
  connection ownership, URL safety, and cleanup.
651
664
 
665
+ ## Evaluations
666
+
667
+ Import evaluation APIs from `@anvia/core/evals`. A suite contains cases, a target, and one or more
668
+ metrics. Required metric failures make a case fail; infrastructure or evaluation errors produce an
669
+ `invalid` outcome.
670
+
671
+ ```ts
672
+ import { contains, exactMatch, runEvalSuite } from "@anvia/core/evals";
673
+
674
+ const result = await runEvalSuite({
675
+ name: "support answers",
676
+ cases: [
677
+ {
678
+ id: "refund-window",
679
+ input: "When can I request a refund?",
680
+ expected: "Refunds are available for 30 days.",
681
+ },
682
+ ],
683
+ target: async (input) => answerSupportQuestion(input),
684
+ metrics: [exactMatch(), contains({ expected: "30 days" })],
685
+ });
686
+
687
+ console.log(result.cases);
688
+ console.log(result.results[0]?.scores.exact_match);
689
+ ```
690
+
691
+ `runEvalSuite` infers the case input, target output, expected value, metric names, and score types.
692
+ Metrics that implicitly read `case.expected`, `case.context`, or `case.retrievalContext` require
693
+ those fields at compile time. Supplying an explicit metric value or selector removes the matching
694
+ case requirement.
695
+
696
+ ### Built-in metrics
697
+
698
+ Deterministic metrics do not call a model:
699
+
700
+ - `exactMatch`, `contains`, `notContains`, `containsAll`, and `containsAny`
701
+ - `matches`, `doesNotMatch`, `maxLength`, and `requiredFields`
702
+ - `semanticSimilarity`, which uses an embedding model
703
+
704
+ Judge metrics call a completion model and record their evaluation token usage:
705
+
706
+ - `llmJudge` and `llmScore`
707
+ - `answerRelevancy`, `promptAlignment`, `jsonCorrectness`, and `summarization`
708
+ - `hallucination`, `faithfulness`, and `abstention`
709
+ - `gEval`, `turnRelevancy`, and `knowledgeRetention`
710
+
711
+ Numeric thresholds use values from `0` through `1`. `strictMode` requires a perfect higher-is-better
712
+ score or a zero lower-is-better score. Judge metrics default to including a final explanation;
713
+ setting `includeReason: false` saves that extra judge call when the explanation is unnecessary.
714
+
715
+ ### Typed custom metrics
716
+
717
+ Use `createEvalTypes` to bind input, output, and expected types once when defining multiple custom
718
+ metrics:
719
+
720
+ ```ts
721
+ import { createEvalTypes, EvalOutcome } from "@anvia/core/evals";
722
+
723
+ const supportEvals = createEvalTypes<string, { answer: string }, string>();
724
+
725
+ const noHandoff = supportEvals.defineMetric({
726
+ name: "no_handoff",
727
+ dataType: "BOOLEAN",
728
+ evaluate: ({ output, signal }) =>
729
+ signal.aborted || output.answer.includes("contact support")
730
+ ? EvalOutcome.fail(false)
731
+ : EvalOutcome.pass(true),
732
+ });
733
+ ```
734
+
735
+ Custom metrics return `EvalOutcome.pass`, `EvalOutcome.fail`, or `EvalOutcome.invalid`. Thrown metric
736
+ errors are converted to structured invalid outcomes containing the error kind and original error.
737
+
738
+ ### Execution controls
739
+
740
+ Evaluation targets receive an optional third argument containing the case `AbortSignal`.
741
+
742
+ ```ts
743
+ const result = await runEvalSuite({
744
+ // cases, target, and metrics...
745
+ name: "release gate",
746
+ cases,
747
+ target: async (input, testCase, context) =>
748
+ generateAnswer(input, { signal: context?.signal, metadata: testCase.metadata }),
749
+ metrics,
750
+ targetConcurrency: 4,
751
+ metricConcurrency: 2,
752
+ caseTimeoutMs: 30_000,
753
+ signal: deploymentSignal,
754
+ failFast: true,
755
+ caseIds: ["refund-window", "billing-owner"],
756
+ shard: { index: 0, count: 4 },
757
+ onProgress(event) {
758
+ console.log(event.type);
759
+ },
760
+ });
761
+ ```
762
+
763
+ - `concurrency` remains the shorthand for both target and metric concurrency.
764
+ - `targetConcurrency` and `metricConcurrency` can limit them independently.
765
+ - `caseTimeoutMs` covers the target and its metrics. Cooperative targets and metrics should observe
766
+ the supplied signal; the runner still stops awaiting work that ignores it.
767
+ - Aborting the suite-level `signal` stops scheduling cases and rejects the run with the abort reason.
768
+ - `caseIds`, `caseFilter`, and `shard` select cases before execution.
769
+ - `failFast` throws `EvalFailFastError` after the first completed required failure or invalid case.
770
+ - `onProgress` receives case, target, metric, and case-completion events.
771
+
772
+ Use `selectEvalCaseIds(previousResult)` to select failed and invalid cases for a rerun.
773
+
774
+ ### Results, usage, and failures
775
+
776
+ Every case result includes `targetStatus`, target and total durations, per-case usage and optional
777
+ cost. Every metric result includes its duration, optional cost, outcome, and reporter errors. A
778
+ successful target that returns `undefined` has `targetStatus: "succeeded"` and retains its `output`
779
+ property, so it is distinct from a failed target.
780
+
781
+ The suite aggregates metric totals, case totals, target and evaluation usage, costs, duration, and
782
+ all reporter errors. Invalid outcomes may include these `kind` values: `target`, `metric`,
783
+ `configuration`, `provider`, or `timeout`.
784
+
785
+ ### CI output and expectations
786
+
787
+ `runEvalCli` prints a result and can set `process.exitCode`. Exit code `1` means a required metric
788
+ failed; `2` means a required metric was invalid. Use `defineEvalExpectations` with a defined suite to
789
+ type-check case and metric names.
790
+
791
+ ```ts
792
+ import { defineEvalExpectations, defineEvalSuite, exactMatch, runEvalCli } from "@anvia/core/evals";
793
+
794
+ const suite = defineEvalSuite({
795
+ name: "release gate",
796
+ cases: [{ id: "refund", input: "refund", expected: "30 days" }],
797
+ target: async () => "30 days",
798
+ metrics: [exactMatch({ name: "correct" })],
799
+ });
800
+
801
+ await runEvalCli({
802
+ ...suite,
803
+ expectations: defineEvalExpectations(suite, {
804
+ outcomes: { refund: { correct: "pass" } },
805
+ }),
806
+ exitCode: true,
807
+ maxValueLength: 2_000,
808
+ redact: (value, context) => (context.kind === "input" ? "[redacted]" : value),
809
+ });
810
+ ```
811
+
812
+ Use `formatEvalResult` for pure pretty or JSON formatting without writing to stdout. Both
813
+ `formatEvalResult` and `runEvalCli` support value truncation and redaction. JSON output otherwise
814
+ contains cases, outputs, metadata, and error details, so redact sensitive data before writing it to
815
+ shared CI logs.
816
+
652
817
  ## Public Areas
653
818
 
654
819
  - `agent`: typed Agent runtime, retries, and stream events
@@ -1,22 +1,22 @@
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-B-3jCRmI.js';
4
- import { M as Message, U as Usage, C as CompletionFinishReason } from '../types-DgvozfPc.js';
5
- import { A as AgentBlockedOutcome, g as AgentInteractionOutcome } from '../types-DL7wX6hJ.js';
6
- export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, h as AgentLifecycle, i as AgentMemoryCompactionEvent, j as AgentMemoryCompactionOptions, k as AgentOutcome, l as AgentPrompt, m as AgentResponse, n as AgentRunOptions, o as AgentRunSettings, p as AgentStartEvent, q as AgentSteerInput, r as AgentSteerReceipt, s as AgentStepFinishEvent, t as AgentStream, u as AgentStreamEvent, v as AgentToolCallDeltaEvent, w as AgentToolFinishEvent, x as AgentToolStartEvent } from '../types-DL7wX6hJ.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-DTmzs1Qr.js';
4
+ import { M as Message, U as Usage, c as CompletionFinishReason } from '../types-CiHjqE6J.js';
5
+ import { A as AgentBlockedOutcome, g as AgentInteractionOutcome } from '../types-CRda8x7p.js';
6
+ export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, h as AgentLifecycle, i as AgentMemoryCompactionEvent, j as AgentMemoryCompactionOptions, k as AgentOutcome, l as AgentPrompt, m as AgentResponse, n as AgentRunOptions, o as AgentRunSettings, p as AgentStartEvent, q as AgentSteerInput, r as AgentSteerReceipt, s as AgentStepFinishEvent, t as AgentStream, u as AgentStreamEvent, v as AgentToolCallDeltaEvent, w as AgentToolFinishEvent, x as AgentToolStartEvent } from '../types-CRda8x7p.js';
7
7
  import '../zod-schema-C7F4clpm.js';
8
8
  import 'zod';
9
- import '../types-DhkodEft.js';
9
+ import '../types-h0EL6Xn0.js';
10
10
  import '../type-utils-CtHVDRn_.js';
11
- import '../types-DjqRHeAi.js';
12
- import '../tool-BpqpoRSE.js';
13
- import '../types-DmzRCbU5.js';
14
- import '../middleware-kcF8AusP.js';
11
+ import '../types-DfRPfehE.js';
12
+ import '../tool-DQMZpZSS.js';
13
+ import '../types-CafU6Ux5.js';
14
+ import '../middleware-mY_lpjDp.js';
15
15
  import './interactions/index.js';
16
- import '../types-DC1U1XwW.js';
17
- import '../dynamic-tools-aIZlg5x1.js';
16
+ import '../types-C1xYKXF2.js';
17
+ import '../dynamic-tools-CNHSPXr1.js';
18
18
  import '../types-Cr4uiYo5.js';
19
- import '../types-CXNE592e.js';
19
+ import '../types-CODGMHnp.js';
20
20
 
21
21
  type AgentStructuredOutputPhase = "truncated" | "content-filter" | "parse" | "schema";
22
22
  type AgentStructuredOutputFormat = "raw" | "json-fence" | "unlabeled-fence";
@@ -2,11 +2,11 @@ import {
2
2
  Agent,
3
3
  createVectorContext,
4
4
  isVectorContext
5
- } from "../chunk-HNRNTFMQ.js";
5
+ } from "../chunk-GAOZ263Y.js";
6
6
  import "../chunk-OJBFDBLG.js";
7
7
  import "../chunk-J6LVLV6P.js";
8
- import "../chunk-XMVOBX43.js";
9
- import "../chunk-34EDX4ZL.js";
8
+ import "../chunk-JLJMVRRE.js";
9
+ import "../chunk-Q5BCNYED.js";
10
10
  import "../chunk-KSKST3KP.js";
11
11
  import "../chunk-YK4WAAS4.js";
12
12
  import "../chunk-2QZJTG2E.js";
@@ -22,8 +22,8 @@ import {
22
22
  } from "../chunk-AHLKV6KP.js";
23
23
  import "../chunk-K5L7R7XM.js";
24
24
  import "../chunk-IZNOP6JG.js";
25
- import "../chunk-D4PACGPA.js";
26
- import "../chunk-TB5EKZM7.js";
25
+ import "../chunk-4UQALF5Y.js";
26
+ import "../chunk-OI3LSMJG.js";
27
27
  import "../chunk-7JLAIN6E.js";
28
28
  import "../chunk-QGX73TSQ.js";
29
29
  import "../chunk-3XQGVDU5.js";
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { p as JsonValue, J as JsonObject, $ as ToolQuestionAnswer } from '../../types-DgvozfPc.js';
2
+ import { t as JsonValue, J as JsonObject, a4 as ToolQuestionAnswer } from '../../types-CiHjqE6J.js';
3
3
  import '../../model-call-options-CZkSw_xN.js';
4
4
 
5
5
  type AgentQuestionChoice = Readonly<{
@@ -1,17 +1,17 @@
1
1
  import { b as RetrySetting } from './retry-CjvSlKGW.js';
2
- import { D as Document, c as CompletionModel, P as ProviderTool, J as JsonObject, v as ToolChoice } from './types-DgvozfPc.js';
2
+ import { D as Document, d as CompletionModel, P as ProviderTool, J as JsonObject, C as CompletionControlValues, f as CompletionModelControlsOf, z as ToolChoice } from './types-CiHjqE6J.js';
3
3
  import { Z as ZodSchema } from './zod-schema-C7F4clpm.js';
4
- import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-DhkodEft.js';
5
- import { a as McpServer } from './types-DjqRHeAi.js';
6
- import { E as MemoryStore, z as MemorySavePolicy, F as MemoryTokenCounter, n as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, y as MemoryOptions, k as MemoryCompactionResult } from './types-DmzRCbU5.js';
7
- import { h as AgentLifecycle, F as AgentObservabilityOptions, n as AgentRunOptions, k as AgentOutcome, o as AgentRunSettings, t as AgentStream, j as AgentMemoryCompactionOptions } from './types-DL7wX6hJ.js';
8
- import { A as AgentMiddleware } from './middleware-kcF8AusP.js';
9
- import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-BpqpoRSE.js';
4
+ import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-h0EL6Xn0.js';
5
+ import { a as McpServer } from './types-DfRPfehE.js';
6
+ import { E as MemoryStore, z as MemorySavePolicy, F as MemoryTokenCounter, n as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, y as MemoryOptions, k as MemoryCompactionResult } from './types-CafU6Ux5.js';
7
+ import { h as AgentLifecycle, F as AgentObservabilityOptions, n as AgentRunOptions, k as AgentOutcome, o as AgentRunSettings, t as AgentStream, j as AgentMemoryCompactionOptions } from './types-CRda8x7p.js';
8
+ import { A as AgentMiddleware } from './middleware-mY_lpjDp.js';
9
+ import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-DQMZpZSS.js';
10
10
  import { AgentContinuation, AgentInteractionResponse } from './agent/interactions/index.js';
11
- import { a as SkillSet } from './types-DC1U1XwW.js';
12
- import { T as ToolIndex } from './dynamic-tools-aIZlg5x1.js';
11
+ import { a as SkillSet } from './types-C1xYKXF2.js';
12
+ import { T as ToolIndex } from './dynamic-tools-CNHSPXr1.js';
13
13
  import { E as EmbeddingModel, c as SparseEmbeddingModel } from './types-Cr4uiYo5.js';
14
- import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-CXNE592e.js';
14
+ import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-CODGMHnp.js';
15
15
 
16
16
  type VectorContextBaseOptions<T = unknown> = {
17
17
  topK: number;
@@ -57,6 +57,7 @@ type AgentOptions<Output = string, M extends CompletionModel = CompletionModel,
57
57
  temperature?: number | undefined;
58
58
  maxTokens?: number | undefined;
59
59
  providerOptions?: JsonObject | undefined;
60
+ controls?: CompletionControlValues<CompletionModelControlsOf<M>> | undefined;
60
61
  retries?: RetrySetting | undefined;
61
62
  toolChoice?: ToolChoice | undefined;
62
63
  maxTurns?: number | undefined;
@@ -95,6 +96,7 @@ type ResolvedAgentOptions<Output = string, M extends CompletionModel = Completio
95
96
  temperature?: number | undefined;
96
97
  maxTokens?: number | undefined;
97
98
  providerOptions?: JsonObject | undefined;
99
+ controls?: CompletionControlValues<CompletionModelControlsOf<M>> | undefined;
98
100
  retries?: RetrySetting | undefined;
99
101
  tools?: readonly AnyTool[] | undefined;
100
102
  mcpServers?: readonly McpServer[] | undefined;
@@ -128,6 +130,7 @@ declare class Agent<Output = string, M extends CompletionModel = CompletionModel
128
130
  readonly temperature: number | undefined;
129
131
  readonly maxTokens: number | undefined;
130
132
  readonly providerOptions: JsonObject | undefined;
133
+ readonly controls: CompletionControlValues<CompletionModelControlsOf<M>> | undefined;
131
134
  readonly retries: RetrySetting | undefined;
132
135
  readonly mcpServers: readonly McpServer[];
133
136
  readonly tools: readonly AnyTool[];
@@ -140,9 +143,9 @@ declare class Agent<Output = string, M extends CompletionModel = CompletionModel
140
143
  readonly middlewares: readonly AgentMiddleware[];
141
144
  readonly memory: AgentMemory | undefined;
142
145
  constructor(options: AgentOptions<Output, M, ContextDocument>);
143
- generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentOutcome<Output>>;
144
- resume(continuation: AgentContinuation, response: AgentInteractionResponse, settings?: AgentRunSettings<Output, RawResponseOf<M>>): Promise<AgentOutcome<Output>>;
145
- stream(options: AgentRunOptions<Output, RawResponseOf<M>>): AgentStream<Output, RawResponseOf<M>>;
146
+ generate(options: AgentRunOptions<Output, RawResponseOf<M>, CompletionModelControlsOf<M>>): Promise<AgentOutcome<Output>>;
147
+ resume(continuation: AgentContinuation, response: AgentInteractionResponse, settings?: AgentRunSettings<Output, RawResponseOf<M>, CompletionModelControlsOf<M>>): Promise<AgentOutcome<Output>>;
148
+ stream(options: AgentRunOptions<Output, RawResponseOf<M>, CompletionModelControlsOf<M>>): AgentStream<Output, RawResponseOf<M>>;
146
149
  compactMemory(options: AgentMemoryCompactionOptions): Promise<MemoryCompactionResult>;
147
150
  asTool(options: AgentToolOptions): Tool<{
148
151
  prompt: string;
@@ -0,0 +1,117 @@
1
+ // src/completion/controls.ts
2
+ var REASONING_EFFORT_CONTROL_ID = "reasoningEffort";
3
+ function defineCompletionModelControls(controls) {
4
+ if (typeof controls !== "object" || controls === null || Array.isArray(controls)) {
5
+ throw new TypeError("Completion model controls must be an object.");
6
+ }
7
+ const snapshot = {};
8
+ for (const [id, control] of Object.entries(controls)) {
9
+ if (id.trim().length === 0) {
10
+ throw new TypeError("Completion control ids must not be empty.");
11
+ }
12
+ if (typeof control !== "object" || control === null || Array.isArray(control)) {
13
+ throw new TypeError(`Completion control "${id}" must be an object.`);
14
+ }
15
+ if (control.type !== "select") {
16
+ throw new TypeError(`Completion control "${id}" must have type "select".`);
17
+ }
18
+ if (typeof control.label !== "string" || control.label.trim().length === 0) {
19
+ throw new TypeError(`Completion control "${id}" must have a non-empty label.`);
20
+ }
21
+ if (!Array.isArray(control.options) || control.options.length === 0) {
22
+ throw new TypeError(`Completion control "${id}" must declare at least one option.`);
23
+ }
24
+ const options = control.options.map((option) => {
25
+ if (typeof option !== "string" || option.trim().length === 0) {
26
+ throw new TypeError(`Completion control "${id}" options must not be empty.`);
27
+ }
28
+ return option;
29
+ });
30
+ if (new Set(options).size !== options.length) {
31
+ throw new TypeError(`Completion control "${id}" options must be unique.`);
32
+ }
33
+ if (control.defaultValue !== void 0 && (typeof control.defaultValue !== "string" || !options.includes(control.defaultValue))) {
34
+ throw new TypeError(
35
+ `Completion control "${id}" defaultValue must be one of its declared options.`
36
+ );
37
+ }
38
+ if (control.description !== void 0 && typeof control.description !== "string") {
39
+ throw new TypeError(`Completion control "${id}" description must be a string.`);
40
+ }
41
+ let next = {
42
+ type: "select",
43
+ label: control.label,
44
+ options: Object.freeze(options)
45
+ };
46
+ if (control.description !== void 0) {
47
+ next = { ...next, description: control.description };
48
+ }
49
+ if (control.defaultValue !== void 0) {
50
+ next = { ...next, defaultValue: control.defaultValue };
51
+ }
52
+ Object.defineProperty(snapshot, id, {
53
+ value: Object.freeze(next),
54
+ enumerable: true,
55
+ configurable: false,
56
+ writable: false
57
+ });
58
+ }
59
+ return Object.freeze(snapshot);
60
+ }
61
+ function mergeCompletionControlValues(defaults, overrides) {
62
+ if (defaults === void 0 && overrides === void 0) return void 0;
63
+ const values = {};
64
+ for (const source of [defaults, overrides]) {
65
+ for (const [id, value] of Object.entries(source ?? {})) {
66
+ if (typeof value !== "string") continue;
67
+ Object.defineProperty(values, id, {
68
+ value,
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true
72
+ });
73
+ }
74
+ }
75
+ return Object.keys(values).length === 0 ? void 0 : Object.freeze(values);
76
+ }
77
+
78
+ // src/completion/documents.ts
79
+ function normalizeDocuments(documents) {
80
+ if (documents.length === 0) {
81
+ return void 0;
82
+ }
83
+ return { role: "user", content: documents.map(formatDocument).join("\n") };
84
+ }
85
+ function formatDocument(document) {
86
+ return `<file id: ${document.id}>
87
+ ${formatDocumentBody(document)}
88
+ </file>
89
+ `;
90
+ }
91
+ function formatDocumentBody(document) {
92
+ const metadata = formatMetadata(document.additionalProps);
93
+ return metadata === void 0 ? document.text : `${metadata}
94
+ ${document.text}`;
95
+ }
96
+ function formatMetadata(additionalProps) {
97
+ if (additionalProps === void 0) {
98
+ return void 0;
99
+ }
100
+ const entries = Object.entries(additionalProps).sort(
101
+ ([left], [right]) => left.localeCompare(right)
102
+ );
103
+ if (entries.length === 0) {
104
+ return void 0;
105
+ }
106
+ const metadata = entries.map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(" ");
107
+ return `<metadata ${metadata} />`;
108
+ }
109
+
110
+ export {
111
+ REASONING_EFFORT_CONTROL_ID,
112
+ defineCompletionModelControls,
113
+ mergeCompletionControlValues,
114
+ normalizeDocuments,
115
+ formatDocument
116
+ };
117
+ //# sourceMappingURL=chunk-4UQALF5Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/completion/controls.ts","../src/completion/documents.ts"],"sourcesContent":["import type {\n CompletionControlValues,\n CompletionModelControls,\n CompletionModelSelectControl,\n} from \"./types\";\n\nexport const REASONING_EFFORT_CONTROL_ID = \"reasoningEffort\";\n\nexport type ReasoningEffortControls<Effort extends string = string> = Readonly<{\n reasoningEffort: CompletionModelSelectControl<Effort>;\n}>;\n\nexport function defineCompletionModelControls<const Controls extends CompletionModelControls>(\n controls: Controls,\n): Controls {\n if (typeof controls !== \"object\" || controls === null || Array.isArray(controls)) {\n throw new TypeError(\"Completion model controls must be an object.\");\n }\n const snapshot: Record<string, CompletionModelSelectControl> = {};\n for (const [id, control] of Object.entries(controls)) {\n if (id.trim().length === 0) {\n throw new TypeError(\"Completion control ids must not be empty.\");\n }\n if (typeof control !== \"object\" || control === null || Array.isArray(control)) {\n throw new TypeError(`Completion control \"${id}\" must be an object.`);\n }\n if (control.type !== \"select\") {\n throw new TypeError(`Completion control \"${id}\" must have type \"select\".`);\n }\n if (typeof control.label !== \"string\" || control.label.trim().length === 0) {\n throw new TypeError(`Completion control \"${id}\" must have a non-empty label.`);\n }\n if (!Array.isArray(control.options) || control.options.length === 0) {\n throw new TypeError(`Completion control \"${id}\" must declare at least one option.`);\n }\n const options = control.options.map((option) => {\n if (typeof option !== \"string\" || option.trim().length === 0) {\n throw new TypeError(`Completion control \"${id}\" options must not be empty.`);\n }\n return option;\n });\n if (new Set(options).size !== options.length) {\n throw new TypeError(`Completion control \"${id}\" options must be unique.`);\n }\n if (\n control.defaultValue !== undefined &&\n (typeof control.defaultValue !== \"string\" || !options.includes(control.defaultValue))\n ) {\n throw new TypeError(\n `Completion control \"${id}\" defaultValue must be one of its declared options.`,\n );\n }\n if (control.description !== undefined && typeof control.description !== \"string\") {\n throw new TypeError(`Completion control \"${id}\" description must be a string.`);\n }\n let next: CompletionModelSelectControl = {\n type: \"select\",\n label: control.label,\n options: Object.freeze(options),\n };\n if (control.description !== undefined) {\n next = { ...next, description: control.description };\n }\n if (control.defaultValue !== undefined) {\n next = { ...next, defaultValue: control.defaultValue };\n }\n Object.defineProperty(snapshot, id, {\n value: Object.freeze(next),\n enumerable: true,\n configurable: false,\n writable: false,\n });\n }\n return Object.freeze(snapshot) as Controls;\n}\n\nexport function mergeCompletionControlValues<Controls extends CompletionModelControls>(\n defaults: CompletionControlValues<Controls> | undefined,\n overrides: CompletionControlValues<Controls> | undefined,\n): Readonly<Record<string, string>> | undefined {\n if (defaults === undefined && overrides === undefined) return undefined;\n const values: Record<string, string> = {};\n for (const source of [defaults, overrides]) {\n for (const [id, value] of Object.entries(source ?? {})) {\n if (typeof value !== \"string\") continue;\n Object.defineProperty(values, id, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n return Object.keys(values).length === 0 ? undefined : Object.freeze(values);\n}\n","import type { Document, Message } from \"./types\";\n\nexport function normalizeDocuments(documents: Document[]): Message | undefined {\n if (documents.length === 0) {\n return undefined;\n }\n\n return { role: \"user\", content: documents.map(formatDocument).join(\"\\n\") };\n}\n\nexport function formatDocument(document: Document): string {\n return `<file id: ${document.id}>\\n${formatDocumentBody(document)}\\n</file>\\n`;\n}\n\nfunction formatDocumentBody(document: Document): string {\n const metadata = formatMetadata(document.additionalProps);\n return metadata === undefined ? document.text : `${metadata}\\n${document.text}`;\n}\n\nfunction formatMetadata(additionalProps: Record<string, string> | undefined): string | undefined {\n if (additionalProps === undefined) {\n return undefined;\n }\n\n const entries = Object.entries(additionalProps).sort(([left], [right]) =>\n left.localeCompare(right),\n );\n if (entries.length === 0) {\n return undefined;\n }\n\n const metadata = entries.map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(\" \");\n return `<metadata ${metadata} />`;\n}\n"],"mappings":";AAMO,IAAM,8BAA8B;AAMpC,SAAS,8BACd,UACU;AACV,MAAI,OAAO,aAAa,YAAY,aAAa,QAAQ,MAAM,QAAQ,QAAQ,GAAG;AAChF,UAAM,IAAI,UAAU,8CAA8C;AAAA,EACpE;AACA,QAAM,WAAyD,CAAC;AAChE,aAAW,CAAC,IAAI,OAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACpD,QAAI,GAAG,KAAK,EAAE,WAAW,GAAG;AAC1B,YAAM,IAAI,UAAU,2CAA2C;AAAA,IACjE;AACA,QAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,MAAM,QAAQ,OAAO,GAAG;AAC7E,YAAM,IAAI,UAAU,uBAAuB,EAAE,sBAAsB;AAAA,IACrE;AACA,QAAI,QAAQ,SAAS,UAAU;AAC7B,YAAM,IAAI,U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K;AAAA,EAC1B;AACA,MAAI,QAAQ,WAAW,GAAG;AACxB,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,QAAQ,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,GAAG,KAAK,KAAK,UAAU,KAAK,CAAC,EAAE,EAAE,KAAK,GAAG;AAC3F,SAAO,aAAa,QAAQ;AAC9B;","names":[]}
@@ -13,10 +13,10 @@ import {
13
13
  createMemoryCompactionSummary,
14
14
  cumulativeCompactedMessageCount,
15
15
  resolveMemoryOptions
16
- } from "./chunk-XMVOBX43.js";
16
+ } from "./chunk-JLJMVRRE.js";
17
17
  import {
18
18
  startAgentRunObservers
19
- } from "./chunk-34EDX4ZL.js";
19
+ } from "./chunk-Q5BCNYED.js";
20
20
  import {
21
21
  isSkillTool
22
22
  } from "./chunk-YK4WAAS4.js";
@@ -50,9 +50,13 @@ import {
50
50
  import {
51
51
  mapWithConcurrency
52
52
  } from "./chunk-IZNOP6JG.js";
53
+ import {
54
+ mergeCompletionControlValues
55
+ } from "./chunk-4UQALF5Y.js";
53
56
  import {
54
57
  CompletionStreamAccumulator,
55
58
  Usage,
59
+ assertCompletionControlsSupported,
56
60
  assertCompletionRequestSupported,
57
61
  assertCompletionResponseIntegrity,
58
62
  createCompletionRequest,
@@ -60,7 +64,7 @@ import {
60
64
  isProviderTool,
61
65
  isStreamingCompletionModel,
62
66
  textFromAssistantContent
63
- } from "./chunk-TB5EKZM7.js";
67
+ } from "./chunk-OI3LSMJG.js";
64
68
  import {
65
69
  assertJsonObject
66
70
  } from "./chunk-7JLAIN6E.js";
@@ -1957,6 +1961,7 @@ var AgentRun = class _AgentRun {
1957
1961
  const retrySetting = options.retries === void 0 ? agent.retries : options.retries;
1958
1962
  this.completionRetryOptions = retrySetting === void 0 || retrySetting === false ? void 0 : resolveRetryOptions(retrySetting);
1959
1963
  this.requestMiddlewares = [...options.middlewares ?? []];
1964
+ this.controls = mergeCompletionControlValues(agent.controls, options.controls);
1960
1965
  this.memoryScope = options.memoryScope;
1961
1966
  this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);
1962
1967
  this.continuationState = options.continuationState;
@@ -1984,6 +1989,7 @@ var AgentRun = class _AgentRun {
1984
1989
  traceOptions;
1985
1990
  completionRetryOptions;
1986
1991
  requestMiddlewares;
1992
+ controls;
1987
1993
  steeringMessages = [];
1988
1994
  runState = "idle";
1989
1995
  memoryRecorder;
@@ -2803,6 +2809,7 @@ var AgentRun = class _AgentRun {
2803
2809
  maxTokens: this.agent.maxTokens,
2804
2810
  providerOptions: this.agent.providerOptions,
2805
2811
  toolChoice: this.agent.toolChoice,
2812
+ controls: this.controls,
2806
2813
  outputSchema: getAgentProviderOutputSchema(this.agent)
2807
2814
  });
2808
2815
  return this.runCompletionRequestMiddlewares(request, turn);
@@ -4341,6 +4348,7 @@ function resolveAgentOptions(options) {
4341
4348
  temperature: options.temperature,
4342
4349
  maxTokens: options.maxTokens,
4343
4350
  providerOptions: options.providerOptions,
4351
+ controls: options.controls,
4344
4352
  retries: options.retries,
4345
4353
  tools: [...toolsByName.values()],
4346
4354
  mcpServers: [...options.mcpServers ?? []],
@@ -4681,6 +4689,7 @@ var Agent = class {
4681
4689
  temperature;
4682
4690
  maxTokens;
4683
4691
  providerOptions;
4692
+ controls;
4684
4693
  retries;
4685
4694
  mcpServers;
4686
4695
  tools;
@@ -4706,6 +4715,8 @@ var Agent = class {
4706
4715
  assertJsonObject(resolved.providerOptions, "Agent providerOptions");
4707
4716
  }
4708
4717
  this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
4718
+ assertCompletionControlsSupported(this.model, resolved.controls);
4719
+ this.controls = cloneFrozenPlainData(resolved.controls);
4709
4720
  this.retries = cloneFrozenPlainData(resolved.retries);
4710
4721
  const preparedTools = prepareAgentTools(resolved);
4711
4722
  this.mcpServers = preparedTools.mcpServers;
@@ -4772,4 +4783,4 @@ export {
4772
4783
  markResolvedAgentOptions,
4773
4784
  Agent
4774
4785
  };
4775
- //# sourceMappingURL=chunk-HNRNTFMQ.js.map
4786
+ //# sourceMappingURL=chunk-GAOZ263Y.js.map