@anvia/core 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/agent/index.d.ts +15 -8
  2. package/dist/agent/index.js +5 -3
  3. package/dist/{agent-CFMdNB6O.d.ts → agent-BW19m79B.d.ts} +7 -2
  4. package/dist/{chunk-GBBMMU5E.js → chunk-6OR42QTG.js} +219 -112
  5. package/dist/chunk-6OR42QTG.js.map +1 -0
  6. package/dist/{chunk-5OGAUWM5.js → chunk-IA47SXLS.js} +1 -1
  7. package/dist/chunk-IA47SXLS.js.map +1 -0
  8. package/dist/{chunk-SYMAVW5T.js → chunk-NCZRYTA6.js} +9 -3
  9. package/dist/chunk-NCZRYTA6.js.map +1 -0
  10. package/dist/{chunk-AYR3BJWH.js → chunk-SHCKZZQH.js} +3 -3
  11. package/dist/evals/index.d.ts +3 -3
  12. package/dist/evals/index.js +4 -4
  13. package/dist/extractor/index.d.ts +3 -3
  14. package/dist/extractor/index.js +4 -4
  15. package/dist/index.d.ts +7 -7
  16. package/dist/index.js +5 -3
  17. package/dist/internal/agent.d.ts +3 -3
  18. package/dist/internal/agent.js +2 -2
  19. package/dist/mcp/index.d.ts +3 -3
  20. package/dist/{middleware-C0eXGwoh.d.ts → middleware-CZocYAtZ.d.ts} +1 -1
  21. package/dist/observability/index.d.ts +1 -1
  22. package/dist/pipeline/index.d.ts +3 -3
  23. package/dist/skills/index.d.ts +3 -3
  24. package/dist/skills/index.js +1 -1
  25. package/dist/{think-tool-DQw-Oz9J.d.ts → think-tool-B8Rqw2i_.d.ts} +1 -1
  26. package/dist/tool/index.d.ts +3 -3
  27. package/dist/tool/index.js +1 -1
  28. package/dist/{tool-Bwj_zoTx.d.ts → tool-BLypI31e.d.ts} +16 -1
  29. package/dist/{types-BLyF-Tub.d.ts → types-CIwm9p4w.d.ts} +1 -1
  30. package/dist/{types-BfEFm6zu.d.ts → types-D-YTJdLj.d.ts} +1 -1
  31. package/dist/vector-store/index.d.ts +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-5OGAUWM5.js.map +0 -1
  34. package/dist/chunk-GBBMMU5E.js.map +0 -1
  35. package/dist/chunk-SYMAVW5T.js.map +0 -1
  36. /package/dist/{chunk-AYR3BJWH.js.map → chunk-SHCKZZQH.js.map} +0 -0
@@ -1,14 +1,15 @@
1
- import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-C0eXGwoh.js';
2
- export { C as CompletionRequestMiddlewareArgs, a as CompletionRequestMiddlewareResult, b as CompletionResponseMiddlewareArgs, c as CompletionResponseMiddlewareResult, T as ToolInputMiddlewareArgs, d as ToolInputMiddlewareResult, f as ToolOutputMiddlewareArgs, g as ToolOutputMiddlewareResult, h as ToolResultMiddlewareArgs, i as createMiddleware, j as createToolMiddleware } from '../middleware-C0eXGwoh.js';
3
- import { D as DynamicContextOptions, f as DynamicToolOptions, g as PromptHook, h as AgentEventStore, i as AgentEventStoreOptions, e as Agent } from '../agent-CFMdNB6O.js';
4
- export { A as AgentChildStreamEvent, j as AgentEventAppendInput, k as AgentEventRecord, l as AgentEventStoreInclude, a as AgentStreamEvent, C as CompletionCallHookArgs, m as CompletionErrorHookArgs, n as CompletionResponseHookArgs, H as HookAction, o as HookResult, P as PromptResponse, R as RunControl, p as RunEndHookArgs, q as RunErrorHookArgs, u as RunStartHookArgs, T as ToolApprovalRequestOptions, v as ToolCallControl, w as ToolCallHookAction, x as ToolCallHookArgs, y as ToolCallHookResult, z as ToolErrorHookArgs, B as ToolHookArgs, E as ToolResultHookArgs, F as TurnEndHookArgs, G as TurnStartHookArgs, c as cancelPrompt, b as createHook, r as requestToolApproval, d as runControl, s as skipTool, t as toolCallControl } from '../agent-CFMdNB6O.js';
1
+ import { A as AnyTool, e as ToolApprovalsOptions, d as ToolApprovalRequest } from '../tool-BLypI31e.js';
2
+ export { b as ToolApprovalDecision } from '../tool-BLypI31e.js';
3
+ import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-CZocYAtZ.js';
4
+ export { C as CompletionRequestMiddlewareArgs, a as CompletionRequestMiddlewareResult, b as CompletionResponseMiddlewareArgs, c as CompletionResponseMiddlewareResult, T as ToolInputMiddlewareArgs, d as ToolInputMiddlewareResult, f as ToolOutputMiddlewareArgs, g as ToolOutputMiddlewareResult, h as ToolResultMiddlewareArgs, i as createMiddleware, j as createToolMiddleware } from '../middleware-CZocYAtZ.js';
5
+ import { D as DynamicContextOptions, f as DynamicToolOptions, g as PromptHook, h as AgentEventStore, i as AgentEventStoreOptions, e as Agent } from '../agent-BW19m79B.js';
6
+ export { A as AgentChildStreamEvent, j as AgentEventAppendInput, k as AgentEventRecord, l as AgentEventStoreInclude, a as AgentStreamEvent, C as CompletionCallHookArgs, m as CompletionErrorHookArgs, n as CompletionResponseHookArgs, H as HookAction, o as HookResult, P as PromptResponse, R as RunControl, p as RunEndHookArgs, q as RunErrorHookArgs, u as RunStartHookArgs, T as ToolApprovalRequestOptions, v as ToolCallControl, w as ToolCallHookAction, x as ToolCallHookArgs, y as ToolCallHookResult, z as ToolErrorHookArgs, B as ToolHookArgs, E as ToolResultHookArgs, F as TurnEndHookArgs, G as TurnStartHookArgs, c as cancelPrompt, b as createHook, r as requestToolApproval, d as runControl, s as skipTool, t as toolCallControl } from '../agent-BW19m79B.js';
5
7
  import { Z as ZodSchema } from '../zod-schema-C7F4clpm.js';
6
8
  import { C as CompletionModel, e as JsonValue, n as ToolChoice, M as Message } from '../types-C8loR4il.js';
7
- import { a as McpServer } from '../types-BLyF-Tub.js';
9
+ import { a as McpServer } from '../types-CIwm9p4w.js';
8
10
  import { MemoryStore, MemoryOptions } from '../memory/index.js';
9
11
  import { AgentObserver, ObserveOptions } from '../observability/index.js';
10
- import { a as SkillSet } from '../types-BfEFm6zu.js';
11
- import { A as AnyTool } from '../tool-Bwj_zoTx.js';
12
+ import { a as SkillSet } from '../types-D-YTJdLj.js';
12
13
  import { VectorSearchIndex } from '../vector-store/index.js';
13
14
  import '../types-IB2e9u5M.js';
14
15
  import 'zod';
@@ -30,6 +31,7 @@ declare class AgentBuilder<M extends CompletionModel = CompletionModel> {
30
31
  private turns;
31
32
  private requestHook;
32
33
  private schema;
34
+ private approvalOptions;
33
35
  private skillInstructionBlocks;
34
36
  private observerRegistrations;
35
37
  private dynamicContextRegistrations;
@@ -67,6 +69,7 @@ declare class AgentBuilder<M extends CompletionModel = CompletionModel> {
67
69
  */
68
70
  toolMiddlewares(middlewares: ToolMiddleware[]): this;
69
71
  observe(observer: AgentObserver, options?: ObserveOptions): this;
72
+ approvals(options: ToolApprovalsOptions): this;
70
73
  memory(store: MemoryStore, options?: MemoryOptions): this;
71
74
  eventStore(store: AgentEventStore, options?: AgentEventStoreOptions): this;
72
75
  outputSchema(schema: ZodSchema): this;
@@ -85,5 +88,9 @@ declare class PromptCancelledError extends Error {
85
88
  readonly reason: string;
86
89
  constructor(chatHistory: Message[], reason: string);
87
90
  }
91
+ declare class ToolApprovalRequiredError extends Error {
92
+ readonly request: ToolApprovalRequest;
93
+ constructor(request: ToolApprovalRequest);
94
+ }
88
95
 
89
- export { AgentBuilder, AgentEventStore, AgentEventStoreOptions, AgentMiddleware, MaxTurnsError, PromptCancelledError, PromptHook, ToolMiddleware };
96
+ export { AgentBuilder, AgentEventStore, AgentEventStoreOptions, AgentMiddleware, MaxTurnsError, PromptCancelledError, PromptHook, ToolApprovalRequest, ToolApprovalRequiredError, ToolApprovalsOptions, ToolMiddleware };
@@ -1,23 +1,24 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "../chunk-SYMAVW5T.js";
3
+ } from "../chunk-NCZRYTA6.js";
4
4
  import {
5
5
  MaxTurnsError,
6
6
  PromptCancelledError,
7
+ ToolApprovalRequiredError,
7
8
  cancelPrompt,
8
9
  createHook,
9
10
  requestToolApproval,
10
11
  runControl,
11
12
  skipTool,
12
13
  toolCallControl
13
- } from "../chunk-GBBMMU5E.js";
14
+ } from "../chunk-6OR42QTG.js";
14
15
  import "../chunk-XUUY2L2D.js";
15
16
  import "../chunk-XXT2UCAR.js";
16
17
  import "../chunk-YK4WAAS4.js";
17
18
  import {
18
19
  createMiddleware,
19
20
  createToolMiddleware
20
- } from "../chunk-5OGAUWM5.js";
21
+ } from "../chunk-IA47SXLS.js";
21
22
  import "../chunk-66IJDP6L.js";
22
23
  import "../chunk-MMHG7WAM.js";
23
24
  import "../chunk-S5IGJ4RB.js";
@@ -29,6 +30,7 @@ export {
29
30
  AgentBuilder,
30
31
  MaxTurnsError,
31
32
  PromptCancelledError,
33
+ ToolApprovalRequiredError,
32
34
  cancelPrompt,
33
35
  createHook,
34
36
  createMiddleware,
@@ -1,8 +1,8 @@
1
1
  import { M as Message, U as Usage, c as CompletionResponse, k as ToolResultContent, x as ReasoningContentType, f as ToolCall, C as CompletionModel, D as Document, e as JsonValue, n as ToolChoice, J as JsonObject } from './types-C8loR4il.js';
2
2
  import { MemoryContext, MemoryRegistration, SessionOptions } from './memory/index.js';
3
3
  import { AgentTraceInfo, AgentTraceOptions, AgentObserverRegistration } from './observability/index.js';
4
- import { A as AgentMiddleware, e as ToolMiddleware, l as ToolSet, k as ToolSearchDocument } from './middleware-C0eXGwoh.js';
5
- import { T as Tool, A as AnyTool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-Bwj_zoTx.js';
4
+ import { A as AgentMiddleware, e as ToolMiddleware, l as ToolSet, k as ToolSearchDocument } from './middleware-CZocYAtZ.js';
5
+ import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-BLypI31e.js';
6
6
  import { VectorFilter, VectorSearchResult, VectorSearchIndex } from './vector-store/index.js';
7
7
 
8
8
  type HookAction = {
@@ -186,9 +186,11 @@ type AgentStreamEvent<RawResponse = unknown> = AgentChildStreamEvent<RawResponse
186
186
  declare class PromptRequest<M extends CompletionModel = CompletionModel> {
187
187
  private readonly agent;
188
188
  private readonly promptMessage;
189
+ private readonly memoryContext;
189
190
  private chatHistory;
190
191
  private maxTurnCount;
191
192
  private activeHook;
193
+ private approvalOptions;
192
194
  private concurrency;
193
195
  private traceOptions;
194
196
  private requestMiddlewares;
@@ -201,6 +203,7 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
201
203
  }): PromptRequest<M>;
202
204
  maxTurns(maxTurns: number): this;
203
205
  withHook(hook: PromptHook): this;
206
+ approvals(options: ToolApprovalsOptions): this;
204
207
  /**
205
208
  * @deprecated Use `withHook` instead.
206
209
  */
@@ -259,6 +262,7 @@ type AgentOptions<M extends CompletionModel = CompletionModel> = {
259
262
  hook?: PromptHook | undefined;
260
263
  outputSchema?: JsonObject | undefined;
261
264
  observers?: AgentObserverRegistration[] | undefined;
265
+ approvals?: ToolApprovalsOptions | undefined;
262
266
  dynamicContexts?: DynamicContextRegistration[] | undefined;
263
267
  dynamicTools?: DynamicToolRegistration[] | undefined;
264
268
  middlewares?: AgentMiddleware[] | undefined;
@@ -337,6 +341,7 @@ declare class Agent<M extends CompletionModel = CompletionModel> {
337
341
  readonly hook: PromptHook | undefined;
338
342
  readonly outputSchema: JsonObject | undefined;
339
343
  readonly observers: AgentObserverRegistration[];
344
+ readonly approvals: ToolApprovalsOptions | undefined;
340
345
  readonly dynamicContexts: DynamicContextRegistration[];
341
346
  readonly dynamicTools: DynamicToolRegistration[];
342
347
  readonly middlewares: AgentMiddleware[];
@@ -6,8 +6,9 @@ import {
6
6
  } from "./chunk-YK4WAAS4.js";
7
7
  import {
8
8
  ToolSet,
9
+ parseToolArgs,
9
10
  toolResultContentToText
10
- } from "./chunk-5OGAUWM5.js";
11
+ } from "./chunk-IA47SXLS.js";
11
12
  import {
12
13
  createTool
13
14
  } from "./chunk-66IJDP6L.js";
@@ -52,6 +53,14 @@ var PromptCancelledError = class extends Error {
52
53
  chatHistory;
53
54
  reason;
54
55
  };
56
+ var ToolApprovalRequiredError = class extends Error {
57
+ constructor(request) {
58
+ super(`Tool approval required for ${request.toolName}, but no approval handler is configured.`);
59
+ this.request = request;
60
+ this.name = "ToolApprovalRequiredError";
61
+ }
62
+ request;
63
+ };
55
64
 
56
65
  // src/agent/hooks.ts
57
66
  function createHook(hook) {
@@ -344,24 +353,6 @@ var ActiveToolObservers = class {
344
353
  }
345
354
  };
346
355
 
347
- // src/agent/request-types.ts
348
- function addTurn(turn, event) {
349
- if (event.type === "text_delta") {
350
- return { type: "text_delta", turn, delta: event.delta };
351
- }
352
- if (event.type === "reasoning_delta") {
353
- const mapped = { type: "reasoning_delta", turn, delta: event.delta };
354
- if (event.id !== void 0) mapped.id = event.id;
355
- if (event.contentType !== void 0) mapped.contentType = event.contentType;
356
- if (event.signature !== void 0) mapped.signature = event.signature;
357
- return mapped;
358
- }
359
- return { type: "tool_call", turn, toolCall: event.toolCall };
360
- }
361
- function isGenerationDeltaEvent(type) {
362
- return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call";
363
- }
364
-
365
356
  // src/agent/request-memory.ts
366
357
  var PromptRequestMemory = class {
367
358
  constructor(agent, memoryContext, initialHistory) {
@@ -454,6 +445,24 @@ var PromptRequestMemory = class {
454
445
  }
455
446
  };
456
447
 
448
+ // src/agent/request-types.ts
449
+ function addTurn(turn, event) {
450
+ if (event.type === "text_delta") {
451
+ return { type: "text_delta", turn, delta: event.delta };
452
+ }
453
+ if (event.type === "reasoning_delta") {
454
+ const mapped = { type: "reasoning_delta", turn, delta: event.delta };
455
+ if (event.id !== void 0) mapped.id = event.id;
456
+ if (event.contentType !== void 0) mapped.contentType = event.contentType;
457
+ if (event.signature !== void 0) mapped.signature = event.signature;
458
+ return mapped;
459
+ }
460
+ return { type: "tool_call", turn, toolCall: event.toolCall };
461
+ }
462
+ function isGenerationDeltaEvent(type) {
463
+ return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call";
464
+ }
465
+
457
466
  // src/agent/retrieval.ts
458
467
  async function fetchDynamicContext(agent, ragText) {
459
468
  if (ragText === void 0 || ragText.length === 0 || agent.dynamicContexts.length === 0) {
@@ -766,15 +775,19 @@ function isEmptyToolArguments(value) {
766
775
  // src/agent/tool-execution.ts
767
776
  var MCP_TOOL_METADATA_KEY = /* @__PURE__ */ Symbol.for("anvia.mcp.tool.metadata");
768
777
  var ToolCallExecutor = class {
769
- constructor(agent, activeHook, concurrency, requestMiddlewares, cancel) {
778
+ constructor(agent, activeHook, approvals, runContext, concurrency, requestMiddlewares, cancel) {
770
779
  this.agent = agent;
771
780
  this.activeHook = activeHook;
781
+ this.approvals = approvals;
782
+ this.runContext = runContext;
772
783
  this.concurrency = concurrency;
773
784
  this.requestMiddlewares = requestMiddlewares;
774
785
  this.cancel = cancel;
775
786
  }
776
787
  agent;
777
788
  activeHook;
789
+ approvals;
790
+ runContext;
778
791
  concurrency;
779
792
  requestMiddlewares;
780
793
  cancel;
@@ -795,16 +808,18 @@ var ToolCallExecutor = class {
795
808
  (definition) => definition.name === toolCall.function.name
796
809
  );
797
810
  const toolMetadata = toolTraceMetadata(tool);
798
- const toolObservers = await observation?.runObservers.startTool(compact({
799
- turn: observation.turn,
800
- toolCall,
801
- toolName: toolCall.function.name,
802
- internalCallId,
803
- args,
804
- toolCallId: toolCall.callId,
805
- toolDefinition,
806
- toolMetadata
807
- }));
811
+ const toolObservers = await observation?.runObservers.startTool(
812
+ compact({
813
+ turn: observation.turn,
814
+ toolCall,
815
+ toolName: toolCall.function.name,
816
+ internalCallId,
817
+ args,
818
+ toolCallId: toolCall.callId,
819
+ toolDefinition,
820
+ toolMetadata
821
+ })
822
+ );
808
823
  const callAction = await this.activeHook?.onToolCall?.({
809
824
  ...hookArgs,
810
825
  tool: toolCallControl
@@ -820,18 +835,6 @@ var ToolCallExecutor = class {
820
835
  );
821
836
  throw this.cancel(callAction.reason);
822
837
  }
823
- if (callAction?.type === "approval_request") {
824
- const reason = `Tool approval was requested for ${toolCall.function.name}, but no approval handler is installed.`;
825
- await recordToolError(
826
- toolObservers,
827
- observation?.turn,
828
- toolCall,
829
- internalCallId,
830
- args,
831
- reason
832
- );
833
- throw this.cancel(reason);
834
- }
835
838
  let output;
836
839
  let skipped = false;
837
840
  let effectiveArgs = args;
@@ -839,51 +842,70 @@ var ToolCallExecutor = class {
839
842
  output = callAction.reason;
840
843
  skipped = true;
841
844
  } else {
842
- effectiveArgs = await this.runToolInputMiddlewares({
843
- ...hookArgs,
844
- turn: observation?.turn ?? 0,
845
- originalArgs: args
846
- });
845
+ let approvalDecision;
847
846
  try {
848
- output = await this.agent.callTool(toolCall.function.name, effectiveArgs, {
849
- emitStreamEvent: async (event) => {
850
- await toolObservers?.streamEvent(
851
- compact({
852
- turn: observation?.turn ?? 0,
853
- toolCall,
854
- toolName: toolCall.function.name,
855
- internalCallId,
856
- args: effectiveArgs,
857
- toolCallId: toolCall.callId,
858
- event
859
- })
860
- );
861
- const payload = agentToolEventPayload(toolCall, internalCallId, event);
862
- if (payload !== void 0) {
863
- onStreamEvent?.(payload);
864
- }
865
- }
866
- });
847
+ approvalDecision = callAction?.type === "approval_request" ? await this.requestApproval(tool, hookArgs, callAction) : await this.evaluateToolApproval(tool, hookArgs) ?? { approved: true };
867
848
  } catch (error) {
868
- const errorAction = await this.activeHook?.onToolError?.({
869
- ...hookArgs,
870
- args: effectiveArgs,
871
- error,
872
- run: runControl
873
- });
874
- await toolObservers?.error({
875
- turn: observation?.turn ?? 0,
849
+ await recordToolError(
850
+ toolObservers,
851
+ observation?.turn,
876
852
  toolCall,
877
- toolName: toolCall.function.name,
878
853
  internalCallId,
879
- args: effectiveArgs,
880
- ...toolCall.callId !== void 0 && { toolCallId: toolCall.callId },
854
+ args,
881
855
  error
856
+ );
857
+ throw error;
858
+ }
859
+ if (!approvalDecision.approved) {
860
+ output = approvalDecision.result;
861
+ skipped = true;
862
+ } else {
863
+ effectiveArgs = await this.runToolInputMiddlewares({
864
+ ...hookArgs,
865
+ turn: observation?.turn ?? 0,
866
+ originalArgs: args
882
867
  });
883
- if (errorAction?.type === "terminate") {
884
- throw this.cancel(errorAction.reason);
868
+ try {
869
+ output = await this.agent.callTool(toolCall.function.name, effectiveArgs, {
870
+ emitStreamEvent: async (event) => {
871
+ await toolObservers?.streamEvent(
872
+ compact({
873
+ turn: observation?.turn ?? 0,
874
+ toolCall,
875
+ toolName: toolCall.function.name,
876
+ internalCallId,
877
+ args: effectiveArgs,
878
+ toolCallId: toolCall.callId,
879
+ event
880
+ })
881
+ );
882
+ const payload = agentToolEventPayload(toolCall, internalCallId, event);
883
+ if (payload !== void 0) {
884
+ onStreamEvent?.(payload);
885
+ }
886
+ }
887
+ });
888
+ } catch (error) {
889
+ const errorAction = await this.activeHook?.onToolError?.({
890
+ ...hookArgs,
891
+ args: effectiveArgs,
892
+ error,
893
+ run: runControl
894
+ });
895
+ await toolObservers?.error({
896
+ turn: observation?.turn ?? 0,
897
+ toolCall,
898
+ toolName: toolCall.function.name,
899
+ internalCallId,
900
+ args: effectiveArgs,
901
+ ...toolCall.callId !== void 0 && { toolCallId: toolCall.callId },
902
+ error
903
+ });
904
+ if (errorAction?.type === "terminate") {
905
+ throw this.cancel(errorAction.reason);
906
+ }
907
+ output = error instanceof Error ? error.toString() : String(error);
885
908
  }
886
- output = error instanceof Error ? error.toString() : String(error);
887
909
  }
888
910
  }
889
911
  let result = toolOutputToText(output);
@@ -991,7 +1013,65 @@ var ToolCallExecutor = class {
991
1013
  activeMiddlewares() {
992
1014
  return [...this.agent.middlewares, ...this.requestMiddlewares];
993
1015
  }
1016
+ async evaluateToolApproval(tool, hookArgs) {
1017
+ if (tool?.approval === void 0) {
1018
+ return void 0;
1019
+ }
1020
+ const policy = tool.approval;
1021
+ const context = approvalContext(tool, hookArgs, this.agent, this.runContext);
1022
+ const required = await policy.when(context);
1023
+ if (!required) {
1024
+ return { approved: true };
1025
+ }
1026
+ const reason = await resolveApprovalText(policy.reason, context);
1027
+ const rejectMessage = await resolveApprovalText(policy.rejectMessage, context);
1028
+ return this.requestApproval(tool, hookArgs, compact({ reason, rejectMessage }));
1029
+ }
1030
+ async requestApproval(tool, hookArgs, options) {
1031
+ const request = compact({
1032
+ ...approvalContext(tool, hookArgs, this.agent, this.runContext),
1033
+ reason: options.reason,
1034
+ rejectMessage: options.rejectMessage
1035
+ });
1036
+ if (this.approvals === void 0) {
1037
+ throw new ToolApprovalRequiredError(request);
1038
+ }
1039
+ const decision = normalizeApprovalDecision(await this.approvals.handler(request));
1040
+ if (decision.approved) {
1041
+ return { approved: true };
1042
+ }
1043
+ return {
1044
+ approved: false,
1045
+ result: decision.rejectMessage ?? decision.reason ?? request.rejectMessage ?? "Tool approval was rejected."
1046
+ };
1047
+ }
994
1048
  };
1049
+ function approvalContext(tool, hookArgs, agent, run) {
1050
+ const rawParsedArgs = parseToolArgs(hookArgs.args);
1051
+ const parsedArgs = tool?.parseApprovalArgs?.(rawParsedArgs) ?? rawParsedArgs;
1052
+ return compact({
1053
+ toolName: hookArgs.toolName,
1054
+ args: parsedArgs,
1055
+ rawArgs: hookArgs.args,
1056
+ toolCallId: hookArgs.toolCallId,
1057
+ internalCallId: hookArgs.internalCallId,
1058
+ run: compact({
1059
+ agentId: agent.id,
1060
+ runId: run.runId,
1061
+ sessionId: run.sessionId,
1062
+ metadata: run.metadata
1063
+ })
1064
+ });
1065
+ }
1066
+ function normalizeApprovalDecision(decision) {
1067
+ if (typeof decision === "boolean") {
1068
+ return { approved: decision };
1069
+ }
1070
+ return decision;
1071
+ }
1072
+ async function resolveApprovalText(value, context) {
1073
+ return typeof value === "function" ? value(context) : value;
1074
+ }
995
1075
  function normalizeToolOutputMiddlewareResult(result) {
996
1076
  if (typeof result === "string") {
997
1077
  return { result };
@@ -1046,16 +1126,20 @@ var PromptRequest = class _PromptRequest {
1046
1126
  constructor(agent, promptMessage, initialHistory = [], memoryContext = void 0) {
1047
1127
  this.agent = agent;
1048
1128
  this.promptMessage = promptMessage;
1129
+ this.memoryContext = memoryContext;
1049
1130
  this.chatHistory = initialHistory;
1050
1131
  this.maxTurnCount = agent.defaultMaxTurns ?? 0;
1051
1132
  this.activeHook = agent.hook;
1133
+ this.approvalOptions = agent.approvals;
1052
1134
  this.memoryRecorder = new PromptRequestMemory(agent, memoryContext, initialHistory);
1053
1135
  }
1054
1136
  agent;
1055
1137
  promptMessage;
1138
+ memoryContext;
1056
1139
  chatHistory;
1057
1140
  maxTurnCount;
1058
1141
  activeHook;
1142
+ approvalOptions;
1059
1143
  concurrency = 1;
1060
1144
  traceOptions;
1061
1145
  requestMiddlewares = [];
@@ -1074,6 +1158,10 @@ var PromptRequest = class _PromptRequest {
1074
1158
  this.activeHook = hook;
1075
1159
  return this;
1076
1160
  }
1161
+ approvals(options) {
1162
+ this.approvalOptions = options;
1163
+ return this;
1164
+ }
1077
1165
  /**
1078
1166
  * @deprecated Use `withHook` instead.
1079
1167
  */
@@ -1187,6 +1275,7 @@ var PromptRequest = class _PromptRequest {
1187
1275
  return result;
1188
1276
  }
1189
1277
  const toolResults = await this.executeToolCalls(
1278
+ runId,
1190
1279
  toolCalls,
1191
1280
  newMessages,
1192
1281
  void 0,
@@ -1259,16 +1348,18 @@ var PromptRequest = class _PromptRequest {
1259
1348
  request = await this.runCompletionRequestMiddlewares(request, currentTurns);
1260
1349
  assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
1261
1350
  const providerRequest = this.providerTraceRequest(request, { stream: true });
1262
- const generationObservers = await runObservers.startGeneration(compact({
1263
- turn: currentTurns,
1264
- request,
1265
- providerRequest,
1266
- modelInfo: {
1267
- provider: this.agent.model.provider,
1268
- defaultModel: this.agent.model.defaultModel,
1269
- capabilities: this.agent.model.capabilities
1270
- }
1271
- }));
1351
+ const generationObservers = await runObservers.startGeneration(
1352
+ compact({
1353
+ turn: currentTurns,
1354
+ request,
1355
+ providerRequest,
1356
+ modelInfo: {
1357
+ provider: this.agent.model.provider,
1358
+ defaultModel: this.agent.model.defaultModel,
1359
+ capabilities: this.agent.model.capabilities
1360
+ }
1361
+ })
1362
+ );
1272
1363
  const accumulator = new CompletionStreamAccumulator();
1273
1364
  const generationStartedAt = Date.now();
1274
1365
  let firstDeltaMs;
@@ -1291,11 +1382,13 @@ var PromptRequest = class _PromptRequest {
1291
1382
  throw error;
1292
1383
  }
1293
1384
  let response = accumulator.response();
1294
- await generationObservers.end(compact({
1295
- turn: currentTurns,
1296
- response,
1297
- firstDeltaMs
1298
- }));
1385
+ await generationObservers.end(
1386
+ compact({
1387
+ turn: currentTurns,
1388
+ response,
1389
+ firstDeltaMs
1390
+ })
1391
+ );
1299
1392
  response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
1300
1393
  usage = Usage.add(usage, response.usage);
1301
1394
  await this.runCompletionResponseHook(prompt, response, newMessages);
@@ -1342,6 +1435,7 @@ var PromptRequest = class _PromptRequest {
1342
1435
  }
1343
1436
  const toolResultEvents = createAsyncQueue();
1344
1437
  const toolResultsPromise = this.executeToolCalls(
1438
+ runId,
1345
1439
  toolCalls,
1346
1440
  newMessages,
1347
1441
  (result) => {
@@ -1391,16 +1485,18 @@ var PromptRequest = class _PromptRequest {
1391
1485
  async runCompletion(request, turn, runObservers) {
1392
1486
  assertCompletionRequestSupported(this.agent.model, request);
1393
1487
  const providerRequest = this.providerTraceRequest(request);
1394
- const generationObservers = await runObservers.startGeneration(compact({
1395
- turn,
1396
- request,
1397
- providerRequest,
1398
- modelInfo: {
1399
- provider: this.agent.model.provider,
1400
- defaultModel: this.agent.model.defaultModel,
1401
- capabilities: this.agent.model.capabilities
1402
- }
1403
- }));
1488
+ const generationObservers = await runObservers.startGeneration(
1489
+ compact({
1490
+ turn,
1491
+ request,
1492
+ providerRequest,
1493
+ modelInfo: {
1494
+ provider: this.agent.model.provider,
1495
+ defaultModel: this.agent.model.defaultModel,
1496
+ capabilities: this.agent.model.capabilities
1497
+ }
1498
+ })
1499
+ );
1404
1500
  try {
1405
1501
  const response = await this.agent.model.completion(request);
1406
1502
  await generationObservers.end({ turn, response });
@@ -1419,10 +1515,16 @@ var PromptRequest = class _PromptRequest {
1419
1515
  };
1420
1516
  }
1421
1517
  }
1422
- async executeToolCalls(toolCalls, newMessages, onResult, onStreamEvent, observation) {
1518
+ async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
1423
1519
  const executor = new ToolCallExecutor(
1424
1520
  this.agent,
1425
1521
  this.activeHook,
1522
+ this.approvalOptions,
1523
+ {
1524
+ runId,
1525
+ sessionId: this.memoryContext?.sessionId,
1526
+ metadata: this.memoryContext?.metadata
1527
+ },
1426
1528
  this.concurrency,
1427
1529
  this.requestMiddlewares,
1428
1530
  (reason) => this.cancelled(newMessages, reason)
@@ -1650,6 +1752,7 @@ var Agent = class {
1650
1752
  hook;
1651
1753
  outputSchema;
1652
1754
  observers;
1755
+ approvals;
1653
1756
  dynamicContexts;
1654
1757
  dynamicTools;
1655
1758
  middlewares;
@@ -1675,6 +1778,7 @@ var Agent = class {
1675
1778
  this.hook = options.hook;
1676
1779
  this.outputSchema = options.outputSchema;
1677
1780
  this.observers = options.observers ?? [];
1781
+ this.approvals = options.approvals;
1678
1782
  this.dynamicContexts = options.dynamicContexts ?? [];
1679
1783
  this.dynamicTools = options.dynamicTools ?? [];
1680
1784
  this.middlewares = options.middlewares ?? options.toolMiddlewares ?? [];
@@ -1714,11 +1818,13 @@ var Agent = class {
1714
1818
  if (options.stream === true && context.emitStreamEvent !== void 0 && this.model.capabilities.streaming && isStreamingCompletionModel(this.model)) {
1715
1819
  let output = "";
1716
1820
  for await (const event of childRequest.stream()) {
1717
- await context.emitStreamEvent(compact({
1718
- agentId: this.id,
1719
- agentName: this.name,
1720
- event
1721
- }));
1821
+ await context.emitStreamEvent(
1822
+ compact({
1823
+ agentId: this.id,
1824
+ agentName: this.name,
1825
+ event
1826
+ })
1827
+ );
1722
1828
  if (event.type === "final") {
1723
1829
  output = event.output;
1724
1830
  }
@@ -1796,6 +1902,7 @@ export {
1796
1902
  normalizeAgentId,
1797
1903
  MaxTurnsError,
1798
1904
  PromptCancelledError,
1905
+ ToolApprovalRequiredError,
1799
1906
  createHook,
1800
1907
  cancelPrompt,
1801
1908
  skipTool,
@@ -1807,4 +1914,4 @@ export {
1807
1914
  Agent,
1808
1915
  AgentSession
1809
1916
  };
1810
- //# sourceMappingURL=chunk-GBBMMU5E.js.map
1917
+ //# sourceMappingURL=chunk-6OR42QTG.js.map