@anvia/core 1.0.0-rc.2 → 1.0.0-rc.4
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 +77 -10
- 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-3RM57ZT2.js +31 -0
- package/dist/chunk-3RM57ZT2.js.map +1 -0
- package/dist/{chunk-DBSCKTUL.js → chunk-5GXSQYQT.js} +1744 -838
- package/dist/chunk-5GXSQYQT.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-KR3RCCHJ.js → chunk-D2ECOWN5.js} +26 -11
- package/dist/chunk-D2ECOWN5.js.map +1 -0
- package/dist/{chunk-EINTGEGY.js → chunk-FXAIYTRE.js} +101 -26
- package/dist/chunk-FXAIYTRE.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-D37WMSP6.js → chunk-J2W63PJI.js} +50 -10
- package/dist/chunk-J2W63PJI.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-TIZYTPJO.js → chunk-PK5LKOFL.js} +33 -2
- package/dist/chunk-PK5LKOFL.js.map +1 -0
- package/dist/{chunk-XKYYBABH.js → chunk-RFHQY2IO.js} +2 -2
- 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-77AIYARB.js → chunk-XYTPYUGB.js} +29 -19
- package/dist/chunk-XYTPYUGB.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 +49 -28
- 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 +7 -6
- package/dist/vector-store/index.js +6 -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-RFHQY2IO.js.map} +0 -0
- /package/dist/{chunk-4WI3VGZK.js.map → chunk-ZCPOIDAQ.js.map} +0 -0
|
@@ -1,12 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isMcpTool
|
|
3
|
+
} from "./chunk-FXAIYTRE.js";
|
|
4
|
+
import {
|
|
5
|
+
MemoryCompactionConflictError,
|
|
6
|
+
MemoryCompactionError,
|
|
7
|
+
assertPositiveInteger,
|
|
8
|
+
createMemoryCompactionSummary,
|
|
9
|
+
cumulativeCompactedMessageCount
|
|
10
|
+
} from "./chunk-KFR4CDGK.js";
|
|
11
|
+
import {
|
|
12
|
+
startAgentRunObservers
|
|
13
|
+
} from "./chunk-VKYZZXP5.js";
|
|
1
14
|
import {
|
|
2
15
|
isSkillTool
|
|
3
16
|
} from "./chunk-YK4WAAS4.js";
|
|
4
17
|
import {
|
|
5
|
-
|
|
6
|
-
} from "./chunk-EINTGEGY.js";
|
|
7
|
-
import {
|
|
18
|
+
isQuestionTool,
|
|
8
19
|
isToolIndex
|
|
9
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-J2W63PJI.js";
|
|
10
21
|
import {
|
|
11
22
|
ToolNotFoundError,
|
|
12
23
|
assertFiniteMinScore,
|
|
@@ -15,23 +26,21 @@ import {
|
|
|
15
26
|
createTool,
|
|
16
27
|
parseToolArgs,
|
|
17
28
|
prepareToolCall,
|
|
29
|
+
prepareToolCallFromInput,
|
|
18
30
|
retrieveDocuments,
|
|
19
31
|
toolMayRequireApproval,
|
|
20
32
|
toolResultContentToText
|
|
21
|
-
} from "./chunk-
|
|
22
|
-
import {
|
|
23
|
-
MemoryCompactionConflictError,
|
|
24
|
-
MemoryCompactionError,
|
|
25
|
-
assertPositiveInteger,
|
|
26
|
-
createMemoryCompactionSummary,
|
|
27
|
-
cumulativeCompactedMessageCount
|
|
28
|
-
} from "./chunk-OJH6HWHX.js";
|
|
33
|
+
} from "./chunk-XYTPYUGB.js";
|
|
29
34
|
import {
|
|
30
|
-
|
|
31
|
-
|
|
35
|
+
AgentRunBlockedError,
|
|
36
|
+
AgentRunCancelledError,
|
|
37
|
+
AgentStreamClosedError,
|
|
38
|
+
AgentToolSuspensionError,
|
|
39
|
+
MaxTurnsError
|
|
40
|
+
} from "./chunk-TRQ3XRFD.js";
|
|
32
41
|
import {
|
|
33
42
|
mapWithConcurrency
|
|
34
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-3RM57ZT2.js";
|
|
35
44
|
import {
|
|
36
45
|
Usage,
|
|
37
46
|
assertCompletionRequestSupported,
|
|
@@ -40,18 +49,13 @@ import {
|
|
|
40
49
|
isProviderTool,
|
|
41
50
|
isStreamingCompletionModel,
|
|
42
51
|
textFromAssistantContent
|
|
43
|
-
} from "./chunk-
|
|
52
|
+
} from "./chunk-D2ECOWN5.js";
|
|
44
53
|
import {
|
|
54
|
+
isJsonValue,
|
|
45
55
|
parseMessage,
|
|
46
56
|
parseMessages,
|
|
47
57
|
toProviderJsonSchema
|
|
48
|
-
} from "./chunk-
|
|
49
|
-
import {
|
|
50
|
-
appendGuardrailPolicies,
|
|
51
|
-
hasEnforcedOutputGuardrails,
|
|
52
|
-
runInputGuardrails,
|
|
53
|
-
runOutputGuardrails
|
|
54
|
-
} from "./chunk-KIDGIJM7.js";
|
|
58
|
+
} from "./chunk-PK5LKOFL.js";
|
|
55
59
|
import {
|
|
56
60
|
abortError,
|
|
57
61
|
resolveRetryOptions,
|
|
@@ -61,38 +65,161 @@ import {
|
|
|
61
65
|
throwIfAborted,
|
|
62
66
|
waitForRetry
|
|
63
67
|
} from "./chunk-FN7HLLAZ.js";
|
|
68
|
+
import {
|
|
69
|
+
appendGuardrailPolicies,
|
|
70
|
+
hasEnforcedOutputGuardrails,
|
|
71
|
+
runInputGuardrails,
|
|
72
|
+
runOutputGuardrails
|
|
73
|
+
} from "./chunk-AZB6N7P4.js";
|
|
64
74
|
|
|
65
|
-
// src/agent/
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
75
|
+
// src/agent/interactions.ts
|
|
76
|
+
import { z } from "zod";
|
|
77
|
+
var nonblank = z.string().trim().min(1);
|
|
78
|
+
var jsonValueSchema = z.custom(isJsonValue, {
|
|
79
|
+
message: "Expected a strict JSON value"
|
|
80
|
+
});
|
|
81
|
+
var jsonObjectSchema = z.custom(
|
|
82
|
+
(value) => typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value),
|
|
83
|
+
{ message: "Expected a strict JSON object" }
|
|
84
|
+
);
|
|
85
|
+
var questionChoiceSchema = z.object({
|
|
86
|
+
label: nonblank,
|
|
87
|
+
value: nonblank
|
|
88
|
+
}).strict();
|
|
89
|
+
var questionPromptSchema = z.object({
|
|
90
|
+
id: nonblank,
|
|
91
|
+
text: nonblank,
|
|
92
|
+
choices: z.array(questionChoiceSchema).min(1).optional(),
|
|
93
|
+
allowCustom: z.boolean().optional()
|
|
94
|
+
}).strict().superRefine((question, context) => {
|
|
95
|
+
if (question.choices === void 0 && question.allowCustom === false) {
|
|
96
|
+
context.addIssue({
|
|
97
|
+
code: "custom",
|
|
98
|
+
message: "A free-text question cannot disable custom answers.",
|
|
99
|
+
path: ["allowCustom"]
|
|
100
|
+
});
|
|
84
101
|
}
|
|
85
|
-
|
|
86
|
-
|
|
102
|
+
const values = /* @__PURE__ */ new Set();
|
|
103
|
+
for (const [index, choice] of (question.choices ?? []).entries()) {
|
|
104
|
+
if (values.has(choice.value)) {
|
|
105
|
+
context.addIssue({
|
|
106
|
+
code: "custom",
|
|
107
|
+
message: "Question choice values must be unique.",
|
|
108
|
+
path: ["choices", index, "value"]
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
values.add(choice.value);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
var questionAnswerSchema = z.object({
|
|
115
|
+
questionId: nonblank,
|
|
116
|
+
value: nonblank
|
|
117
|
+
}).strict();
|
|
118
|
+
var interactionBase = {
|
|
119
|
+
id: nonblank,
|
|
120
|
+
toolName: nonblank,
|
|
121
|
+
toolCallId: nonblank,
|
|
122
|
+
callId: z.string().optional(),
|
|
123
|
+
internalCallId: nonblank
|
|
87
124
|
};
|
|
88
|
-
var
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
125
|
+
var approvalRequestSchema = z.object({
|
|
126
|
+
type: z.literal("tool-approval"),
|
|
127
|
+
...interactionBase,
|
|
128
|
+
input: jsonValueSchema,
|
|
129
|
+
reason: z.string().optional()
|
|
130
|
+
}).strict();
|
|
131
|
+
var questionRequestSchema = z.object({
|
|
132
|
+
type: z.literal("tool-question"),
|
|
133
|
+
...interactionBase,
|
|
134
|
+
questions: z.array(questionPromptSchema).min(1)
|
|
135
|
+
}).strict().superRefine((request, context) => {
|
|
136
|
+
const ids = /* @__PURE__ */ new Set();
|
|
137
|
+
for (const [index, question] of request.questions.entries()) {
|
|
138
|
+
if (ids.has(question.id)) {
|
|
139
|
+
context.addIssue({
|
|
140
|
+
code: "custom",
|
|
141
|
+
message: "Question IDs must be unique.",
|
|
142
|
+
path: ["questions", index, "id"]
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
ids.add(question.id);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
var agentInteractionRequestSchema = z.discriminatedUnion("type", [
|
|
149
|
+
approvalRequestSchema,
|
|
150
|
+
questionRequestSchema
|
|
151
|
+
]);
|
|
152
|
+
var agentInteractionResponseSchema = z.discriminatedUnion("type", [
|
|
153
|
+
z.object({
|
|
154
|
+
type: z.literal("tool-approval"),
|
|
155
|
+
approved: z.boolean(),
|
|
156
|
+
reason: z.string().optional()
|
|
157
|
+
}).strict(),
|
|
158
|
+
z.object({
|
|
159
|
+
type: z.literal("tool-question"),
|
|
160
|
+
answers: z.array(questionAnswerSchema)
|
|
161
|
+
}).strict()
|
|
162
|
+
]);
|
|
163
|
+
var agentContinuationSchema = z.object({
|
|
164
|
+
version: z.literal(1),
|
|
165
|
+
agentId: nonblank,
|
|
166
|
+
sourceRunId: nonblank,
|
|
167
|
+
interaction: agentInteractionRequestSchema,
|
|
168
|
+
state: jsonObjectSchema
|
|
169
|
+
}).strict();
|
|
170
|
+
function parseAgentInteractionRequest(value) {
|
|
171
|
+
return freeze(agentInteractionRequestSchema.parse(value));
|
|
172
|
+
}
|
|
173
|
+
function parseAgentInteractionResponse(value) {
|
|
174
|
+
return freeze(agentInteractionResponseSchema.parse(value));
|
|
175
|
+
}
|
|
176
|
+
function parseAgentQuestionPrompts(value) {
|
|
177
|
+
const request = questionRequestSchema.parse({
|
|
178
|
+
type: "tool-question",
|
|
179
|
+
id: "validation",
|
|
180
|
+
toolName: "validation",
|
|
181
|
+
toolCallId: "validation",
|
|
182
|
+
internalCallId: "validation",
|
|
183
|
+
questions: value
|
|
184
|
+
});
|
|
185
|
+
return freeze(request.questions);
|
|
186
|
+
}
|
|
187
|
+
function parseAgentContinuation(value) {
|
|
188
|
+
return freeze(agentContinuationSchema.parse(value));
|
|
189
|
+
}
|
|
190
|
+
function assertAgentInteractionResponse(request, response) {
|
|
191
|
+
if (request.type !== response.type) {
|
|
192
|
+
throw new TypeError("Interaction response type does not match the pending request.");
|
|
93
193
|
}
|
|
94
|
-
|
|
95
|
-
|
|
194
|
+
if (request.type === "tool-question" && response.type === "tool-question") {
|
|
195
|
+
assertQuestionAnswers(request, response.answers);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function assertQuestionAnswers(request, answers) {
|
|
199
|
+
const parsed = answers.map((answer) => questionAnswerSchema.parse(answer));
|
|
200
|
+
const byId = new Map(parsed.map((answer) => [answer.questionId, answer]));
|
|
201
|
+
if (byId.size !== parsed.length) {
|
|
202
|
+
throw new TypeError("Question answers must not contain duplicate question IDs.");
|
|
203
|
+
}
|
|
204
|
+
if (byId.size !== request.questions.length) {
|
|
205
|
+
throw new TypeError("Question responses must answer every question exactly once.");
|
|
206
|
+
}
|
|
207
|
+
for (const question of request.questions) {
|
|
208
|
+
const answer = byId.get(question.id);
|
|
209
|
+
if (answer === void 0) {
|
|
210
|
+
throw new TypeError(`Question response is missing an answer for "${question.id}".`);
|
|
211
|
+
}
|
|
212
|
+
const choices = question.choices;
|
|
213
|
+
if (choices !== void 0 && question.allowCustom !== true && !choices.some((choice) => choice.value === answer.value)) {
|
|
214
|
+
throw new TypeError(`Question "${question.id}" requires one of its configured choices.`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function freeze(value) {
|
|
219
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
|
|
220
|
+
for (const child of Object.values(value)) freeze(child);
|
|
221
|
+
return Object.freeze(value);
|
|
222
|
+
}
|
|
96
223
|
|
|
97
224
|
// src/agent/tool-state.ts
|
|
98
225
|
var agentToolStates = /* @__PURE__ */ new WeakMap();
|
|
@@ -158,25 +285,19 @@ var toolCallControl = {
|
|
|
158
285
|
}
|
|
159
286
|
};
|
|
160
287
|
|
|
161
|
-
// src/internal/agent-runtime/approval-details.ts
|
|
162
|
-
var approvalDetails = /* @__PURE__ */ new WeakMap();
|
|
163
|
-
function registerAgentApprovalRequestDetails(approval, request) {
|
|
164
|
-
approvalDetails.set(approval, request);
|
|
165
|
-
}
|
|
166
|
-
function getAgentApprovalRequestDetails(approval) {
|
|
167
|
-
return approvalDetails.get(approval);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
288
|
// src/agent/vector-context.ts
|
|
171
289
|
function createVectorContext(options) {
|
|
172
290
|
const topK = assertPositiveSearchLimit(options.topK);
|
|
173
291
|
const minScore = assertFiniteMinScore(options.minScore);
|
|
174
|
-
|
|
292
|
+
let context = {
|
|
175
293
|
...options,
|
|
176
294
|
topK,
|
|
177
|
-
...minScore === void 0 ? {} : { minScore },
|
|
178
295
|
kind: "vector-context"
|
|
179
|
-
}
|
|
296
|
+
};
|
|
297
|
+
if (minScore !== void 0) {
|
|
298
|
+
context = { ...context, minScore };
|
|
299
|
+
}
|
|
300
|
+
return Object.freeze(context);
|
|
180
301
|
}
|
|
181
302
|
function isVectorContext(value) {
|
|
182
303
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -199,9 +320,6 @@ function getInternalAgentRunOptions(options) {
|
|
|
199
320
|
return options[internalAgentRunOptions];
|
|
200
321
|
}
|
|
201
322
|
|
|
202
|
-
// src/agent/agent.ts
|
|
203
|
-
import { z } from "zod";
|
|
204
|
-
|
|
205
323
|
// src/agent/lifecycle.ts
|
|
206
324
|
function composeAgentLifecycle(first, second) {
|
|
207
325
|
if (first === void 0) return second;
|
|
@@ -265,6 +383,17 @@ function cloneLifecycleFallback(value, seen) {
|
|
|
265
383
|
return clone;
|
|
266
384
|
}
|
|
267
385
|
|
|
386
|
+
// src/agent/output-schema.ts
|
|
387
|
+
var providerOutputSchemas = /* @__PURE__ */ new WeakMap();
|
|
388
|
+
function registerAgentProviderOutputSchema(agent, schema) {
|
|
389
|
+
if (schema !== void 0) {
|
|
390
|
+
providerOutputSchemas.set(agent, toProviderJsonSchema(schema));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function getAgentProviderOutputSchema(agent) {
|
|
394
|
+
return providerOutputSchemas.get(agent);
|
|
395
|
+
}
|
|
396
|
+
|
|
268
397
|
// src/internal/async-queue.ts
|
|
269
398
|
function createAsyncQueue() {
|
|
270
399
|
const values = [];
|
|
@@ -343,6 +472,9 @@ function extractRagText(message) {
|
|
|
343
472
|
}
|
|
344
473
|
if (message.role === "tool") {
|
|
345
474
|
return message.content.flatMap((item) => {
|
|
475
|
+
if (item.type !== "tool-result") {
|
|
476
|
+
return [];
|
|
477
|
+
}
|
|
346
478
|
const output = item.output;
|
|
347
479
|
if (output.type === "text" || output.type === "error-text") {
|
|
348
480
|
return [output.value];
|
|
@@ -356,6 +488,179 @@ function extractRagText(message) {
|
|
|
356
488
|
return void 0;
|
|
357
489
|
}
|
|
358
490
|
|
|
491
|
+
// src/internal/agent-runtime/continuation-state.ts
|
|
492
|
+
function serializeContinuationState(state) {
|
|
493
|
+
const value = structuredClone(state);
|
|
494
|
+
if (!isJsonValue(value) || Array.isArray(value) || value === null) {
|
|
495
|
+
throw new TypeError("Agent continuation state must be strict JSON.");
|
|
496
|
+
}
|
|
497
|
+
return value;
|
|
498
|
+
}
|
|
499
|
+
function parseContinuationState(value, interaction) {
|
|
500
|
+
requireOnlyKeys(value, [
|
|
501
|
+
"kind",
|
|
502
|
+
"history",
|
|
503
|
+
"messages",
|
|
504
|
+
"pending",
|
|
505
|
+
"remainingToolCalls",
|
|
506
|
+
"steering",
|
|
507
|
+
"memoryScope"
|
|
508
|
+
]);
|
|
509
|
+
if (value.kind !== "anvia.agent-continuation") {
|
|
510
|
+
throw new TypeError("Agent continuation has an unsupported internal state.");
|
|
511
|
+
}
|
|
512
|
+
const history = parseMessages(value.history);
|
|
513
|
+
const messages = parseMessages(value.messages);
|
|
514
|
+
const pending = parsePending(value.pending);
|
|
515
|
+
const remainingToolCalls = parseToolCalls(value.remainingToolCalls);
|
|
516
|
+
const steering = parseSteering(value.steering);
|
|
517
|
+
if (pending.toolCall.toolCallId !== interaction.toolCallId || pending.toolCall.toolName !== interaction.toolName || pending.toolCall.callId !== interaction.callId || pending.internalCallId !== interaction.internalCallId) {
|
|
518
|
+
throw new TypeError("Agent continuation interaction does not match its pending tool call.");
|
|
519
|
+
}
|
|
520
|
+
if (interaction.type === "tool-approval" && !jsonEqual(interaction.input, pending.input)) {
|
|
521
|
+
throw new TypeError("Agent continuation approval input does not match its pending tool input.");
|
|
522
|
+
}
|
|
523
|
+
if (interaction.type === "tool-question") {
|
|
524
|
+
const questions = object(pending.input) && "questions" in pending.input ? parseAgentQuestionPrompts(pending.input.questions) : void 0;
|
|
525
|
+
if (questions === void 0 || !jsonEqual(interaction.questions, questions)) {
|
|
526
|
+
throw new TypeError(
|
|
527
|
+
"Agent continuation questions do not match its pending question tool input."
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const state = {
|
|
532
|
+
kind: "anvia.agent-continuation",
|
|
533
|
+
history,
|
|
534
|
+
messages,
|
|
535
|
+
pending,
|
|
536
|
+
remainingToolCalls,
|
|
537
|
+
steering
|
|
538
|
+
};
|
|
539
|
+
if (value.memoryScope !== void 0) {
|
|
540
|
+
state.memoryScope = parseOptionalJsonObject(value.memoryScope, "memoryScope");
|
|
541
|
+
}
|
|
542
|
+
return state;
|
|
543
|
+
}
|
|
544
|
+
function questionResult(answers) {
|
|
545
|
+
return { type: "json", value: { answers: structuredClone([...answers]) } };
|
|
546
|
+
}
|
|
547
|
+
function parsePending(value) {
|
|
548
|
+
if (!object(value)) throw new TypeError("Agent continuation pending state is invalid.");
|
|
549
|
+
const [toolCall] = parseToolCalls([value.toolCall]);
|
|
550
|
+
if (toolCall === void 0) throw new TypeError("Agent continuation pending tool is missing.");
|
|
551
|
+
if (typeof value.effectiveArgs !== "string" || typeof value.internalCallId !== "string") {
|
|
552
|
+
throw new TypeError("Agent continuation pending execution metadata is invalid.");
|
|
553
|
+
}
|
|
554
|
+
const pending = {
|
|
555
|
+
toolCall,
|
|
556
|
+
effectiveArgs: value.effectiveArgs,
|
|
557
|
+
input: parseJsonValue(value.input, "pending input"),
|
|
558
|
+
internalCallId: value.internalCallId
|
|
559
|
+
};
|
|
560
|
+
if (typeof value.rejectMessage === "string") {
|
|
561
|
+
pending.rejectMessage = value.rejectMessage;
|
|
562
|
+
}
|
|
563
|
+
return pending;
|
|
564
|
+
}
|
|
565
|
+
function parseJsonValue(value, name) {
|
|
566
|
+
if (!isJsonValue(value)) {
|
|
567
|
+
throw new TypeError(`Agent continuation ${name} is invalid.`);
|
|
568
|
+
}
|
|
569
|
+
return structuredClone(value);
|
|
570
|
+
}
|
|
571
|
+
function parseToolCalls(value) {
|
|
572
|
+
if (!Array.isArray(value)) throw new TypeError("Agent continuation tool calls must be an array.");
|
|
573
|
+
const message = parseMessages([{ role: "assistant", content: value }])[0];
|
|
574
|
+
if (message?.role !== "assistant" || typeof message.content === "string") {
|
|
575
|
+
throw new TypeError("Agent continuation tool calls are invalid.");
|
|
576
|
+
}
|
|
577
|
+
if (!message.content.every((part) => part.type === "tool-call")) {
|
|
578
|
+
throw new TypeError("Agent continuation contains a non-tool-call part.");
|
|
579
|
+
}
|
|
580
|
+
return message.content;
|
|
581
|
+
}
|
|
582
|
+
function parseSteering(value) {
|
|
583
|
+
if (!Array.isArray(value)) throw new TypeError("Agent continuation steering state is invalid.");
|
|
584
|
+
return value.map((item) => {
|
|
585
|
+
if (!object(item) || typeof item.id !== "string") {
|
|
586
|
+
throw new TypeError("Agent continuation steering entry is invalid.");
|
|
587
|
+
}
|
|
588
|
+
return { id: item.id, messages: parseMessages(item.messages) };
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
function parseOptionalJsonObject(value, name) {
|
|
592
|
+
if (value === void 0) return void 0;
|
|
593
|
+
if (!object(value) || !isJsonValue(value)) {
|
|
594
|
+
throw new TypeError(`Agent continuation ${name} is invalid.`);
|
|
595
|
+
}
|
|
596
|
+
return structuredClone(value);
|
|
597
|
+
}
|
|
598
|
+
function object(value) {
|
|
599
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
600
|
+
}
|
|
601
|
+
function requireOnlyKeys(value, allowed) {
|
|
602
|
+
const allowedKeys = new Set(allowed);
|
|
603
|
+
const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
|
|
604
|
+
if (unknown !== void 0) {
|
|
605
|
+
throw new TypeError(`Agent continuation state contains unknown key "${unknown}".`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function jsonEqual(left, right) {
|
|
609
|
+
if (Object.is(left, right)) return true;
|
|
610
|
+
if (Array.isArray(left)) {
|
|
611
|
+
return Array.isArray(right) && left.length === right.length && left.every((value, index) => jsonEqual(value, right[index]));
|
|
612
|
+
}
|
|
613
|
+
if (object(left)) {
|
|
614
|
+
if (!object(right)) return false;
|
|
615
|
+
const keys = Object.keys(left);
|
|
616
|
+
return keys.length === Object.keys(right).length && keys.every((key) => key in right && jsonEqual(left[key], right[key]));
|
|
617
|
+
}
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// src/internal/agent-runtime/interaction-suspension.ts
|
|
622
|
+
var AgentInteractionSignal = class extends Error {
|
|
623
|
+
constructor(interaction, rejectMessage) {
|
|
624
|
+
super("Agent execution requires a human interaction.");
|
|
625
|
+
this.interaction = interaction;
|
|
626
|
+
this.rejectMessage = rejectMessage;
|
|
627
|
+
this.name = "AgentInteractionSignal";
|
|
628
|
+
}
|
|
629
|
+
interaction;
|
|
630
|
+
rejectMessage;
|
|
631
|
+
};
|
|
632
|
+
var ToolExecutionSuspension = class extends Error {
|
|
633
|
+
constructor(interaction, pending) {
|
|
634
|
+
super("Tool execution suspended for human interaction.");
|
|
635
|
+
this.interaction = interaction;
|
|
636
|
+
this.pending = pending;
|
|
637
|
+
this.name = "ToolExecutionSuspension";
|
|
638
|
+
}
|
|
639
|
+
interaction;
|
|
640
|
+
pending;
|
|
641
|
+
completedResults = [];
|
|
642
|
+
remainingToolCalls = [];
|
|
643
|
+
};
|
|
644
|
+
function approvalInteraction(request) {
|
|
645
|
+
if (request.toolCallId === void 0) {
|
|
646
|
+
throw new TypeError("Tool approval requires a canonical toolCallId.");
|
|
647
|
+
}
|
|
648
|
+
if (!isJsonValue(request.args)) {
|
|
649
|
+
throw new TypeError("Tool approval input must be strict JSON.");
|
|
650
|
+
}
|
|
651
|
+
let interaction = {
|
|
652
|
+
type: "tool-approval",
|
|
653
|
+
id: request.id,
|
|
654
|
+
toolName: request.toolName,
|
|
655
|
+
toolCallId: request.toolCallId,
|
|
656
|
+
internalCallId: request.internalCallId,
|
|
657
|
+
input: request.args
|
|
658
|
+
};
|
|
659
|
+
if (request.callId !== void 0) interaction = { ...interaction, callId: request.callId };
|
|
660
|
+
if (request.reason !== void 0) interaction = { ...interaction, reason: request.reason };
|
|
661
|
+
return interaction;
|
|
662
|
+
}
|
|
663
|
+
|
|
359
664
|
// src/internal/agent-runtime/memory.ts
|
|
360
665
|
var AgentRunMemory = class {
|
|
361
666
|
constructor(agent, memoryScope, initialHistory) {
|
|
@@ -900,11 +1205,12 @@ var CompletionStreamAccumulator = class {
|
|
|
900
1205
|
accumulatedResponse.providerToolCalls,
|
|
901
1206
|
response.providerToolCalls
|
|
902
1207
|
);
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
}
|
|
1208
|
+
let accumulated = { ...withMessageId };
|
|
1209
|
+
if (sources.length > 0) accumulated = { ...accumulated, sources };
|
|
1210
|
+
if (providerToolCalls.length > 0) {
|
|
1211
|
+
accumulated = { ...accumulated, providerToolCalls };
|
|
1212
|
+
}
|
|
1213
|
+
return accumulated;
|
|
908
1214
|
}
|
|
909
1215
|
createTextKey() {
|
|
910
1216
|
this.nextTextKey += 1;
|
|
@@ -926,11 +1232,12 @@ var CompletionStreamAccumulator = class {
|
|
|
926
1232
|
const last = reasoning.details.at(-1);
|
|
927
1233
|
if (contentType === "text") {
|
|
928
1234
|
if (last?.type === "text") {
|
|
929
|
-
|
|
1235
|
+
let detail = {
|
|
930
1236
|
...last,
|
|
931
|
-
text: `${last.text}${event.delta}
|
|
932
|
-
...event.signature === void 0 ? {} : { signature: event.signature }
|
|
1237
|
+
text: `${last.text}${event.delta}`
|
|
933
1238
|
};
|
|
1239
|
+
if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
|
|
1240
|
+
reasoning.details[reasoning.details.length - 1] = detail;
|
|
934
1241
|
} else {
|
|
935
1242
|
reasoning.details.push(
|
|
936
1243
|
event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
|
|
@@ -979,14 +1286,15 @@ function reasoningContent(reasoning) {
|
|
|
979
1286
|
}
|
|
980
1287
|
function toolCallContent(toolCall, finalToolCall) {
|
|
981
1288
|
const argumentsValue = finalToolCall !== void 0 && !isEmptyToolArguments(finalToolCall.input) ? finalToolCall.input : parseToolArguments(toolCall.id, toolCall.argumentsText);
|
|
982
|
-
|
|
1289
|
+
let content = {
|
|
983
1290
|
type: "tool-call",
|
|
984
1291
|
toolCallId: toolCall.id,
|
|
985
1292
|
toolName: toolCall.name,
|
|
986
|
-
input: argumentsValue
|
|
987
|
-
...toolCall.callId === void 0 ? {} : { callId: toolCall.callId },
|
|
988
|
-
...toolCall.signature === void 0 ? {} : { signature: toolCall.signature }
|
|
1293
|
+
input: argumentsValue
|
|
989
1294
|
};
|
|
1295
|
+
if (toolCall.callId !== void 0) content = { ...content, callId: toolCall.callId };
|
|
1296
|
+
if (toolCall.signature !== void 0) content = { ...content, signature: toolCall.signature };
|
|
1297
|
+
return content;
|
|
990
1298
|
}
|
|
991
1299
|
function matchingFinalToolCall(accumulated, finalChoice) {
|
|
992
1300
|
const byId = finalChoice?.find(
|
|
@@ -1109,33 +1417,36 @@ var ToolCallExecutor = class {
|
|
|
1109
1417
|
);
|
|
1110
1418
|
}
|
|
1111
1419
|
}
|
|
1112
|
-
|
|
1420
|
+
const executeOne = async (toolCall) => {
|
|
1113
1421
|
throwIfAborted(this.abortSignal);
|
|
1114
1422
|
const args = JSON.stringify(toolCall.input);
|
|
1115
1423
|
const internalCallId = globalThis.crypto.randomUUID();
|
|
1116
1424
|
const hookArgs = {
|
|
1117
1425
|
toolName: toolCall.toolName,
|
|
1426
|
+
toolCallId: toolCall.toolCallId,
|
|
1118
1427
|
internalCallId,
|
|
1119
1428
|
args
|
|
1120
1429
|
};
|
|
1121
1430
|
if (toolCall.callId !== void 0) {
|
|
1122
|
-
hookArgs.
|
|
1431
|
+
hookArgs.callId = toolCall.callId;
|
|
1123
1432
|
}
|
|
1124
1433
|
const tool = this.agent.getTool(toolCall.toolName);
|
|
1125
1434
|
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1126
1435
|
(definition) => definition.name === toolCall.toolName
|
|
1127
1436
|
);
|
|
1128
1437
|
const toolMetadata = toolTraceMetadata(tool);
|
|
1129
|
-
|
|
1438
|
+
let toolStartArgs = {
|
|
1130
1439
|
turn: observation?.turn ?? 0,
|
|
1131
1440
|
toolCall,
|
|
1132
1441
|
toolName: toolCall.toolName,
|
|
1133
1442
|
internalCallId,
|
|
1134
|
-
args
|
|
1135
|
-
...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
|
|
1136
|
-
...toolDefinition === void 0 ? {} : { toolDefinition },
|
|
1137
|
-
...toolMetadata === void 0 ? {} : { toolMetadata }
|
|
1443
|
+
args
|
|
1138
1444
|
};
|
|
1445
|
+
if (toolCall.callId !== void 0) {
|
|
1446
|
+
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1447
|
+
}
|
|
1448
|
+
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1449
|
+
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1139
1450
|
const toolObservers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1140
1451
|
const toolObservation = new ToolObserverScope(toolObservers);
|
|
1141
1452
|
let output;
|
|
@@ -1176,6 +1487,38 @@ var ToolCallExecutor = class {
|
|
|
1176
1487
|
output = outcome.output;
|
|
1177
1488
|
toolExecutionFailed = outcome.failed;
|
|
1178
1489
|
}
|
|
1490
|
+
if (prepared !== void 0 && isQuestionTool(tool)) {
|
|
1491
|
+
try {
|
|
1492
|
+
const questions = parseAgentQuestionPrompts(
|
|
1493
|
+
prepared.input.questions
|
|
1494
|
+
);
|
|
1495
|
+
const interaction = {
|
|
1496
|
+
type: "tool-question",
|
|
1497
|
+
id: globalThis.crypto.randomUUID(),
|
|
1498
|
+
toolName: toolCall.toolName,
|
|
1499
|
+
toolCallId: toolCall.toolCallId,
|
|
1500
|
+
internalCallId,
|
|
1501
|
+
questions
|
|
1502
|
+
};
|
|
1503
|
+
if (toolCall.callId !== void 0) {
|
|
1504
|
+
Object.assign(interaction, { callId: toolCall.callId });
|
|
1505
|
+
}
|
|
1506
|
+
throw new AgentInteractionSignal(interaction);
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
if (error instanceof AgentInteractionSignal) throw error;
|
|
1509
|
+
const outcome = await this.handleToolError(
|
|
1510
|
+
toolCall,
|
|
1511
|
+
hookArgs,
|
|
1512
|
+
effectiveArgs,
|
|
1513
|
+
error,
|
|
1514
|
+
toolObservation,
|
|
1515
|
+
observation
|
|
1516
|
+
);
|
|
1517
|
+
output = outcome.output;
|
|
1518
|
+
toolExecutionFailed = outcome.failed;
|
|
1519
|
+
prepared = void 0;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1179
1522
|
if (prepared !== void 0) {
|
|
1180
1523
|
const approvalContext = createApprovalContext(
|
|
1181
1524
|
prepared.input,
|
|
@@ -1195,9 +1538,11 @@ var ToolCallExecutor = class {
|
|
|
1195
1538
|
runId: this.runContext.runId,
|
|
1196
1539
|
step,
|
|
1197
1540
|
toolName: toolCall.toolName,
|
|
1198
|
-
input: lifecycleSnapshot(prepared.input)
|
|
1199
|
-
...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
|
|
1541
|
+
input: lifecycleSnapshot(prepared.input)
|
|
1200
1542
|
};
|
|
1543
|
+
if (toolCall.callId !== void 0) {
|
|
1544
|
+
Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
|
|
1545
|
+
}
|
|
1201
1546
|
await this.lifecycle?.onToolStart?.(lifecycleEvent);
|
|
1202
1547
|
const startedAt = Date.now();
|
|
1203
1548
|
const outcome = await this.runApprovedToolCall(
|
|
@@ -1228,6 +1573,13 @@ var ToolCallExecutor = class {
|
|
|
1228
1573
|
}
|
|
1229
1574
|
}
|
|
1230
1575
|
} catch (error) {
|
|
1576
|
+
if (error instanceof AgentInteractionSignal) {
|
|
1577
|
+
await toolObservation.suspend({
|
|
1578
|
+
...toolStartArgs,
|
|
1579
|
+
interaction: error.interaction
|
|
1580
|
+
});
|
|
1581
|
+
throw error;
|
|
1582
|
+
}
|
|
1231
1583
|
await toolObservation.error(
|
|
1232
1584
|
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1233
1585
|
);
|
|
@@ -1286,39 +1638,316 @@ var ToolCallExecutor = class {
|
|
|
1286
1638
|
args: effectiveArgs,
|
|
1287
1639
|
output,
|
|
1288
1640
|
result,
|
|
1289
|
-
structuredResult
|
|
1290
|
-
...toolCall.callId === void 0 ? {} : { callId: toolCall.callId }
|
|
1641
|
+
structuredResult
|
|
1291
1642
|
};
|
|
1643
|
+
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1292
1644
|
onResult?.(resultPayload);
|
|
1293
|
-
|
|
1645
|
+
let resultPart = {
|
|
1294
1646
|
type: "tool-result",
|
|
1295
1647
|
toolCallId: toolCall.toolCallId,
|
|
1296
1648
|
toolName: toolCall.toolName,
|
|
1297
|
-
output
|
|
1298
|
-
...toolCall.callId === void 0 ? {} : { callId: toolCall.callId }
|
|
1649
|
+
output
|
|
1299
1650
|
};
|
|
1651
|
+
if (toolCall.callId !== void 0) {
|
|
1652
|
+
resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1653
|
+
}
|
|
1654
|
+
return resultPart;
|
|
1300
1655
|
} catch (error) {
|
|
1656
|
+
if (error instanceof AgentInteractionSignal) {
|
|
1657
|
+
const pending = {
|
|
1658
|
+
toolCall,
|
|
1659
|
+
effectiveArgs,
|
|
1660
|
+
input: error.interaction.type === "tool-approval" ? error.interaction.input : parseToolArgs(effectiveArgs),
|
|
1661
|
+
internalCallId
|
|
1662
|
+
};
|
|
1663
|
+
if (error.rejectMessage !== void 0) pending.rejectMessage = error.rejectMessage;
|
|
1664
|
+
throw new ToolExecutionSuspension(error.interaction, pending);
|
|
1665
|
+
}
|
|
1301
1666
|
await toolObservation.error(
|
|
1302
1667
|
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1303
1668
|
);
|
|
1304
1669
|
throw error;
|
|
1305
1670
|
}
|
|
1306
|
-
}
|
|
1671
|
+
};
|
|
1672
|
+
if (this.concurrency === 1) {
|
|
1673
|
+
const results = [];
|
|
1674
|
+
for (const toolCall of toolCalls) {
|
|
1675
|
+
try {
|
|
1676
|
+
results.push(await executeOne(toolCall));
|
|
1677
|
+
} catch (error) {
|
|
1678
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
1679
|
+
error.completedResults = [...results];
|
|
1680
|
+
error.remainingToolCalls = toolCalls.slice(results.length + 1);
|
|
1681
|
+
}
|
|
1682
|
+
throw error;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
return results;
|
|
1686
|
+
}
|
|
1687
|
+
return mapWithConcurrency(toolCalls, this.concurrency, executeOne);
|
|
1688
|
+
}
|
|
1689
|
+
async executeResumed(pending, onResult, onStreamEvent, observation) {
|
|
1690
|
+
throwIfAborted(this.abortSignal);
|
|
1691
|
+
const { toolCall, internalCallId, effectiveArgs } = pending;
|
|
1692
|
+
const tool = this.agent.getTool(toolCall.toolName);
|
|
1693
|
+
if (tool === void 0) {
|
|
1694
|
+
throw new Error(
|
|
1695
|
+
`Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
|
|
1696
|
+
);
|
|
1697
|
+
}
|
|
1698
|
+
if (isQuestionTool(tool)) {
|
|
1699
|
+
throw new TypeError("Question interactions are resolved from their submitted answers.");
|
|
1700
|
+
}
|
|
1701
|
+
const hookArgs = {
|
|
1702
|
+
toolName: toolCall.toolName,
|
|
1703
|
+
toolCallId: toolCall.toolCallId,
|
|
1704
|
+
internalCallId,
|
|
1705
|
+
args: effectiveArgs
|
|
1706
|
+
};
|
|
1707
|
+
if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
|
|
1708
|
+
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1709
|
+
(definition) => definition.name === toolCall.toolName
|
|
1710
|
+
);
|
|
1711
|
+
const toolMetadata = toolTraceMetadata(tool);
|
|
1712
|
+
let toolStartArgs = {
|
|
1713
|
+
turn: observation?.turn ?? 0,
|
|
1714
|
+
toolCall,
|
|
1715
|
+
toolName: toolCall.toolName,
|
|
1716
|
+
internalCallId,
|
|
1717
|
+
args: effectiveArgs
|
|
1718
|
+
};
|
|
1719
|
+
if (toolCall.callId !== void 0) {
|
|
1720
|
+
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1721
|
+
}
|
|
1722
|
+
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1723
|
+
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1724
|
+
const observers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1725
|
+
const toolObservation = new ToolObserverScope(observers);
|
|
1726
|
+
let output;
|
|
1727
|
+
let failed = false;
|
|
1728
|
+
try {
|
|
1729
|
+
const prepared = prepareToolCallFromInput(tool, pending.input);
|
|
1730
|
+
const step = observation?.turn ?? 0;
|
|
1731
|
+
const lifecycleEvent = {
|
|
1732
|
+
runId: this.runContext.runId,
|
|
1733
|
+
step,
|
|
1734
|
+
toolName: toolCall.toolName,
|
|
1735
|
+
input: lifecycleSnapshot(prepared.input)
|
|
1736
|
+
};
|
|
1737
|
+
if (toolCall.callId !== void 0) {
|
|
1738
|
+
Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
|
|
1739
|
+
}
|
|
1740
|
+
await this.lifecycle?.onToolStart?.(lifecycleEvent);
|
|
1741
|
+
const startedAt = Date.now();
|
|
1742
|
+
const outcome = await this.runApprovedToolCall(
|
|
1743
|
+
prepared,
|
|
1744
|
+
toolCall,
|
|
1745
|
+
hookArgs,
|
|
1746
|
+
effectiveArgs,
|
|
1747
|
+
toolObservation,
|
|
1748
|
+
observation,
|
|
1749
|
+
onStreamEvent
|
|
1750
|
+
);
|
|
1751
|
+
output = outcome.output;
|
|
1752
|
+
failed = outcome.failed;
|
|
1753
|
+
const durationMs = Date.now() - startedAt;
|
|
1754
|
+
await this.lifecycle?.onToolFinish?.(
|
|
1755
|
+
outcome.failed ? {
|
|
1756
|
+
...lifecycleEvent,
|
|
1757
|
+
durationMs,
|
|
1758
|
+
success: false,
|
|
1759
|
+
error: lifecycleSnapshot(outcome.error)
|
|
1760
|
+
} : {
|
|
1761
|
+
...lifecycleEvent,
|
|
1762
|
+
durationMs,
|
|
1763
|
+
success: true,
|
|
1764
|
+
output: lifecycleSnapshot(output)
|
|
1765
|
+
}
|
|
1766
|
+
);
|
|
1767
|
+
let result = toolOutputToText(output);
|
|
1768
|
+
let structuredResult = toolOutputToStructuredResult(output);
|
|
1769
|
+
if (!isSkillTool(tool)) {
|
|
1770
|
+
const replacement = await this.runToolResultMiddlewares({
|
|
1771
|
+
...hookArgs,
|
|
1772
|
+
args: effectiveArgs,
|
|
1773
|
+
result,
|
|
1774
|
+
originalResult: result,
|
|
1775
|
+
structuredResult,
|
|
1776
|
+
originalStructuredResult: structuredResult,
|
|
1777
|
+
turn: step
|
|
1778
|
+
});
|
|
1779
|
+
if (replacement !== void 0) {
|
|
1780
|
+
output = replacement;
|
|
1781
|
+
result = toolOutputToText(replacement);
|
|
1782
|
+
structuredResult = toolOutputToStructuredResult(replacement);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
const resultAction = await this.activeHook?.onToolResult?.({
|
|
1786
|
+
...hookArgs,
|
|
1787
|
+
result,
|
|
1788
|
+
structuredResult,
|
|
1789
|
+
run: runControl
|
|
1790
|
+
});
|
|
1791
|
+
if (!failed) {
|
|
1792
|
+
await toolObservation.end({
|
|
1793
|
+
turn: step,
|
|
1794
|
+
toolCall,
|
|
1795
|
+
toolName: toolCall.toolName,
|
|
1796
|
+
internalCallId,
|
|
1797
|
+
args: effectiveArgs,
|
|
1798
|
+
result,
|
|
1799
|
+
structuredResult,
|
|
1800
|
+
skipped: false,
|
|
1801
|
+
toolCallId: toolCall.callId
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
if (resultAction?.type === "terminate") {
|
|
1805
|
+
throw this.cancel(resultAction.reason);
|
|
1806
|
+
}
|
|
1807
|
+
const resultPayload = {
|
|
1808
|
+
type: "tool_result",
|
|
1809
|
+
toolName: toolCall.toolName,
|
|
1810
|
+
toolCallId: toolCall.toolCallId,
|
|
1811
|
+
internalCallId,
|
|
1812
|
+
args: effectiveArgs,
|
|
1813
|
+
output,
|
|
1814
|
+
result,
|
|
1815
|
+
structuredResult
|
|
1816
|
+
};
|
|
1817
|
+
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1818
|
+
onResult?.(resultPayload);
|
|
1819
|
+
let resultPart = {
|
|
1820
|
+
type: "tool-result",
|
|
1821
|
+
toolName: toolCall.toolName,
|
|
1822
|
+
toolCallId: toolCall.toolCallId,
|
|
1823
|
+
output
|
|
1824
|
+
};
|
|
1825
|
+
if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1826
|
+
return resultPart;
|
|
1827
|
+
} catch (error) {
|
|
1828
|
+
await toolObservation.error(
|
|
1829
|
+
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1830
|
+
);
|
|
1831
|
+
throw error;
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
async resolveResumed(pending, initialOutput, onResult, observation) {
|
|
1835
|
+
throwIfAborted(this.abortSignal);
|
|
1836
|
+
const { toolCall, internalCallId, effectiveArgs } = pending;
|
|
1837
|
+
const tool = this.agent.getTool(toolCall.toolName);
|
|
1838
|
+
if (tool === void 0) {
|
|
1839
|
+
throw new Error(
|
|
1840
|
+
`Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
const hookArgs = {
|
|
1844
|
+
toolName: toolCall.toolName,
|
|
1845
|
+
toolCallId: toolCall.toolCallId,
|
|
1846
|
+
internalCallId,
|
|
1847
|
+
args: effectiveArgs
|
|
1848
|
+
};
|
|
1849
|
+
if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
|
|
1850
|
+
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1851
|
+
(definition) => definition.name === toolCall.toolName
|
|
1852
|
+
);
|
|
1853
|
+
const toolMetadata = toolTraceMetadata(tool);
|
|
1854
|
+
let toolStartArgs = {
|
|
1855
|
+
turn: observation?.turn ?? 0,
|
|
1856
|
+
toolCall,
|
|
1857
|
+
toolName: toolCall.toolName,
|
|
1858
|
+
internalCallId,
|
|
1859
|
+
args: effectiveArgs
|
|
1860
|
+
};
|
|
1861
|
+
if (toolCall.callId !== void 0) {
|
|
1862
|
+
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1863
|
+
}
|
|
1864
|
+
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1865
|
+
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1866
|
+
const observers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1867
|
+
const toolObservation = new ToolObserverScope(observers);
|
|
1868
|
+
try {
|
|
1869
|
+
let output = initialOutput;
|
|
1870
|
+
let result = toolOutputToText(output);
|
|
1871
|
+
let structuredResult = toolOutputToStructuredResult(output);
|
|
1872
|
+
if (!isSkillTool(tool)) {
|
|
1873
|
+
const replacement = await this.runToolResultMiddlewares({
|
|
1874
|
+
...hookArgs,
|
|
1875
|
+
args: effectiveArgs,
|
|
1876
|
+
result,
|
|
1877
|
+
originalResult: result,
|
|
1878
|
+
structuredResult,
|
|
1879
|
+
originalStructuredResult: structuredResult,
|
|
1880
|
+
turn: observation?.turn ?? 0
|
|
1881
|
+
});
|
|
1882
|
+
if (replacement !== void 0) {
|
|
1883
|
+
output = replacement;
|
|
1884
|
+
result = toolOutputToText(replacement);
|
|
1885
|
+
structuredResult = toolOutputToStructuredResult(replacement);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
const resultAction = await this.activeHook?.onToolResult?.({
|
|
1889
|
+
...hookArgs,
|
|
1890
|
+
result,
|
|
1891
|
+
structuredResult,
|
|
1892
|
+
run: runControl
|
|
1893
|
+
});
|
|
1894
|
+
await toolObservation.end({
|
|
1895
|
+
turn: observation?.turn ?? 0,
|
|
1896
|
+
toolCall,
|
|
1897
|
+
toolName: toolCall.toolName,
|
|
1898
|
+
internalCallId,
|
|
1899
|
+
args: effectiveArgs,
|
|
1900
|
+
result,
|
|
1901
|
+
structuredResult,
|
|
1902
|
+
skipped: true,
|
|
1903
|
+
toolCallId: toolCall.callId
|
|
1904
|
+
});
|
|
1905
|
+
if (resultAction?.type === "terminate") {
|
|
1906
|
+
throw this.cancel(resultAction.reason);
|
|
1907
|
+
}
|
|
1908
|
+
const resultPayload = {
|
|
1909
|
+
type: "tool_result",
|
|
1910
|
+
toolName: toolCall.toolName,
|
|
1911
|
+
toolCallId: toolCall.toolCallId,
|
|
1912
|
+
internalCallId,
|
|
1913
|
+
args: effectiveArgs,
|
|
1914
|
+
output,
|
|
1915
|
+
result,
|
|
1916
|
+
structuredResult
|
|
1917
|
+
};
|
|
1918
|
+
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1919
|
+
onResult?.(resultPayload);
|
|
1920
|
+
let resultPart = {
|
|
1921
|
+
type: "tool-result",
|
|
1922
|
+
toolName: toolCall.toolName,
|
|
1923
|
+
toolCallId: toolCall.toolCallId,
|
|
1924
|
+
output
|
|
1925
|
+
};
|
|
1926
|
+
if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1927
|
+
return resultPart;
|
|
1928
|
+
} catch (error) {
|
|
1929
|
+
await toolObservation.error(
|
|
1930
|
+
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1931
|
+
);
|
|
1932
|
+
throw error;
|
|
1933
|
+
}
|
|
1307
1934
|
}
|
|
1308
1935
|
async runApprovedToolCall(prepared, toolCall, hookArgs, effectiveArgs, toolObservation, observation, onStreamEvent) {
|
|
1309
1936
|
try {
|
|
1310
1937
|
const toolContext = {
|
|
1311
1938
|
abortSignal: this.abortSignal,
|
|
1312
1939
|
emitStreamEvent: async (event) => {
|
|
1313
|
-
|
|
1940
|
+
let streamEventArgs = {
|
|
1314
1941
|
turn: observation?.turn ?? 0,
|
|
1315
1942
|
toolCall,
|
|
1316
1943
|
toolName: toolCall.toolName,
|
|
1317
1944
|
internalCallId: hookArgs.internalCallId,
|
|
1318
1945
|
args: effectiveArgs,
|
|
1319
|
-
event
|
|
1320
|
-
...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
|
|
1946
|
+
event
|
|
1321
1947
|
};
|
|
1948
|
+
if (toolCall.callId !== void 0) {
|
|
1949
|
+
streamEventArgs = { ...streamEventArgs, toolCallId: toolCall.callId };
|
|
1950
|
+
}
|
|
1322
1951
|
await toolObservation.streamEvent(streamEventArgs);
|
|
1323
1952
|
const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);
|
|
1324
1953
|
if (payload !== void 0) {
|
|
@@ -1442,6 +2071,9 @@ var ToolCallExecutor = class {
|
|
|
1442
2071
|
try {
|
|
1443
2072
|
decision = await this.approvalHandler(request);
|
|
1444
2073
|
} catch (error) {
|
|
2074
|
+
if (error instanceof AgentInteractionSignal) {
|
|
2075
|
+
throw error;
|
|
2076
|
+
}
|
|
1445
2077
|
await observation?.runObservers.event({
|
|
1446
2078
|
name: "tool.approval_failed",
|
|
1447
2079
|
level: "ERROR",
|
|
@@ -1452,13 +2084,14 @@ var ToolCallExecutor = class {
|
|
|
1452
2084
|
});
|
|
1453
2085
|
throw error;
|
|
1454
2086
|
}
|
|
2087
|
+
const attributes = {
|
|
2088
|
+
...approvalEventAttributes(request, observation?.turn ?? 0),
|
|
2089
|
+
approved: decision.approved
|
|
2090
|
+
};
|
|
2091
|
+
if (decision.reason !== void 0) attributes.decisionReason = decision.reason;
|
|
1455
2092
|
await observation?.runObservers.event({
|
|
1456
2093
|
name: "tool.approval_resolved",
|
|
1457
|
-
attributes
|
|
1458
|
-
...approvalEventAttributes(request, observation.turn),
|
|
1459
|
-
approved: decision.approved,
|
|
1460
|
-
...decision.reason === void 0 ? {} : { decisionReason: decision.reason }
|
|
1461
|
-
}
|
|
2094
|
+
attributes
|
|
1462
2095
|
});
|
|
1463
2096
|
if (decision.approved) {
|
|
1464
2097
|
return { approved: true };
|
|
@@ -1484,11 +2117,12 @@ function createApprovalContext(input, hookArgs, agent, run) {
|
|
|
1484
2117
|
toolName: hookArgs.toolName,
|
|
1485
2118
|
args: lifecycleSnapshot(input),
|
|
1486
2119
|
rawArgs: hookArgs.args,
|
|
2120
|
+
toolCallId: hookArgs.toolCallId,
|
|
1487
2121
|
internalCallId: hookArgs.internalCallId,
|
|
1488
2122
|
run: approvalRun
|
|
1489
2123
|
};
|
|
1490
|
-
if (hookArgs.
|
|
1491
|
-
context.
|
|
2124
|
+
if (hookArgs.callId !== void 0) {
|
|
2125
|
+
context.callId = hookArgs.callId;
|
|
1492
2126
|
}
|
|
1493
2127
|
return context;
|
|
1494
2128
|
}
|
|
@@ -1522,15 +2156,17 @@ function toolTraceMetadata(tool) {
|
|
|
1522
2156
|
return result;
|
|
1523
2157
|
}
|
|
1524
2158
|
function toolErrorArgs(turn, toolCall, internalCallId, args, error) {
|
|
1525
|
-
|
|
2159
|
+
let observerArgs = {
|
|
1526
2160
|
turn,
|
|
1527
2161
|
toolCall,
|
|
1528
2162
|
toolName: toolCall.toolName,
|
|
1529
2163
|
internalCallId,
|
|
1530
2164
|
args,
|
|
1531
|
-
error
|
|
1532
|
-
...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
|
|
2165
|
+
error
|
|
1533
2166
|
};
|
|
2167
|
+
if (toolCall.callId !== void 0) {
|
|
2168
|
+
observerArgs = { ...observerArgs, toolCallId: toolCall.callId };
|
|
2169
|
+
}
|
|
1534
2170
|
return observerArgs;
|
|
1535
2171
|
}
|
|
1536
2172
|
var ToolObserverScope = class {
|
|
@@ -1547,6 +2183,11 @@ var ToolObserverScope = class {
|
|
|
1547
2183
|
this.terminal = true;
|
|
1548
2184
|
await this.observers?.end(args);
|
|
1549
2185
|
}
|
|
2186
|
+
async suspend(args) {
|
|
2187
|
+
if (this.terminal) return;
|
|
2188
|
+
this.terminal = true;
|
|
2189
|
+
await this.observers?.suspend(args);
|
|
2190
|
+
}
|
|
1550
2191
|
async error(args) {
|
|
1551
2192
|
if (this.terminal) return;
|
|
1552
2193
|
this.terminal = true;
|
|
@@ -1591,14 +2232,6 @@ function agentToolEventPayload(toolCall, internalCallId, event) {
|
|
|
1591
2232
|
}
|
|
1592
2233
|
|
|
1593
2234
|
// src/internal/agent-runtime/agent-run.ts
|
|
1594
|
-
function deferredSignal() {
|
|
1595
|
-
let resolve = () => {
|
|
1596
|
-
};
|
|
1597
|
-
const promise = new Promise((done) => {
|
|
1598
|
-
resolve = done;
|
|
1599
|
-
});
|
|
1600
|
-
return { promise, resolve };
|
|
1601
|
-
}
|
|
1602
2235
|
async function settleFailureCleanup(operations) {
|
|
1603
2236
|
for (const operation of operations) {
|
|
1604
2237
|
try {
|
|
@@ -1627,13 +2260,26 @@ var AgentRun = class _AgentRun {
|
|
|
1627
2260
|
options.toolConcurrency ?? 1,
|
|
1628
2261
|
"toolConcurrency"
|
|
1629
2262
|
);
|
|
1630
|
-
this.concurrency = this.activeHook !== void 0 || agent.tools.some(
|
|
2263
|
+
this.concurrency = this.activeHook !== void 0 || agent.tools.some(
|
|
2264
|
+
(tool) => toolMayRequireApproval(tool.requiresApproval) || isQuestionTool(tool)
|
|
2265
|
+
) ? 1 : configuredConcurrency;
|
|
1631
2266
|
this.traceOptions = options.trace;
|
|
1632
2267
|
const retrySetting = options.retries === void 0 ? agent.retries : options.retries;
|
|
1633
2268
|
this.completionRetryOptions = retrySetting === void 0 || retrySetting === false ? void 0 : resolveRetryOptions(retrySetting);
|
|
1634
2269
|
this.requestMiddlewares = [...options.middlewares ?? []];
|
|
1635
2270
|
this.memoryScope = options.memoryScope;
|
|
1636
2271
|
this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);
|
|
2272
|
+
this.continuationState = options.continuationState;
|
|
2273
|
+
this.interactionResponse = options.interactionResponse;
|
|
2274
|
+
if (options.continuationState !== void 0) {
|
|
2275
|
+
this.steeringMessages.push(
|
|
2276
|
+
...options.continuationState.steering.map((entry) => ({
|
|
2277
|
+
id: entry.id,
|
|
2278
|
+
messages: [...entry.messages]
|
|
2279
|
+
}))
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
this.resumedFrom = options.sourceRunId === void 0 || options.interactionId === void 0 ? void 0 : { runId: options.sourceRunId, interactionId: options.interactionId };
|
|
1637
2283
|
this.linkExternalAbortSignal(options.abortSignal);
|
|
1638
2284
|
}
|
|
1639
2285
|
agent;
|
|
@@ -1655,52 +2301,39 @@ var AgentRun = class _AgentRun {
|
|
|
1655
2301
|
onInternalFailure;
|
|
1656
2302
|
onInternalMemoryCompaction;
|
|
1657
2303
|
memoryCompaction;
|
|
1658
|
-
pendingApproval;
|
|
1659
|
-
approvalSignal = deferredSignal();
|
|
1660
|
-
activeRunId;
|
|
1661
2304
|
requestedRunId;
|
|
1662
|
-
|
|
2305
|
+
continuationState;
|
|
2306
|
+
interactionResponse;
|
|
2307
|
+
resumedFrom;
|
|
1663
2308
|
currentMessages = [];
|
|
1664
2309
|
cancellationError;
|
|
1665
2310
|
activeGeneration;
|
|
1666
2311
|
abortController = new AbortController();
|
|
1667
2312
|
removeExternalAbortListener;
|
|
1668
2313
|
static fromAgent(agent, options) {
|
|
1669
|
-
const normalized = normalizeAgentInput(options);
|
|
2314
|
+
const normalized = normalizeAgentInput(agent.id, options);
|
|
1670
2315
|
if (normalized.scope !== void 0 && agent.memory === void 0) {
|
|
1671
2316
|
throw new TypeError(`Agent "${agent.id}" cannot use a session without a memory store.`);
|
|
1672
2317
|
}
|
|
1673
2318
|
return new _AgentRun(agent, normalized.prompt, normalized.history, {
|
|
1674
2319
|
...options,
|
|
1675
|
-
memoryScope: normalized.scope
|
|
2320
|
+
memoryScope: normalized.scope,
|
|
2321
|
+
continuationState: normalized.continuationState,
|
|
2322
|
+
interactionResponse: normalized.interactionResponse,
|
|
2323
|
+
sourceRunId: normalized.sourceRunId,
|
|
2324
|
+
interactionId: normalized.interactionId
|
|
1676
2325
|
});
|
|
1677
2326
|
}
|
|
1678
2327
|
steer(input) {
|
|
1679
2328
|
if (this.isTerminal() || this.cancellationError !== void 0) {
|
|
1680
|
-
|
|
1681
|
-
}
|
|
1682
|
-
this.steeringMessages.push(...normalizeSteeringInput(input));
|
|
1683
|
-
return true;
|
|
1684
|
-
}
|
|
1685
|
-
waitForApproval() {
|
|
1686
|
-
return this.pendingApproval === void 0 ? this.approvalSignal.promise : Promise.resolve();
|
|
1687
|
-
}
|
|
1688
|
-
approvalResult() {
|
|
1689
|
-
const snapshot = this.approvalSnapshot();
|
|
1690
|
-
return { status: "approval_required", ...snapshot };
|
|
1691
|
-
}
|
|
1692
|
-
approvalEvent() {
|
|
1693
|
-
const snapshot = this.approvalSnapshot();
|
|
1694
|
-
return { type: "approval_required", ...snapshot };
|
|
1695
|
-
}
|
|
1696
|
-
resolveApproval(decision) {
|
|
1697
|
-
const pending = this.pendingApproval;
|
|
1698
|
-
if (pending === void 0) {
|
|
1699
|
-
throw new TypeError("Agent run has no pending tool approval.");
|
|
2329
|
+
throw new AgentStreamClosedError();
|
|
1700
2330
|
}
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
2331
|
+
const receipt = Object.freeze({
|
|
2332
|
+
id: globalThis.crypto.randomUUID(),
|
|
2333
|
+
status: "queued"
|
|
2334
|
+
});
|
|
2335
|
+
this.steeringMessages.push({ id: receipt.id, messages: normalizeSteeringInput(input) });
|
|
2336
|
+
return receipt;
|
|
1704
2337
|
}
|
|
1705
2338
|
cancel(reason) {
|
|
1706
2339
|
if (this.isTerminal() || this.cancellationError !== void 0) {
|
|
@@ -1713,35 +2346,33 @@ var AgentRun = class _AgentRun {
|
|
|
1713
2346
|
setCancellationError(error) {
|
|
1714
2347
|
this.cancellationError = error;
|
|
1715
2348
|
if (!this.abortController.signal.aborted) this.abortController.abort(error);
|
|
1716
|
-
const pending = this.pendingApproval;
|
|
1717
|
-
if (pending !== void 0) {
|
|
1718
|
-
this.pendingApproval = void 0;
|
|
1719
|
-
this.approvalSignal = deferredSignal();
|
|
1720
|
-
pending.reject(error);
|
|
1721
|
-
}
|
|
1722
2349
|
}
|
|
1723
2350
|
async generate() {
|
|
1724
2351
|
this.startRun();
|
|
1725
2352
|
const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
|
|
1726
|
-
this.activeRunId = runId;
|
|
1727
2353
|
let usage = Usage.empty();
|
|
1728
2354
|
let currentTurns = 0;
|
|
1729
2355
|
let lastPrompt = this.promptMessage;
|
|
1730
2356
|
let newMessages = [this.promptMessage];
|
|
1731
2357
|
let runObservers;
|
|
2358
|
+
let pendingTurnMessages = [];
|
|
1732
2359
|
try {
|
|
1733
2360
|
this.throwIfCancelled();
|
|
1734
|
-
const memoryPreparation = await this.memoryRecorder.prepareHistory(
|
|
2361
|
+
const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
|
|
1735
2362
|
runId,
|
|
1736
2363
|
newMessages.length,
|
|
1737
2364
|
this.abortController.signal
|
|
1738
|
-
);
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
2365
|
+
) : void 0;
|
|
2366
|
+
if (memoryPreparation !== void 0) {
|
|
2367
|
+
this.chatHistory = memoryPreparation.history;
|
|
2368
|
+
usage = Usage.add(usage, memoryPreparation.usage);
|
|
2369
|
+
this.memoryCompaction = memoryPreparation.compaction;
|
|
2370
|
+
await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
|
|
2371
|
+
}
|
|
1743
2372
|
runObservers = await this.startRunObservers(runId);
|
|
1744
|
-
|
|
2373
|
+
if (memoryPreparation !== void 0) {
|
|
2374
|
+
await this.recordMemoryCompaction(memoryPreparation, runObservers);
|
|
2375
|
+
}
|
|
1745
2376
|
this.throwIfCancelled();
|
|
1746
2377
|
await this.activeLifecycle?.onStart?.({
|
|
1747
2378
|
runId,
|
|
@@ -1749,39 +2380,84 @@ var AgentRun = class _AgentRun {
|
|
|
1749
2380
|
history: lifecycleSnapshot(this.chatHistory),
|
|
1750
2381
|
maxTurns: this.maxTurnCount
|
|
1751
2382
|
});
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
2383
|
+
if (this.continuationState === void 0) {
|
|
2384
|
+
const inputResult = await runInputGuardrails(this.guardrailPolicies, {
|
|
2385
|
+
prompt: this.promptMessage,
|
|
2386
|
+
history: this.chatHistory,
|
|
2387
|
+
inputText: textFromMessage(this.promptMessage),
|
|
2388
|
+
run: this.guardrailRunContext(runId)
|
|
2389
|
+
});
|
|
2390
|
+
for (const decision of inputResult.decisions) {
|
|
2391
|
+
await this.recordGuardrailDecision(decision, runObservers);
|
|
2392
|
+
}
|
|
2393
|
+
this.promptMessage = inputResult.prompt;
|
|
2394
|
+
if (inputResult.blocked) {
|
|
2395
|
+
const text = inputResult.message ?? "The request was blocked by a guardrail.";
|
|
2396
|
+
const result = {
|
|
2397
|
+
status: "blocked",
|
|
2398
|
+
stage: "input",
|
|
2399
|
+
runId,
|
|
2400
|
+
text,
|
|
2401
|
+
usage,
|
|
2402
|
+
messages: [this.promptMessage, { role: "assistant", content: text }],
|
|
2403
|
+
trace: runObservers.trace,
|
|
2404
|
+
guardrails: [...this.guardrailDecisions],
|
|
2405
|
+
...this.memoryCompactionResult()
|
|
2406
|
+
};
|
|
2407
|
+
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
2408
|
+
this.runState = "closing";
|
|
2409
|
+
await this.runLifecycleFinish(result);
|
|
2410
|
+
await runObservers.end(result);
|
|
2411
|
+
this.runState = "completed";
|
|
2412
|
+
this.disposeAbortLink();
|
|
2413
|
+
return result;
|
|
2414
|
+
}
|
|
1780
2415
|
}
|
|
1781
2416
|
newMessages = [this.promptMessage];
|
|
1782
2417
|
await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
|
|
1783
|
-
|
|
2418
|
+
pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
|
|
1784
2419
|
await this.runRunStartHook(newMessages);
|
|
2420
|
+
if (this.continuationState !== void 0) {
|
|
2421
|
+
await runObservers.event({
|
|
2422
|
+
name: "agent.interaction_response",
|
|
2423
|
+
attributes: {
|
|
2424
|
+
sourceRunId: this.resumedFrom?.runId,
|
|
2425
|
+
interactionId: this.resumedFrom?.interactionId,
|
|
2426
|
+
interactionType: this.interactionResponse?.type
|
|
2427
|
+
}
|
|
2428
|
+
});
|
|
2429
|
+
try {
|
|
2430
|
+
const toolResults = await this.resolveContinuationTools(
|
|
2431
|
+
runId,
|
|
2432
|
+
newMessages,
|
|
2433
|
+
void 0,
|
|
2434
|
+
void 0,
|
|
2435
|
+
{
|
|
2436
|
+
turn: 1,
|
|
2437
|
+
runObservers
|
|
2438
|
+
}
|
|
2439
|
+
);
|
|
2440
|
+
const toolMessage = { role: "tool", content: toolResults };
|
|
2441
|
+
newMessages.push(toolMessage);
|
|
2442
|
+
await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
|
|
2443
|
+
await this.drainSteeringMessages(runId, 1, newMessages, pendingTurnMessages);
|
|
2444
|
+
await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
|
|
2445
|
+
} catch (error) {
|
|
2446
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
2447
|
+
return this.finishSuspension({
|
|
2448
|
+
runId,
|
|
2449
|
+
turn: 1,
|
|
2450
|
+
usage,
|
|
2451
|
+
newMessages,
|
|
2452
|
+
pendingTurnMessages,
|
|
2453
|
+
runObservers,
|
|
2454
|
+
suspension: error,
|
|
2455
|
+
uncommittedMessages: []
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
throw error;
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
1785
2461
|
while (currentTurns <= this.maxTurnCount + 1) {
|
|
1786
2462
|
const prompt = newMessages.at(-1);
|
|
1787
2463
|
if (prompt === void 0) {
|
|
@@ -1804,7 +2480,7 @@ var AgentRun = class _AgentRun {
|
|
|
1804
2480
|
}
|
|
1805
2481
|
response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
|
|
1806
2482
|
usage = Usage.add(usage, response.usage);
|
|
1807
|
-
this.
|
|
2483
|
+
this.updateRunProgress(newMessages);
|
|
1808
2484
|
await this.runCompletionResponseHook(prompt, response, newMessages);
|
|
1809
2485
|
await this.runTurnEndHook(currentTurns, response, newMessages);
|
|
1810
2486
|
await this.activeLifecycle?.onStepFinish?.({
|
|
@@ -1827,7 +2503,20 @@ var AgentRun = class _AgentRun {
|
|
|
1827
2503
|
pendingTurnMessages
|
|
1828
2504
|
);
|
|
1829
2505
|
}
|
|
1830
|
-
|
|
2506
|
+
const appliedSteering = await this.drainSteeringMessages(
|
|
2507
|
+
runId,
|
|
2508
|
+
currentTurns,
|
|
2509
|
+
newMessages,
|
|
2510
|
+
pendingTurnMessages,
|
|
2511
|
+
{ closeWhenEmpty: true }
|
|
2512
|
+
);
|
|
2513
|
+
if (appliedSteering.length > 0) {
|
|
2514
|
+
for (const receipt of appliedSteering) {
|
|
2515
|
+
await runObservers.event({
|
|
2516
|
+
name: "agent.steering_applied",
|
|
2517
|
+
attributes: { id: receipt.id, turn: currentTurns }
|
|
2518
|
+
});
|
|
2519
|
+
}
|
|
1831
2520
|
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
1832
2521
|
continue;
|
|
1833
2522
|
}
|
|
@@ -1870,19 +2559,36 @@ var AgentRun = class _AgentRun {
|
|
|
1870
2559
|
this.disposeAbortLink();
|
|
1871
2560
|
return result;
|
|
1872
2561
|
}
|
|
1873
|
-
this.
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
2562
|
+
this.updateRunProgress(newMessages);
|
|
2563
|
+
let toolResults;
|
|
2564
|
+
try {
|
|
2565
|
+
toolResults = await this.executeToolCalls(
|
|
2566
|
+
runId,
|
|
2567
|
+
toolCalls,
|
|
2568
|
+
newMessages,
|
|
2569
|
+
void 0,
|
|
2570
|
+
void 0,
|
|
2571
|
+
{
|
|
2572
|
+
turn: currentTurns,
|
|
2573
|
+
runObservers,
|
|
2574
|
+
toolDefinitions: request.tools
|
|
2575
|
+
}
|
|
2576
|
+
);
|
|
2577
|
+
} catch (error) {
|
|
2578
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
2579
|
+
return this.finishSuspension({
|
|
2580
|
+
runId,
|
|
2581
|
+
turn: currentTurns,
|
|
2582
|
+
usage,
|
|
2583
|
+
newMessages,
|
|
2584
|
+
pendingTurnMessages,
|
|
2585
|
+
runObservers,
|
|
2586
|
+
suspension: error,
|
|
2587
|
+
uncommittedMessages: [assistantMessage]
|
|
2588
|
+
});
|
|
1884
2589
|
}
|
|
1885
|
-
|
|
2590
|
+
throw error;
|
|
2591
|
+
}
|
|
1886
2592
|
const toolMessage = { role: "tool", content: toolResults };
|
|
1887
2593
|
newMessages.push(toolMessage);
|
|
1888
2594
|
await this.memoryRecorder.commitMessages(
|
|
@@ -1899,6 +2605,7 @@ var AgentRun = class _AgentRun {
|
|
|
1899
2605
|
if (error instanceof MemoryCompactionError && error.usage !== void 0) {
|
|
1900
2606
|
usage = Usage.add(usage, error.usage);
|
|
1901
2607
|
}
|
|
2608
|
+
this.runState = "closing";
|
|
1902
2609
|
const runError = this.normalizeRunError(error);
|
|
1903
2610
|
const reportedError = await this.reportRunFailure(
|
|
1904
2611
|
runError,
|
|
@@ -1915,27 +2622,31 @@ var AgentRun = class _AgentRun {
|
|
|
1915
2622
|
async *events() {
|
|
1916
2623
|
this.startRun();
|
|
1917
2624
|
const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
|
|
1918
|
-
this.activeRunId = runId;
|
|
1919
2625
|
let usage = Usage.empty();
|
|
1920
2626
|
let currentTurns = 0;
|
|
1921
2627
|
let lastPrompt = this.promptMessage;
|
|
1922
2628
|
let newMessages = [this.promptMessage];
|
|
1923
2629
|
const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);
|
|
1924
2630
|
let runObservers;
|
|
2631
|
+
let pendingTurnMessages = [];
|
|
1925
2632
|
try {
|
|
1926
2633
|
this.throwIfCancelled();
|
|
1927
|
-
const memoryPreparation = await this.memoryRecorder.prepareHistory(
|
|
2634
|
+
const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
|
|
1928
2635
|
runId,
|
|
1929
2636
|
newMessages.length,
|
|
1930
2637
|
this.abortController.signal
|
|
1931
|
-
);
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
2638
|
+
) : void 0;
|
|
2639
|
+
if (memoryPreparation !== void 0) {
|
|
2640
|
+
this.chatHistory = memoryPreparation.history;
|
|
2641
|
+
usage = Usage.add(usage, memoryPreparation.usage);
|
|
2642
|
+
this.memoryCompaction = memoryPreparation.compaction;
|
|
2643
|
+
await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
|
|
2644
|
+
}
|
|
1936
2645
|
runObservers = await this.startRunObservers(runId);
|
|
1937
|
-
|
|
1938
|
-
|
|
2646
|
+
if (memoryPreparation !== void 0) {
|
|
2647
|
+
await this.recordMemoryCompaction(memoryPreparation, runObservers);
|
|
2648
|
+
}
|
|
2649
|
+
if (memoryPreparation?.compaction !== void 0) {
|
|
1939
2650
|
yield { type: "memory_compaction", ...memoryPreparation.compaction };
|
|
1940
2651
|
}
|
|
1941
2652
|
this.throwIfCancelled();
|
|
@@ -1945,41 +2656,94 @@ var AgentRun = class _AgentRun {
|
|
|
1945
2656
|
history: lifecycleSnapshot(this.chatHistory),
|
|
1946
2657
|
maxTurns: this.maxTurnCount
|
|
1947
2658
|
});
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2659
|
+
if (this.continuationState === void 0) {
|
|
2660
|
+
const inputResult = await runInputGuardrails(this.guardrailPolicies, {
|
|
2661
|
+
prompt: this.promptMessage,
|
|
2662
|
+
history: this.chatHistory,
|
|
2663
|
+
inputText: textFromMessage(this.promptMessage),
|
|
2664
|
+
run: this.guardrailRunContext(runId)
|
|
2665
|
+
});
|
|
2666
|
+
for (const decision of inputResult.decisions) {
|
|
2667
|
+
await this.recordGuardrailDecision(decision, runObservers);
|
|
2668
|
+
yield { type: "guardrail_decision", decision };
|
|
2669
|
+
}
|
|
2670
|
+
this.promptMessage = inputResult.prompt;
|
|
2671
|
+
if (inputResult.blocked) {
|
|
2672
|
+
const text = inputResult.message ?? "The request was blocked by a guardrail.";
|
|
2673
|
+
const result = {
|
|
2674
|
+
status: "blocked",
|
|
2675
|
+
stage: "input",
|
|
2676
|
+
runId,
|
|
2677
|
+
text,
|
|
2678
|
+
usage,
|
|
2679
|
+
messages: [this.promptMessage, { role: "assistant", content: text }],
|
|
2680
|
+
trace: runObservers.trace,
|
|
2681
|
+
guardrails: [...this.guardrailDecisions],
|
|
2682
|
+
...this.memoryCompactionResult()
|
|
2683
|
+
};
|
|
2684
|
+
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
2685
|
+
this.runState = "closing";
|
|
2686
|
+
await this.runLifecycleFinish(result);
|
|
2687
|
+
await runObservers.end(result);
|
|
2688
|
+
this.runState = "completed";
|
|
2689
|
+
this.disposeAbortLink();
|
|
2690
|
+
yield { type: "final", result };
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
1978
2693
|
}
|
|
1979
2694
|
newMessages = [this.promptMessage];
|
|
1980
2695
|
await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
|
|
1981
|
-
|
|
2696
|
+
pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
|
|
1982
2697
|
await this.runRunStartHook(newMessages);
|
|
2698
|
+
if (this.continuationState !== void 0) {
|
|
2699
|
+
const responsePart = this.promptMessage.role === "tool" ? this.promptMessage.content[0] : void 0;
|
|
2700
|
+
if (responsePart === void 0 || responsePart.type === "tool-result") {
|
|
2701
|
+
throw new TypeError("Agent continuation response message is invalid.");
|
|
2702
|
+
}
|
|
2703
|
+
yield {
|
|
2704
|
+
type: "interaction_response",
|
|
2705
|
+
response: responsePart,
|
|
2706
|
+
sourceRunId: this.resumedFrom?.runId ?? this.continuationState.kind
|
|
2707
|
+
};
|
|
2708
|
+
try {
|
|
2709
|
+
const execution = this.executeContinuationToolStream(runId, newMessages, {
|
|
2710
|
+
turn: 1,
|
|
2711
|
+
runObservers
|
|
2712
|
+
});
|
|
2713
|
+
for await (const event of execution.events) {
|
|
2714
|
+
yield { turn: 1, ...event };
|
|
2715
|
+
}
|
|
2716
|
+
const toolResults = await execution.results;
|
|
2717
|
+
const toolMessage = { role: "tool", content: toolResults };
|
|
2718
|
+
newMessages.push(toolMessage);
|
|
2719
|
+
await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
|
|
2720
|
+
for (const receipt of await this.drainSteeringMessages(
|
|
2721
|
+
runId,
|
|
2722
|
+
1,
|
|
2723
|
+
newMessages,
|
|
2724
|
+
pendingTurnMessages
|
|
2725
|
+
)) {
|
|
2726
|
+
yield { type: "steering_applied", id: receipt.id, turn: 1 };
|
|
2727
|
+
}
|
|
2728
|
+
await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
|
|
2729
|
+
} catch (error) {
|
|
2730
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
2731
|
+
const result = await this.finishSuspension({
|
|
2732
|
+
runId,
|
|
2733
|
+
turn: 1,
|
|
2734
|
+
usage,
|
|
2735
|
+
newMessages,
|
|
2736
|
+
pendingTurnMessages,
|
|
2737
|
+
runObservers,
|
|
2738
|
+
suspension: error,
|
|
2739
|
+
uncommittedMessages: []
|
|
2740
|
+
});
|
|
2741
|
+
yield { type: "final", result };
|
|
2742
|
+
return;
|
|
2743
|
+
}
|
|
2744
|
+
throw error;
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
1983
2747
|
while (currentTurns <= this.maxTurnCount + 1) {
|
|
1984
2748
|
const prompt = newMessages.at(-1);
|
|
1985
2749
|
if (prompt === void 0) {
|
|
@@ -2050,16 +2814,18 @@ var AgentRun = class _AgentRun {
|
|
|
2050
2814
|
throw error;
|
|
2051
2815
|
}
|
|
2052
2816
|
const { firstDeltaMs, emittedToolCallIds } = completionState;
|
|
2053
|
-
|
|
2817
|
+
let generationEndArgs = {
|
|
2054
2818
|
turn: currentTurns,
|
|
2055
|
-
response
|
|
2056
|
-
...firstDeltaMs === void 0 ? {} : { firstDeltaMs }
|
|
2819
|
+
response
|
|
2057
2820
|
};
|
|
2821
|
+
if (firstDeltaMs !== void 0) {
|
|
2822
|
+
generationEndArgs = { ...generationEndArgs, firstDeltaMs };
|
|
2823
|
+
}
|
|
2058
2824
|
this.activeGeneration = void 0;
|
|
2059
2825
|
await generationObservers.end(generationEndArgs);
|
|
2060
2826
|
response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
|
|
2061
2827
|
usage = Usage.add(usage, response.usage);
|
|
2062
|
-
this.
|
|
2828
|
+
this.updateRunProgress(newMessages);
|
|
2063
2829
|
await this.runCompletionResponseHook(prompt, response, newMessages);
|
|
2064
2830
|
await this.runTurnEndHook(currentTurns, response, newMessages);
|
|
2065
2831
|
await this.activeLifecycle?.onStepFinish?.({
|
|
@@ -2097,7 +2863,17 @@ var AgentRun = class _AgentRun {
|
|
|
2097
2863
|
pendingTurnMessages
|
|
2098
2864
|
);
|
|
2099
2865
|
}
|
|
2100
|
-
|
|
2866
|
+
const appliedSteering = await this.drainSteeringMessages(
|
|
2867
|
+
runId,
|
|
2868
|
+
currentTurns,
|
|
2869
|
+
newMessages,
|
|
2870
|
+
pendingTurnMessages,
|
|
2871
|
+
{ closeWhenEmpty: true }
|
|
2872
|
+
);
|
|
2873
|
+
for (const receipt of appliedSteering) {
|
|
2874
|
+
yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
|
|
2875
|
+
}
|
|
2876
|
+
if (appliedSteering.length > 0) {
|
|
2101
2877
|
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2102
2878
|
continue;
|
|
2103
2879
|
}
|
|
@@ -2130,22 +2906,41 @@ var AgentRun = class _AgentRun {
|
|
|
2130
2906
|
}
|
|
2131
2907
|
}
|
|
2132
2908
|
}
|
|
2133
|
-
this.
|
|
2909
|
+
this.updateRunProgress(newMessages);
|
|
2134
2910
|
yield {
|
|
2135
2911
|
type: "turn_end",
|
|
2136
2912
|
turn: currentTurns,
|
|
2137
2913
|
response,
|
|
2138
2914
|
firstDeltaMs
|
|
2139
2915
|
};
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2916
|
+
let toolResults;
|
|
2917
|
+
try {
|
|
2918
|
+
const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {
|
|
2919
|
+
turn: currentTurns,
|
|
2920
|
+
runObservers,
|
|
2921
|
+
toolDefinitions: request.tools
|
|
2922
|
+
});
|
|
2923
|
+
for await (const result of toolExecution.events) {
|
|
2924
|
+
yield { turn: currentTurns, ...result };
|
|
2925
|
+
}
|
|
2926
|
+
toolResults = await toolExecution.results;
|
|
2927
|
+
} catch (error) {
|
|
2928
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
2929
|
+
const result = await this.finishSuspension({
|
|
2930
|
+
runId,
|
|
2931
|
+
turn: currentTurns,
|
|
2932
|
+
usage,
|
|
2933
|
+
newMessages,
|
|
2934
|
+
pendingTurnMessages,
|
|
2935
|
+
runObservers,
|
|
2936
|
+
suspension: error,
|
|
2937
|
+
uncommittedMessages: [assistantMessage]
|
|
2938
|
+
});
|
|
2939
|
+
yield { type: "final", result };
|
|
2940
|
+
return;
|
|
2941
|
+
}
|
|
2942
|
+
throw error;
|
|
2147
2943
|
}
|
|
2148
|
-
const toolResults = await toolExecution.results;
|
|
2149
2944
|
const toolMessage = { role: "tool", content: toolResults };
|
|
2150
2945
|
newMessages.push(toolMessage);
|
|
2151
2946
|
await this.memoryRecorder.commitMessages(
|
|
@@ -2154,7 +2949,14 @@ var AgentRun = class _AgentRun {
|
|
|
2154
2949
|
[assistantMessage, toolMessage],
|
|
2155
2950
|
pendingTurnMessages
|
|
2156
2951
|
);
|
|
2157
|
-
await this.drainSteeringMessages(
|
|
2952
|
+
for (const receipt of await this.drainSteeringMessages(
|
|
2953
|
+
runId,
|
|
2954
|
+
currentTurns,
|
|
2955
|
+
newMessages,
|
|
2956
|
+
pendingTurnMessages
|
|
2957
|
+
)) {
|
|
2958
|
+
yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
|
|
2959
|
+
}
|
|
2158
2960
|
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2159
2961
|
}
|
|
2160
2962
|
throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
|
|
@@ -2162,6 +2964,7 @@ var AgentRun = class _AgentRun {
|
|
|
2162
2964
|
if (error instanceof MemoryCompactionError && error.usage !== void 0) {
|
|
2163
2965
|
usage = Usage.add(usage, error.usage);
|
|
2164
2966
|
}
|
|
2967
|
+
this.runState = "closing";
|
|
2165
2968
|
const runError = this.normalizeRunError(error);
|
|
2166
2969
|
const reportedError = await this.reportRunFailure(
|
|
2167
2970
|
runError,
|
|
@@ -2176,7 +2979,7 @@ var AgentRun = class _AgentRun {
|
|
|
2176
2979
|
this.disposeAbortLink();
|
|
2177
2980
|
return;
|
|
2178
2981
|
} finally {
|
|
2179
|
-
if (this.runState === "running") {
|
|
2982
|
+
if (this.runState === "running" || this.runState === "closing") {
|
|
2180
2983
|
const cancellation = this.cancellationError ?? new AgentRunCancelledError([...this.chatHistory, ...newMessages], "Agent stream closed.");
|
|
2181
2984
|
this.cancellationError = cancellation;
|
|
2182
2985
|
await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);
|
|
@@ -2226,7 +3029,7 @@ var AgentRun = class _AgentRun {
|
|
|
2226
3029
|
const abortSignal = this.abortController.signal;
|
|
2227
3030
|
const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);
|
|
2228
3031
|
const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);
|
|
2229
|
-
const request = createCompletionRequest([...history, prompt], {
|
|
3032
|
+
const request = createCompletionRequest(providerMessages([...history, prompt]), {
|
|
2230
3033
|
instructions: this.agent.instructions,
|
|
2231
3034
|
documents,
|
|
2232
3035
|
tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],
|
|
@@ -2348,25 +3151,84 @@ var AgentRun = class _AgentRun {
|
|
|
2348
3151
|
this.disposeAbortLink();
|
|
2349
3152
|
yield { type: "final", result };
|
|
2350
3153
|
}
|
|
3154
|
+
async finishSuspension(args) {
|
|
3155
|
+
const partialToolMessage = args.suspension.completedResults.length === 0 ? void 0 : { role: "tool", content: [...args.suspension.completedResults] };
|
|
3156
|
+
if (partialToolMessage !== void 0) {
|
|
3157
|
+
args.newMessages.push(partialToolMessage);
|
|
3158
|
+
args.uncommittedMessages.push(partialToolMessage);
|
|
3159
|
+
}
|
|
3160
|
+
await this.memoryRecorder.commitMessages(
|
|
3161
|
+
args.runId,
|
|
3162
|
+
args.turn,
|
|
3163
|
+
args.uncommittedMessages,
|
|
3164
|
+
args.pendingTurnMessages
|
|
3165
|
+
);
|
|
3166
|
+
await this.memoryRecorder.commitCompletedRun(
|
|
3167
|
+
args.runId,
|
|
3168
|
+
args.turn,
|
|
3169
|
+
args.newMessages,
|
|
3170
|
+
args.pendingTurnMessages
|
|
3171
|
+
);
|
|
3172
|
+
this.runState = "closing";
|
|
3173
|
+
const continuationState = {
|
|
3174
|
+
kind: "anvia.agent-continuation",
|
|
3175
|
+
history: [...this.chatHistory],
|
|
3176
|
+
messages: [...args.newMessages],
|
|
3177
|
+
pending: args.suspension.pending,
|
|
3178
|
+
remainingToolCalls: [...args.suspension.remainingToolCalls],
|
|
3179
|
+
steering: this.steeringMessages.map((entry) => ({
|
|
3180
|
+
id: entry.id,
|
|
3181
|
+
messages: [...entry.messages]
|
|
3182
|
+
}))
|
|
3183
|
+
};
|
|
3184
|
+
if (this.memoryScope !== void 0) continuationState.memoryScope = this.memoryScope;
|
|
3185
|
+
const continuation = parseAgentContinuation({
|
|
3186
|
+
version: 1,
|
|
3187
|
+
agentId: this.agent.id,
|
|
3188
|
+
sourceRunId: args.runId,
|
|
3189
|
+
interaction: args.suspension.interaction,
|
|
3190
|
+
state: serializeContinuationState(continuationState)
|
|
3191
|
+
});
|
|
3192
|
+
const result = {
|
|
3193
|
+
status: "suspended",
|
|
3194
|
+
runId: args.runId,
|
|
3195
|
+
text: latestAssistantText([...this.chatHistory, ...args.newMessages]),
|
|
3196
|
+
usage: args.usage,
|
|
3197
|
+
messages: [...args.newMessages],
|
|
3198
|
+
trace: args.runObservers.trace,
|
|
3199
|
+
guardrails: [...this.guardrailDecisions],
|
|
3200
|
+
interaction: continuation.interaction,
|
|
3201
|
+
continuation,
|
|
3202
|
+
...generationArtifacts([...this.chatHistory, ...args.newMessages]),
|
|
3203
|
+
...this.memoryCompactionResult()
|
|
3204
|
+
};
|
|
3205
|
+
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
3206
|
+
await this.runLifecycleFinish(result);
|
|
3207
|
+
await args.runObservers.end(result);
|
|
3208
|
+
this.runState = "completed";
|
|
3209
|
+
this.currentMessages = [...args.newMessages];
|
|
3210
|
+
this.disposeAbortLink();
|
|
3211
|
+
return result;
|
|
3212
|
+
}
|
|
2351
3213
|
generatedAssistantMessage(response, _request) {
|
|
2352
|
-
const
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
modelId: this.agent.model.modelId,
|
|
2357
|
-
usage: { ...response.usage },
|
|
2358
|
-
...response.contextUsage === void 0 ? {} : { contextUsage: response.contextUsage },
|
|
2359
|
-
...response.sources === void 0 ? {} : { sources: response.sources },
|
|
2360
|
-
...response.providerToolCalls === void 0 ? {} : { providerToolCalls: response.providerToolCalls }
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
3214
|
+
const generation = {
|
|
3215
|
+
provider: this.agent.model.provider,
|
|
3216
|
+
modelId: this.agent.model.modelId,
|
|
3217
|
+
usage: { ...response.usage }
|
|
2363
3218
|
};
|
|
2364
|
-
|
|
3219
|
+
if (response.contextUsage !== void 0) generation.contextUsage = response.contextUsage;
|
|
3220
|
+
if (response.sources !== void 0) generation.sources = response.sources;
|
|
3221
|
+
if (response.providerToolCalls !== void 0) {
|
|
3222
|
+
generation.providerToolCalls = response.providerToolCalls;
|
|
3223
|
+
}
|
|
3224
|
+
const metadata = { anvia: { generation } };
|
|
3225
|
+
let message = {
|
|
2365
3226
|
role: "assistant",
|
|
2366
3227
|
content: response.choice,
|
|
2367
|
-
...response.messageId === void 0 ? {} : { id: response.messageId },
|
|
2368
3228
|
metadata
|
|
2369
3229
|
};
|
|
3230
|
+
if (response.messageId !== void 0) message = { ...message, id: response.messageId };
|
|
3231
|
+
return message;
|
|
2370
3232
|
}
|
|
2371
3233
|
providerTraceRequest(request, options = {}) {
|
|
2372
3234
|
try {
|
|
@@ -2378,16 +3240,17 @@ var AgentRun = class _AgentRun {
|
|
|
2378
3240
|
}
|
|
2379
3241
|
}
|
|
2380
3242
|
generationStartArgs(turn, request, providerRequest) {
|
|
2381
|
-
|
|
3243
|
+
let args = {
|
|
2382
3244
|
turn,
|
|
2383
3245
|
request,
|
|
2384
3246
|
modelInfo: {
|
|
2385
3247
|
provider: this.agent.model.provider,
|
|
2386
3248
|
modelId: this.agent.model.modelId,
|
|
2387
3249
|
capabilities: this.agent.model.capabilities
|
|
2388
|
-
}
|
|
2389
|
-
...providerRequest === void 0 ? {} : { providerRequest }
|
|
3250
|
+
}
|
|
2390
3251
|
};
|
|
3252
|
+
if (providerRequest !== void 0) args = { ...args, providerRequest };
|
|
3253
|
+
return args;
|
|
2391
3254
|
}
|
|
2392
3255
|
retryOptionsForFailure(error, attempt, turn, streaming) {
|
|
2393
3256
|
if (this.abortController.signal.aborted) return void 0;
|
|
@@ -2416,10 +3279,16 @@ var AgentRun = class _AgentRun {
|
|
|
2416
3279
|
await waitForRetry(delayMs, this.abortController.signal);
|
|
2417
3280
|
}
|
|
2418
3281
|
async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
|
|
2419
|
-
const executor =
|
|
3282
|
+
const executor = this.createToolExecutor(runId, newMessages);
|
|
3283
|
+
return executor.execute(toolCalls, onResult, onStreamEvent, observation);
|
|
3284
|
+
}
|
|
3285
|
+
createToolExecutor(runId, newMessages) {
|
|
3286
|
+
return new ToolCallExecutor(
|
|
2420
3287
|
this.agent,
|
|
2421
3288
|
this.activeHook,
|
|
2422
|
-
(request) =>
|
|
3289
|
+
async (request) => {
|
|
3290
|
+
throw new AgentInteractionSignal(approvalInteraction(request), request.rejectMessage);
|
|
3291
|
+
},
|
|
2423
3292
|
this.activeLifecycle,
|
|
2424
3293
|
{
|
|
2425
3294
|
runId,
|
|
@@ -2431,7 +3300,63 @@ var AgentRun = class _AgentRun {
|
|
|
2431
3300
|
this.abortController.signal,
|
|
2432
3301
|
(reason) => this.cancelled(newMessages, reason)
|
|
2433
3302
|
);
|
|
2434
|
-
|
|
3303
|
+
}
|
|
3304
|
+
async resolveContinuationTools(runId, newMessages, onResult, onStreamEvent, observation) {
|
|
3305
|
+
const state = this.continuationState;
|
|
3306
|
+
const response = this.interactionResponse;
|
|
3307
|
+
if (state === void 0 || response === void 0) {
|
|
3308
|
+
return [];
|
|
3309
|
+
}
|
|
3310
|
+
const pending = state.pending;
|
|
3311
|
+
const interaction = this.resumedFrom;
|
|
3312
|
+
if (interaction === void 0) {
|
|
3313
|
+
throw new TypeError("Agent continuation is missing its source run linkage.");
|
|
3314
|
+
}
|
|
3315
|
+
const executor = this.createToolExecutor(runId, newMessages);
|
|
3316
|
+
const results = [];
|
|
3317
|
+
if (response.type === "tool-approval") {
|
|
3318
|
+
const attributes = {
|
|
3319
|
+
approvalId: interaction.interactionId,
|
|
3320
|
+
toolName: pending.toolCall.toolName,
|
|
3321
|
+
toolCallId: pending.toolCall.toolCallId,
|
|
3322
|
+
internalCallId: pending.internalCallId,
|
|
3323
|
+
approved: response.approved
|
|
3324
|
+
};
|
|
3325
|
+
if (response.reason !== void 0) attributes.decisionReason = response.reason;
|
|
3326
|
+
await observation.runObservers.event({
|
|
3327
|
+
name: "tool.approval_resolved",
|
|
3328
|
+
attributes
|
|
3329
|
+
});
|
|
3330
|
+
if (response.approved) {
|
|
3331
|
+
results.push(await executor.executeResumed(pending, onResult, onStreamEvent, observation));
|
|
3332
|
+
} else {
|
|
3333
|
+
const output = {
|
|
3334
|
+
type: "execution-denied",
|
|
3335
|
+
reason: response.reason ?? pending.rejectMessage ?? "Tool approval was rejected."
|
|
3336
|
+
};
|
|
3337
|
+
results.push(await executor.resolveResumed(pending, output, onResult, observation));
|
|
3338
|
+
}
|
|
3339
|
+
} else {
|
|
3340
|
+
const currentTool = this.agent.getTool(pending.toolCall.toolName);
|
|
3341
|
+
if (currentTool === void 0 || !isQuestionTool(currentTool)) {
|
|
3342
|
+
throw new TypeError(
|
|
3343
|
+
`Cannot resume question interaction because tool "${pending.toolCall.toolName}" is no longer registered as a question tool.`
|
|
3344
|
+
);
|
|
3345
|
+
}
|
|
3346
|
+
const output = questionResult(response.answers);
|
|
3347
|
+
results.push(await executor.resolveResumed(pending, output, onResult, observation));
|
|
3348
|
+
}
|
|
3349
|
+
try {
|
|
3350
|
+
results.push(
|
|
3351
|
+
...await executor.execute(state.remainingToolCalls, onResult, onStreamEvent, observation)
|
|
3352
|
+
);
|
|
3353
|
+
} catch (error) {
|
|
3354
|
+
if (error instanceof ToolExecutionSuspension) {
|
|
3355
|
+
error.completedResults = [...results, ...error.completedResults];
|
|
3356
|
+
}
|
|
3357
|
+
throw error;
|
|
3358
|
+
}
|
|
3359
|
+
return results;
|
|
2435
3360
|
}
|
|
2436
3361
|
executeStreamingToolCalls(runId, toolCalls, newMessages, observation) {
|
|
2437
3362
|
const events = createAsyncQueue();
|
|
@@ -2449,17 +3374,20 @@ var AgentRun = class _AgentRun {
|
|
|
2449
3374
|
);
|
|
2450
3375
|
return { events, results };
|
|
2451
3376
|
}
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
3377
|
+
executeContinuationToolStream(runId, newMessages, observation) {
|
|
3378
|
+
const events = createAsyncQueue();
|
|
3379
|
+
const results = this.resolveContinuationTools(
|
|
3380
|
+
runId,
|
|
3381
|
+
newMessages,
|
|
3382
|
+
(result) => events.enqueue(result),
|
|
3383
|
+
(event) => events.enqueue(event),
|
|
3384
|
+
observation
|
|
3385
|
+
);
|
|
3386
|
+
results.then(
|
|
3387
|
+
() => events.close(),
|
|
3388
|
+
(error) => events.throw(error)
|
|
3389
|
+
);
|
|
3390
|
+
return { events, results };
|
|
2463
3391
|
}
|
|
2464
3392
|
async closeActiveGeneration(error) {
|
|
2465
3393
|
const active = this.activeGeneration;
|
|
@@ -2469,31 +3397,7 @@ var AgentRun = class _AgentRun {
|
|
|
2469
3397
|
this.activeGeneration = void 0;
|
|
2470
3398
|
await active.observers.error({ turn: active.turn, error });
|
|
2471
3399
|
}
|
|
2472
|
-
|
|
2473
|
-
const pending = this.pendingApproval;
|
|
2474
|
-
const runId = this.activeRunId;
|
|
2475
|
-
if (pending === void 0 || runId === void 0) {
|
|
2476
|
-
throw new TypeError("Agent run has no pending tool approval.");
|
|
2477
|
-
}
|
|
2478
|
-
const approval = {
|
|
2479
|
-
id: pending.request.id,
|
|
2480
|
-
toolName: pending.request.toolName,
|
|
2481
|
-
input: lifecycleSnapshot(pending.request.args),
|
|
2482
|
-
...pending.request.toolCallId === void 0 ? {} : { toolCallId: pending.request.toolCallId },
|
|
2483
|
-
...pending.request.reason === void 0 ? {} : { reason: pending.request.reason }
|
|
2484
|
-
};
|
|
2485
|
-
registerAgentApprovalRequestDetails(approval, pending.request);
|
|
2486
|
-
return {
|
|
2487
|
-
runId,
|
|
2488
|
-
approval,
|
|
2489
|
-
usage: lifecycleSnapshot(this.currentUsage),
|
|
2490
|
-
messages: lifecycleSnapshot(this.currentMessages),
|
|
2491
|
-
...this.memoryCompactionResult()
|
|
2492
|
-
};
|
|
2493
|
-
}
|
|
2494
|
-
updateApprovalProgress(runId, usage, messages) {
|
|
2495
|
-
this.activeRunId = runId;
|
|
2496
|
-
this.currentUsage = usage;
|
|
3400
|
+
updateRunProgress(messages) {
|
|
2497
3401
|
this.currentMessages = [...messages];
|
|
2498
3402
|
}
|
|
2499
3403
|
async runLifecycleFinish(result) {
|
|
@@ -2501,17 +3405,23 @@ var AgentRun = class _AgentRun {
|
|
|
2501
3405
|
runId: result.runId,
|
|
2502
3406
|
text: result.text,
|
|
2503
3407
|
usage: lifecycleSnapshot(result.usage),
|
|
2504
|
-
messages: lifecycleSnapshot(result.messages)
|
|
2505
|
-
...result.memoryCompaction === void 0 ? {} : { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) }
|
|
3408
|
+
messages: lifecycleSnapshot(result.messages)
|
|
2506
3409
|
};
|
|
3410
|
+
if (result.memoryCompaction !== void 0) {
|
|
3411
|
+
Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });
|
|
3412
|
+
}
|
|
2507
3413
|
const event = result.status === "completed" ? {
|
|
2508
3414
|
...common,
|
|
2509
3415
|
status: "completed",
|
|
2510
3416
|
output: lifecycleSnapshot(result.output)
|
|
2511
|
-
} : {
|
|
3417
|
+
} : result.status === "blocked" ? {
|
|
2512
3418
|
...common,
|
|
2513
3419
|
status: "blocked",
|
|
2514
3420
|
stage: result.stage
|
|
3421
|
+
} : {
|
|
3422
|
+
...common,
|
|
3423
|
+
status: "suspended",
|
|
3424
|
+
interaction: lifecycleSnapshot(result.interaction)
|
|
2515
3425
|
};
|
|
2516
3426
|
await this.activeLifecycle?.onFinish?.(event);
|
|
2517
3427
|
}
|
|
@@ -2588,6 +3498,7 @@ var AgentRun = class _AgentRun {
|
|
|
2588
3498
|
...generationArtifacts(messages),
|
|
2589
3499
|
...this.memoryCompactionResult()
|
|
2590
3500
|
};
|
|
3501
|
+
if (this.resumedFrom !== void 0) Object.assign(common, { resumedFrom: this.resumedFrom });
|
|
2591
3502
|
if (blocked) {
|
|
2592
3503
|
return { ...common, status: "blocked", stage: "output" };
|
|
2593
3504
|
}
|
|
@@ -2798,14 +3709,18 @@ var AgentRun = class _AgentRun {
|
|
|
2798
3709
|
shouldBufferStreamResponseEvents() {
|
|
2799
3710
|
return this.activeHook?.onCompletionResponse !== void 0 || this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== void 0);
|
|
2800
3711
|
}
|
|
2801
|
-
async drainSteeringMessages(runId, turn, newMessages, pendingTurnMessages) {
|
|
2802
|
-
const
|
|
2803
|
-
if (
|
|
2804
|
-
|
|
3712
|
+
async drainSteeringMessages(runId, turn, newMessages, pendingTurnMessages, options = {}) {
|
|
3713
|
+
const receipts = this.steeringMessages.splice(0);
|
|
3714
|
+
if (receipts.length === 0) {
|
|
3715
|
+
if (options.closeWhenEmpty === true) {
|
|
3716
|
+
this.runState = "closing";
|
|
3717
|
+
}
|
|
3718
|
+
return [];
|
|
2805
3719
|
}
|
|
3720
|
+
const messages = receipts.flatMap((receipt) => receipt.messages);
|
|
2806
3721
|
newMessages.push(...messages);
|
|
2807
3722
|
await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);
|
|
2808
|
-
return
|
|
3723
|
+
return receipts;
|
|
2809
3724
|
}
|
|
2810
3725
|
startRun() {
|
|
2811
3726
|
if (this.runState === "idle") {
|
|
@@ -2818,7 +3733,7 @@ var AgentRun = class _AgentRun {
|
|
|
2818
3733
|
throw new Error("Agent stream has already been consumed.");
|
|
2819
3734
|
}
|
|
2820
3735
|
isTerminal() {
|
|
2821
|
-
return this.runState
|
|
3736
|
+
return this.runState !== "idle" && this.runState !== "running";
|
|
2822
3737
|
}
|
|
2823
3738
|
cancelled(newMessages, reason) {
|
|
2824
3739
|
if (this.cancellationError !== void 0) return this.cancellationError;
|
|
@@ -2864,14 +3779,67 @@ function abortReason(reason) {
|
|
|
2864
3779
|
if (reason instanceof Error && reason.message.trim().length > 0) return reason.message;
|
|
2865
3780
|
return "External abort signal.";
|
|
2866
3781
|
}
|
|
2867
|
-
function normalizeAgentInput(input) {
|
|
3782
|
+
function normalizeAgentInput(agentId, input) {
|
|
2868
3783
|
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
2869
3784
|
throw new TypeError("Agent runs require one options object with prompt or messages.");
|
|
2870
3785
|
}
|
|
3786
|
+
const hasContinuation = "continuation" in input && input.continuation !== void 0;
|
|
2871
3787
|
const hasPrompt = "prompt" in input && input.prompt !== void 0;
|
|
2872
3788
|
const hasMessages = "messages" in input && input.messages !== void 0;
|
|
2873
|
-
if (hasPrompt
|
|
2874
|
-
throw new TypeError("Agent runs require exactly one of prompt or
|
|
3789
|
+
if (Number(hasContinuation) + Number(hasPrompt) + Number(hasMessages) !== 1) {
|
|
3790
|
+
throw new TypeError("Agent runs require exactly one of prompt, messages, or continuation.");
|
|
3791
|
+
}
|
|
3792
|
+
if (hasContinuation) {
|
|
3793
|
+
if (!("response" in input) || input.response === void 0) {
|
|
3794
|
+
throw new TypeError("Agent continuation runs require an interaction response.");
|
|
3795
|
+
}
|
|
3796
|
+
if ("session" in input && input.session !== void 0) {
|
|
3797
|
+
throw new TypeError("Agent continuations carry their memory scope and cannot use session.");
|
|
3798
|
+
}
|
|
3799
|
+
const continuation = parseAgentContinuation(input.continuation);
|
|
3800
|
+
if (continuation.agentId !== agentId) {
|
|
3801
|
+
throw new TypeError(
|
|
3802
|
+
`Agent continuation belongs to "${continuation.agentId}", not "${agentId}".`
|
|
3803
|
+
);
|
|
3804
|
+
}
|
|
3805
|
+
const response = parseAgentInteractionResponse(input.response);
|
|
3806
|
+
assertAgentInteractionResponse(continuation.interaction, response);
|
|
3807
|
+
const state = parseContinuationState(continuation.state, continuation.interaction);
|
|
3808
|
+
let responsePart;
|
|
3809
|
+
if (response.type === "tool-approval") {
|
|
3810
|
+
responsePart = {
|
|
3811
|
+
type: "tool-approval-response",
|
|
3812
|
+
interactionId: continuation.interaction.id,
|
|
3813
|
+
toolCallId: continuation.interaction.toolCallId,
|
|
3814
|
+
toolName: continuation.interaction.toolName,
|
|
3815
|
+
approved: response.approved
|
|
3816
|
+
};
|
|
3817
|
+
if (response.reason !== void 0)
|
|
3818
|
+
responsePart = { ...responsePart, reason: response.reason };
|
|
3819
|
+
} else {
|
|
3820
|
+
responsePart = {
|
|
3821
|
+
type: "tool-question-response",
|
|
3822
|
+
interactionId: continuation.interaction.id,
|
|
3823
|
+
toolCallId: continuation.interaction.toolCallId,
|
|
3824
|
+
toolName: continuation.interaction.toolName,
|
|
3825
|
+
answers: response.answers
|
|
3826
|
+
};
|
|
3827
|
+
}
|
|
3828
|
+
if (continuation.interaction.callId !== void 0) {
|
|
3829
|
+
responsePart = { ...responsePart, callId: continuation.interaction.callId };
|
|
3830
|
+
}
|
|
3831
|
+
const normalized = {
|
|
3832
|
+
prompt: parseMessage({ role: "tool", content: [responsePart] }),
|
|
3833
|
+
history: [...state.history, ...state.messages],
|
|
3834
|
+
continuationState: state,
|
|
3835
|
+
interactionResponse: response,
|
|
3836
|
+
sourceRunId: continuation.sourceRunId,
|
|
3837
|
+
interactionId: continuation.interaction.id
|
|
3838
|
+
};
|
|
3839
|
+
if (state.memoryScope !== void 0) {
|
|
3840
|
+
Object.assign(normalized, { scope: normalizeMemoryScope(state.memoryScope) });
|
|
3841
|
+
}
|
|
3842
|
+
return normalized;
|
|
2875
3843
|
}
|
|
2876
3844
|
if (hasPrompt) {
|
|
2877
3845
|
const prompt = input.prompt;
|
|
@@ -2884,11 +3852,14 @@ function normalizeAgentInput(input) {
|
|
|
2884
3852
|
if (parsedPrompt.role !== "user") {
|
|
2885
3853
|
throw new TypeError("Agent prompt must be text or a user message.");
|
|
2886
3854
|
}
|
|
2887
|
-
|
|
3855
|
+
const normalized = {
|
|
2888
3856
|
prompt: parsedPrompt,
|
|
2889
|
-
history: []
|
|
2890
|
-
...input.session === void 0 ? {} : { scope: normalizeMemoryScope(input.session) }
|
|
3857
|
+
history: []
|
|
2891
3858
|
};
|
|
3859
|
+
if (input.session !== void 0) {
|
|
3860
|
+
Object.assign(normalized, { scope: normalizeMemoryScope(input.session) });
|
|
3861
|
+
}
|
|
3862
|
+
return normalized;
|
|
2892
3863
|
}
|
|
2893
3864
|
if (input.session !== void 0) {
|
|
2894
3865
|
throw new TypeError("Agent messages cannot be combined with a persisted session.");
|
|
@@ -2949,11 +3920,12 @@ function normalizeMemoryScope(scope) {
|
|
|
2949
3920
|
if (typeof scope.sessionId !== "string" || scope.sessionId.trim().length === 0) {
|
|
2950
3921
|
throw new TypeError("Agent sessionId must be a non-empty string.");
|
|
2951
3922
|
}
|
|
2952
|
-
|
|
2953
|
-
sessionId: scope.sessionId.trim()
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
3923
|
+
const normalized = {
|
|
3924
|
+
sessionId: scope.sessionId.trim()
|
|
3925
|
+
};
|
|
3926
|
+
if (scope.userId !== void 0) normalized.userId = scope.userId;
|
|
3927
|
+
if (scope.metadata !== void 0) normalized.metadata = scope.metadata;
|
|
3928
|
+
return lifecycleSnapshot(normalized);
|
|
2957
3929
|
}
|
|
2958
3930
|
function normalizeRequestedRunId(runId) {
|
|
2959
3931
|
if (runId === void 0) {
|
|
@@ -3023,11 +3995,13 @@ function generationArtifacts(messages) {
|
|
|
3023
3995
|
providerToolCalls.set(toolCall.id, toolCall);
|
|
3024
3996
|
}
|
|
3025
3997
|
}
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
}
|
|
3998
|
+
const artifacts = {};
|
|
3999
|
+
if (sources.size > 0) artifacts.sources = [...sources.values()];
|
|
4000
|
+
if (providerToolCalls.size > 0) {
|
|
4001
|
+
artifacts.providerToolCalls = [...providerToolCalls.values()];
|
|
4002
|
+
}
|
|
4003
|
+
if (contextUsage !== void 0) artifacts.contextUsage = contextUsage;
|
|
4004
|
+
return artifacts;
|
|
3031
4005
|
}
|
|
3032
4006
|
function reasoningDeltaEvent2(turn, delta, details = {}) {
|
|
3033
4007
|
const event = {
|
|
@@ -3063,6 +4037,29 @@ function textFromMessage(message) {
|
|
|
3063
4037
|
return [];
|
|
3064
4038
|
}).join("\n");
|
|
3065
4039
|
}
|
|
4040
|
+
function latestAssistantText(messages) {
|
|
4041
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
4042
|
+
const message = messages[index];
|
|
4043
|
+
if (message?.role === "assistant") {
|
|
4044
|
+
return typeof message.content === "string" ? message.content : textFromAssistantContent(message.content);
|
|
4045
|
+
}
|
|
4046
|
+
}
|
|
4047
|
+
return "";
|
|
4048
|
+
}
|
|
4049
|
+
function providerMessages(messages) {
|
|
4050
|
+
const providerMessages2 = [];
|
|
4051
|
+
for (const message of messages) {
|
|
4052
|
+
if (message.role !== "tool") {
|
|
4053
|
+
providerMessages2.push(message);
|
|
4054
|
+
continue;
|
|
4055
|
+
}
|
|
4056
|
+
const results = message.content.filter((part) => part.type === "tool-result");
|
|
4057
|
+
if (results.length > 0) {
|
|
4058
|
+
providerMessages2.push({ ...message, content: results });
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
return providerMessages2;
|
|
4062
|
+
}
|
|
3066
4063
|
function guardrailDecisionAttributes(decision) {
|
|
3067
4064
|
const attributes = {
|
|
3068
4065
|
policyId: decision.policyId,
|
|
@@ -3082,9 +4079,126 @@ function guardrailDecisionAttributes(decision) {
|
|
|
3082
4079
|
return attributes;
|
|
3083
4080
|
}
|
|
3084
4081
|
|
|
3085
|
-
// src/
|
|
3086
|
-
function
|
|
3087
|
-
|
|
4082
|
+
// src/agent/agent-stream.ts
|
|
4083
|
+
function createAgentStream(run) {
|
|
4084
|
+
return new DefaultAgentStream(run);
|
|
4085
|
+
}
|
|
4086
|
+
var DefaultAgentStream = class {
|
|
4087
|
+
constructor(run) {
|
|
4088
|
+
this.run = run;
|
|
4089
|
+
}
|
|
4090
|
+
run;
|
|
4091
|
+
consuming = false;
|
|
4092
|
+
completed = false;
|
|
4093
|
+
steer(input) {
|
|
4094
|
+
return this.run.steer(input);
|
|
4095
|
+
}
|
|
4096
|
+
[Symbol.asyncIterator]() {
|
|
4097
|
+
return this.consume()[Symbol.asyncIterator]();
|
|
4098
|
+
}
|
|
4099
|
+
async *consume() {
|
|
4100
|
+
if (this.completed) {
|
|
4101
|
+
throw new Error("Agent stream has already been consumed.");
|
|
4102
|
+
}
|
|
4103
|
+
if (this.consuming) {
|
|
4104
|
+
throw new Error("Agent stream is already running.");
|
|
4105
|
+
}
|
|
4106
|
+
this.consuming = true;
|
|
4107
|
+
try {
|
|
4108
|
+
for await (const event of this.run.events()) {
|
|
4109
|
+
yield event;
|
|
4110
|
+
}
|
|
4111
|
+
} finally {
|
|
4112
|
+
if (!this.completed) {
|
|
4113
|
+
this.run.cancel("Agent stream consumer closed the stream.");
|
|
4114
|
+
}
|
|
4115
|
+
this.consuming = false;
|
|
4116
|
+
this.completed = true;
|
|
4117
|
+
}
|
|
4118
|
+
}
|
|
4119
|
+
};
|
|
4120
|
+
|
|
4121
|
+
// src/agent/agent-tool.ts
|
|
4122
|
+
import { z as z2 } from "zod";
|
|
4123
|
+
function createAgentTool(agent, options) {
|
|
4124
|
+
if (options.suspension !== "reject") {
|
|
4125
|
+
throw new TypeError('Agent.asTool() requires suspension: "reject".');
|
|
4126
|
+
}
|
|
4127
|
+
const description = options.description ?? agent.description ?? `Prompt the ${options.name} agent.`;
|
|
4128
|
+
return createTool({
|
|
4129
|
+
name: options.name,
|
|
4130
|
+
description,
|
|
4131
|
+
inputSchema: z2.object({
|
|
4132
|
+
prompt: z2.string().describe("The prompt to send to the agent.")
|
|
4133
|
+
}),
|
|
4134
|
+
execute: async ({ prompt }, context) => {
|
|
4135
|
+
if (options.stream === true && context.emitStreamEvent !== void 0 && agent.model.capabilities.streaming && isStreamingCompletionModel(agent.model)) {
|
|
4136
|
+
let completed = false;
|
|
4137
|
+
let output;
|
|
4138
|
+
const childStream = agent.stream({
|
|
4139
|
+
prompt,
|
|
4140
|
+
maxTurns: options.maxTurns,
|
|
4141
|
+
abortSignal: context.abortSignal
|
|
4142
|
+
});
|
|
4143
|
+
for await (const event of childStream) {
|
|
4144
|
+
const streamEvent = {
|
|
4145
|
+
agentId: agent.id,
|
|
4146
|
+
event
|
|
4147
|
+
};
|
|
4148
|
+
if (agent.name !== void 0) {
|
|
4149
|
+
streamEvent.agentName = agent.name;
|
|
4150
|
+
}
|
|
4151
|
+
await context.emitStreamEvent(streamEvent);
|
|
4152
|
+
if (event.type === "error") {
|
|
4153
|
+
throw event.error;
|
|
4154
|
+
}
|
|
4155
|
+
if (event.type === "final") {
|
|
4156
|
+
if (event.result.status === "suspended") {
|
|
4157
|
+
throw new AgentToolSuspensionError(event.result);
|
|
4158
|
+
}
|
|
4159
|
+
if (event.result.status === "blocked") {
|
|
4160
|
+
throw new AgentRunBlockedError(event.result);
|
|
4161
|
+
}
|
|
4162
|
+
output = event.result.output;
|
|
4163
|
+
completed = true;
|
|
4164
|
+
}
|
|
4165
|
+
}
|
|
4166
|
+
if (!completed) {
|
|
4167
|
+
throw new Error(`Agent tool "${options.name}" ended without a final result.`);
|
|
4168
|
+
}
|
|
4169
|
+
return output;
|
|
4170
|
+
}
|
|
4171
|
+
const response = await agent.generate({
|
|
4172
|
+
prompt,
|
|
4173
|
+
maxTurns: options.maxTurns,
|
|
4174
|
+
abortSignal: context.abortSignal
|
|
4175
|
+
});
|
|
4176
|
+
if (response.status === "suspended") {
|
|
4177
|
+
throw new AgentToolSuspensionError(response);
|
|
4178
|
+
}
|
|
4179
|
+
if (response.status === "blocked") {
|
|
4180
|
+
throw new AgentRunBlockedError(response);
|
|
4181
|
+
}
|
|
4182
|
+
return response.output;
|
|
4183
|
+
}
|
|
4184
|
+
});
|
|
4185
|
+
}
|
|
4186
|
+
|
|
4187
|
+
// src/agent/ids.ts
|
|
4188
|
+
function normalizeAgentId(id) {
|
|
4189
|
+
if (typeof id !== "string") {
|
|
4190
|
+
throw new TypeError("Agent id must be a string.");
|
|
4191
|
+
}
|
|
4192
|
+
const normalized = id.trim();
|
|
4193
|
+
if (normalized.length === 0) {
|
|
4194
|
+
throw new TypeError("Agent id must be a non-empty string.");
|
|
4195
|
+
}
|
|
4196
|
+
return normalized;
|
|
4197
|
+
}
|
|
4198
|
+
|
|
4199
|
+
// src/memory/options.ts
|
|
4200
|
+
function resolveMemoryOptions(options = {}) {
|
|
4201
|
+
const resolved = {
|
|
3088
4202
|
savePolicy: options.savePolicy ?? "message"
|
|
3089
4203
|
};
|
|
3090
4204
|
if (options.compaction !== void 0) {
|
|
@@ -3115,236 +4229,8 @@ function resolveMemoryOptions(options = {}) {
|
|
|
3115
4229
|
return resolved;
|
|
3116
4230
|
}
|
|
3117
4231
|
|
|
3118
|
-
// src/agent/
|
|
3119
|
-
function normalizeAgentId(id) {
|
|
3120
|
-
if (typeof id !== "string") {
|
|
3121
|
-
throw new TypeError("Agent id must be a string.");
|
|
3122
|
-
}
|
|
3123
|
-
const normalized = id.trim();
|
|
3124
|
-
if (normalized.length === 0) {
|
|
3125
|
-
throw new TypeError("Agent id must be a non-empty string.");
|
|
3126
|
-
}
|
|
3127
|
-
return normalized;
|
|
3128
|
-
}
|
|
3129
|
-
|
|
3130
|
-
// src/agent/agent.ts
|
|
3131
|
-
var DEFAULT_MAX_TURNS = 20;
|
|
3132
|
-
var providerOutputSchemas = /* @__PURE__ */ new WeakMap();
|
|
3133
|
-
var Agent = class {
|
|
3134
|
-
id;
|
|
3135
|
-
name;
|
|
3136
|
-
description;
|
|
3137
|
-
model;
|
|
3138
|
-
instructions;
|
|
3139
|
-
context;
|
|
3140
|
-
temperature;
|
|
3141
|
-
maxTokens;
|
|
3142
|
-
providerOptions;
|
|
3143
|
-
retries;
|
|
3144
|
-
mcpServers;
|
|
3145
|
-
tools;
|
|
3146
|
-
toolChoice;
|
|
3147
|
-
defaultMaxTurns;
|
|
3148
|
-
lifecycle;
|
|
3149
|
-
outputSchema;
|
|
3150
|
-
observability;
|
|
3151
|
-
guardrails;
|
|
3152
|
-
middlewares;
|
|
3153
|
-
memory;
|
|
3154
|
-
constructor(options) {
|
|
3155
|
-
const resolved = resolveAgentOptions(options);
|
|
3156
|
-
this.id = normalizeAgentId(resolved.id);
|
|
3157
|
-
this.name = resolved.name;
|
|
3158
|
-
this.description = resolved.description;
|
|
3159
|
-
this.model = resolved.model;
|
|
3160
|
-
this.instructions = resolved.instructions;
|
|
3161
|
-
const context = (resolved.context ?? []).map(snapshotContextInput);
|
|
3162
|
-
assertValidVectorContexts(context);
|
|
3163
|
-
this.context = Object.freeze(context);
|
|
3164
|
-
this.temperature = resolved.temperature;
|
|
3165
|
-
this.maxTokens = resolved.maxTokens;
|
|
3166
|
-
this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
|
|
3167
|
-
this.retries = cloneFrozenPlainData(resolved.retries);
|
|
3168
|
-
assertUniqueMcpServerNames(resolved.mcpServers ?? []);
|
|
3169
|
-
this.mcpServers = Object.freeze((resolved.mcpServers ?? []).map(snapshotMcpServer));
|
|
3170
|
-
const configuredTools = [...resolved.tools ?? []];
|
|
3171
|
-
const staticTools = [...configuredTools, ...this.mcpServers.flatMap((server) => server.tools)];
|
|
3172
|
-
const toolIndexes = (resolved.toolIndexes ?? []).map(snapshotToolIndex);
|
|
3173
|
-
const providerTools = (resolved.providerTools ?? []).map(snapshotProviderTool);
|
|
3174
|
-
assertUniqueAgentToolNames({
|
|
3175
|
-
staticTools,
|
|
3176
|
-
providerTools,
|
|
3177
|
-
toolIndexes
|
|
3178
|
-
});
|
|
3179
|
-
const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
|
|
3180
|
-
for (const index of toolIndexes) {
|
|
3181
|
-
for (const tool of index.tools) {
|
|
3182
|
-
toolsByName.set(tool.name, tool);
|
|
3183
|
-
}
|
|
3184
|
-
}
|
|
3185
|
-
this.tools = Object.freeze([...toolsByName.values()]);
|
|
3186
|
-
const publicToolState = Object.freeze({
|
|
3187
|
-
configuredTools: Object.freeze(configuredTools),
|
|
3188
|
-
staticTools: Object.freeze(staticTools),
|
|
3189
|
-
providerTools: Object.freeze(providerTools),
|
|
3190
|
-
toolIndexes: Object.freeze(toolIndexes)
|
|
3191
|
-
});
|
|
3192
|
-
registerAgentToolState(this, publicToolState, toolsByName);
|
|
3193
|
-
this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);
|
|
3194
|
-
this.defaultMaxTurns = assertNonnegativeSafeInteger(
|
|
3195
|
-
resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,
|
|
3196
|
-
"maxTurns"
|
|
3197
|
-
);
|
|
3198
|
-
this.lifecycle = resolved.lifecycle;
|
|
3199
|
-
this.outputSchema = resolved.outputSchema;
|
|
3200
|
-
if (resolved.outputSchema !== void 0) {
|
|
3201
|
-
providerOutputSchemas.set(this, toProviderJsonSchema(resolved.outputSchema));
|
|
3202
|
-
}
|
|
3203
|
-
this.observability = snapshotAgentObservability(resolved.observability);
|
|
3204
|
-
this.guardrails = Object.freeze((resolved.guardrails ?? []).map(snapshotGuardrailPolicy));
|
|
3205
|
-
this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
|
|
3206
|
-
this.memory = snapshotAgentMemory(resolved.memory);
|
|
3207
|
-
}
|
|
3208
|
-
generate(options) {
|
|
3209
|
-
return createGenerateExecution(this, AgentRun.fromAgent(this, options)).next();
|
|
3210
|
-
}
|
|
3211
|
-
stream(options) {
|
|
3212
|
-
const run = AgentRun.fromAgent(this, options);
|
|
3213
|
-
if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {
|
|
3214
|
-
throw new Error("This completion model does not support streaming");
|
|
3215
|
-
}
|
|
3216
|
-
return createStreamExecution(this, run);
|
|
3217
|
-
}
|
|
3218
|
-
resume(pending, decision) {
|
|
3219
|
-
assertAgentApprovalDecision(decision);
|
|
3220
|
-
const continuation = approvalContinuations.get(pending);
|
|
3221
|
-
if (continuation === void 0 || continuation.agent !== this) {
|
|
3222
|
-
throw new TypeError("Approval continuation does not belong to this agent.");
|
|
3223
|
-
}
|
|
3224
|
-
approvalContinuations.delete(pending);
|
|
3225
|
-
continuation.resolve(decision);
|
|
3226
|
-
return continuation.mode === "generate" ? continuation.resume() : continuation.resume();
|
|
3227
|
-
}
|
|
3228
|
-
asTool(options) {
|
|
3229
|
-
const description = options.description ?? this.description ?? `Prompt the ${options.name} agent.`;
|
|
3230
|
-
return createTool({
|
|
3231
|
-
name: options.name,
|
|
3232
|
-
description,
|
|
3233
|
-
inputSchema: z.object({
|
|
3234
|
-
prompt: z.string().describe("The prompt to send to the agent.")
|
|
3235
|
-
}),
|
|
3236
|
-
execute: async ({ prompt }, context) => {
|
|
3237
|
-
if (options.stream === true && context.emitStreamEvent !== void 0 && this.model.capabilities.streaming && isStreamingCompletionModel(this.model)) {
|
|
3238
|
-
let completed = false;
|
|
3239
|
-
let output;
|
|
3240
|
-
const childStream = this.stream({
|
|
3241
|
-
prompt,
|
|
3242
|
-
maxTurns: options.maxTurns,
|
|
3243
|
-
abortSignal: context.abortSignal
|
|
3244
|
-
});
|
|
3245
|
-
for await (const event of childStream) {
|
|
3246
|
-
if (event.type === "approval_required") {
|
|
3247
|
-
await cancelAgentApproval(
|
|
3248
|
-
event,
|
|
3249
|
-
`Agent tool "${options.name}" cannot suspend for tool approval.`
|
|
3250
|
-
);
|
|
3251
|
-
throw new Error(
|
|
3252
|
-
`Agent tool "${options.name}" cannot suspend for tool approval. Run the agent directly to handle approvals.`
|
|
3253
|
-
);
|
|
3254
|
-
}
|
|
3255
|
-
const streamEvent = {
|
|
3256
|
-
agentId: this.id,
|
|
3257
|
-
event
|
|
3258
|
-
};
|
|
3259
|
-
if (this.name !== void 0) {
|
|
3260
|
-
streamEvent.agentName = this.name;
|
|
3261
|
-
}
|
|
3262
|
-
await context.emitStreamEvent(streamEvent);
|
|
3263
|
-
if (event.type === "error") {
|
|
3264
|
-
throw event.error;
|
|
3265
|
-
}
|
|
3266
|
-
if (event.type === "final") {
|
|
3267
|
-
if (event.result.status === "blocked") {
|
|
3268
|
-
throw new AgentRunBlockedError(event.result);
|
|
3269
|
-
}
|
|
3270
|
-
output = event.result.output;
|
|
3271
|
-
completed = true;
|
|
3272
|
-
}
|
|
3273
|
-
}
|
|
3274
|
-
if (!completed) {
|
|
3275
|
-
throw new Error(`Agent tool "${options.name}" ended without a final result.`);
|
|
3276
|
-
}
|
|
3277
|
-
return output;
|
|
3278
|
-
}
|
|
3279
|
-
const response = await this.generate({
|
|
3280
|
-
prompt,
|
|
3281
|
-
maxTurns: options.maxTurns,
|
|
3282
|
-
abortSignal: context.abortSignal
|
|
3283
|
-
});
|
|
3284
|
-
if (response.status === "approval_required") {
|
|
3285
|
-
await cancelAgentApproval(
|
|
3286
|
-
response,
|
|
3287
|
-
`Agent tool "${options.name}" cannot suspend for tool approval.`
|
|
3288
|
-
);
|
|
3289
|
-
throw new Error(
|
|
3290
|
-
`Agent tool "${options.name}" cannot suspend for tool approval. Run the agent directly to handle approvals.`
|
|
3291
|
-
);
|
|
3292
|
-
}
|
|
3293
|
-
if (response.status === "blocked") {
|
|
3294
|
-
throw new AgentRunBlockedError(response);
|
|
3295
|
-
}
|
|
3296
|
-
return response.output;
|
|
3297
|
-
}
|
|
3298
|
-
});
|
|
3299
|
-
}
|
|
3300
|
-
getTool(toolName) {
|
|
3301
|
-
return getRegisteredAgentTool(this, toolName);
|
|
3302
|
-
}
|
|
3303
|
-
async callTool(toolName, args, context) {
|
|
3304
|
-
const tool = this.getTool(toolName);
|
|
3305
|
-
if (tool === void 0) {
|
|
3306
|
-
throw new ToolNotFoundError(toolName);
|
|
3307
|
-
}
|
|
3308
|
-
return prepareToolCall(tool, args).call(context ?? {});
|
|
3309
|
-
}
|
|
3310
|
-
};
|
|
4232
|
+
// src/agent/resolve-options.ts
|
|
3311
4233
|
var resolvedAgentOptions = /* @__PURE__ */ Symbol("resolvedAgentOptions");
|
|
3312
|
-
function createResolvedAgent(options) {
|
|
3313
|
-
return new Agent({
|
|
3314
|
-
...options,
|
|
3315
|
-
[resolvedAgentOptions]: true
|
|
3316
|
-
});
|
|
3317
|
-
}
|
|
3318
|
-
function getResolvedAgentOptions(agent) {
|
|
3319
|
-
const toolState = getAgentToolState(agent);
|
|
3320
|
-
return {
|
|
3321
|
-
id: agent.id,
|
|
3322
|
-
name: agent.name,
|
|
3323
|
-
description: agent.description,
|
|
3324
|
-
model: agent.model,
|
|
3325
|
-
instructions: agent.instructions,
|
|
3326
|
-
context: [...agent.context],
|
|
3327
|
-
temperature: agent.temperature,
|
|
3328
|
-
maxTokens: agent.maxTokens,
|
|
3329
|
-
providerOptions: agent.providerOptions,
|
|
3330
|
-
retries: agent.retries,
|
|
3331
|
-
tools: [...toolState.configuredTools],
|
|
3332
|
-
mcpServers: [...agent.mcpServers],
|
|
3333
|
-
providerTools: [...toolState.providerTools],
|
|
3334
|
-
toolIndexes: [...toolState.toolIndexes],
|
|
3335
|
-
toolChoice: agent.toolChoice,
|
|
3336
|
-
defaultMaxTurns: agent.defaultMaxTurns,
|
|
3337
|
-
lifecycle: agent.lifecycle,
|
|
3338
|
-
outputSchema: agent.outputSchema,
|
|
3339
|
-
observability: agent.observability,
|
|
3340
|
-
guardrails: [...agent.guardrails],
|
|
3341
|
-
middlewares: [...agent.middlewares],
|
|
3342
|
-
memory: agent.memory
|
|
3343
|
-
};
|
|
3344
|
-
}
|
|
3345
|
-
function getAgentProviderOutputSchema(agent) {
|
|
3346
|
-
return providerOutputSchemas.get(agent);
|
|
3347
|
-
}
|
|
3348
4234
|
function resolveAgentOptions(options) {
|
|
3349
4235
|
if (isInternalAgentOptions(options)) {
|
|
3350
4236
|
return options;
|
|
@@ -3404,38 +4290,27 @@ function resolveAgentOptions(options) {
|
|
|
3404
4290
|
memory
|
|
3405
4291
|
};
|
|
3406
4292
|
}
|
|
3407
|
-
function
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
}
|
|
3412
|
-
for (const tool of options.providerTools) {
|
|
3413
|
-
registerToolOwner(owners, tool.name, "provider tool");
|
|
3414
|
-
}
|
|
3415
|
-
for (const [indexPosition, index] of options.toolIndexes.entries()) {
|
|
3416
|
-
if (!isToolIndex(index)) {
|
|
3417
|
-
throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
|
|
3418
|
-
}
|
|
3419
|
-
assertPositiveSearchLimit(index.topK);
|
|
3420
|
-
assertFiniteMinScore(index.minScore);
|
|
3421
|
-
for (const tool of index.tools) {
|
|
3422
|
-
if (isMcpTool(tool)) {
|
|
3423
|
-
throw new TypeError(
|
|
3424
|
-
`MCP tool "${tool.name}" must be registered through Agent.mcpServers, not a tool index.`
|
|
3425
|
-
);
|
|
3426
|
-
}
|
|
3427
|
-
registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);
|
|
3428
|
-
}
|
|
3429
|
-
}
|
|
4293
|
+
function markResolvedAgentOptions(options) {
|
|
4294
|
+
return {
|
|
4295
|
+
...options,
|
|
4296
|
+
[resolvedAgentOptions]: true
|
|
4297
|
+
};
|
|
3430
4298
|
}
|
|
3431
|
-
function
|
|
3432
|
-
|
|
3433
|
-
|
|
4299
|
+
function isInternalAgentOptions(options) {
|
|
4300
|
+
return options[resolvedAgentOptions] === true;
|
|
4301
|
+
}
|
|
4302
|
+
function resolveAgentMemory(options) {
|
|
4303
|
+
if (options.memory === void 0) {
|
|
4304
|
+
return void 0;
|
|
4305
|
+
}
|
|
4306
|
+
const { store, ...memoryOptions } = options.memory;
|
|
4307
|
+
const resolvedOptions = resolveMemoryOptions(memoryOptions);
|
|
4308
|
+
if (resolvedOptions.compaction !== void 0 && store.compaction === void 0) {
|
|
3434
4309
|
throw new TypeError(
|
|
3435
|
-
|
|
4310
|
+
"Memory compaction requires a store with the optional compaction capability."
|
|
3436
4311
|
);
|
|
3437
4312
|
}
|
|
3438
|
-
|
|
4313
|
+
return { store, ...resolvedOptions };
|
|
3439
4314
|
}
|
|
3440
4315
|
function addUniqueTool(tools, tool, source) {
|
|
3441
4316
|
if (tools.has(tool.name)) {
|
|
@@ -3443,12 +4318,16 @@ function addUniqueTool(tools, tool, source) {
|
|
|
3443
4318
|
}
|
|
3444
4319
|
tools.set(tool.name, tool);
|
|
3445
4320
|
}
|
|
3446
|
-
|
|
3447
|
-
|
|
4321
|
+
|
|
4322
|
+
// src/agent/snapshot.ts
|
|
4323
|
+
function snapshotAgentContext(inputs) {
|
|
4324
|
+
const context = (inputs ?? []).map(snapshotContextInput);
|
|
4325
|
+
for (const input of context) {
|
|
3448
4326
|
if (!isVectorContext(input)) continue;
|
|
3449
4327
|
assertPositiveSearchLimit(input.topK);
|
|
3450
4328
|
assertFiniteMinScore(input.minScore);
|
|
3451
4329
|
}
|
|
4330
|
+
return Object.freeze(context);
|
|
3452
4331
|
}
|
|
3453
4332
|
function snapshotAgentObservability(observability) {
|
|
3454
4333
|
if (observability === void 0) return void 0;
|
|
@@ -3471,211 +4350,174 @@ function snapshotAgentObservability(observability) {
|
|
|
3471
4350
|
if (errorPolicy !== "ignore" && errorPolicy !== "throw") {
|
|
3472
4351
|
throw new TypeError('Agent observability.errorPolicy must be "ignore" or "throw".');
|
|
3473
4352
|
}
|
|
3474
|
-
|
|
4353
|
+
let snapshot = {
|
|
3475
4354
|
observers: Object.freeze(observers),
|
|
3476
|
-
...observability.primaryTrace === void 0 ? {} : { primaryTrace: observability.primaryTrace },
|
|
3477
4355
|
errorPolicy
|
|
3478
|
-
}
|
|
4356
|
+
};
|
|
4357
|
+
if (observability.primaryTrace !== void 0) {
|
|
4358
|
+
snapshot = { ...snapshot, primaryTrace: observability.primaryTrace };
|
|
4359
|
+
}
|
|
4360
|
+
return Object.freeze(snapshot);
|
|
3479
4361
|
}
|
|
3480
|
-
function
|
|
3481
|
-
return
|
|
4362
|
+
function snapshotGuardrailPolicies(policies) {
|
|
4363
|
+
return Object.freeze((policies ?? []).map(snapshotGuardrailPolicy));
|
|
3482
4364
|
}
|
|
3483
|
-
function
|
|
3484
|
-
if (
|
|
4365
|
+
function snapshotAgentMemory(memory) {
|
|
4366
|
+
if (memory === void 0) {
|
|
3485
4367
|
return void 0;
|
|
3486
4368
|
}
|
|
3487
|
-
const
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
4369
|
+
const compaction = memory.compaction === void 0 ? void 0 : Object.freeze({
|
|
4370
|
+
...memory.compaction,
|
|
4371
|
+
trigger: Object.freeze({ ...memory.compaction.trigger }),
|
|
4372
|
+
retention: Object.freeze({ ...memory.compaction.retention }),
|
|
4373
|
+
conflictRetries: memory.compaction.conflictRetries === false ? false : Object.freeze({ ...memory.compaction.conflictRetries })
|
|
4374
|
+
});
|
|
4375
|
+
let snapshot = {
|
|
4376
|
+
store: memory.store,
|
|
4377
|
+
savePolicy: memory.savePolicy
|
|
4378
|
+
};
|
|
4379
|
+
if (compaction !== void 0) {
|
|
4380
|
+
snapshot = { ...snapshot, compaction };
|
|
3493
4381
|
}
|
|
3494
|
-
return
|
|
4382
|
+
return Object.freeze(snapshot);
|
|
3495
4383
|
}
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
const
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
});
|
|
3524
|
-
return pending;
|
|
3525
|
-
},
|
|
3526
|
-
async cancel(reason) {
|
|
3527
|
-
run.cancel(reason);
|
|
3528
|
-
await completion.catch(() => void 0);
|
|
4384
|
+
function cloneFrozenPlainData(value) {
|
|
4385
|
+
if (Array.isArray(value)) {
|
|
4386
|
+
return Object.freeze(value.map(cloneFrozenPlainData));
|
|
4387
|
+
}
|
|
4388
|
+
if (typeof value !== "object" || value === null) {
|
|
4389
|
+
return value;
|
|
4390
|
+
}
|
|
4391
|
+
const prototype = Object.getPrototypeOf(value);
|
|
4392
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
4393
|
+
return value;
|
|
4394
|
+
}
|
|
4395
|
+
const clone = Object.fromEntries(
|
|
4396
|
+
Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)])
|
|
4397
|
+
);
|
|
4398
|
+
return Object.freeze(clone);
|
|
4399
|
+
}
|
|
4400
|
+
function snapshotContextInput(input) {
|
|
4401
|
+
if (!isVectorContext(input)) {
|
|
4402
|
+
let document = {
|
|
4403
|
+
id: input.id,
|
|
4404
|
+
text: input.text
|
|
4405
|
+
};
|
|
4406
|
+
if (input.additionalProps !== void 0) {
|
|
4407
|
+
document = {
|
|
4408
|
+
...document,
|
|
4409
|
+
additionalProps: cloneFrozenPlainData(input.additionalProps)
|
|
4410
|
+
};
|
|
3529
4411
|
}
|
|
4412
|
+
return Object.freeze(document);
|
|
4413
|
+
}
|
|
4414
|
+
const format = input.format;
|
|
4415
|
+
let shared = {
|
|
4416
|
+
kind: "vector-context",
|
|
4417
|
+
store: input.store,
|
|
4418
|
+
topK: input.topK
|
|
3530
4419
|
};
|
|
3531
|
-
|
|
3532
|
-
}
|
|
3533
|
-
var StreamExecution = class {
|
|
3534
|
-
constructor(agent, run) {
|
|
3535
|
-
this.agent = agent;
|
|
3536
|
-
this.run = run;
|
|
3537
|
-
this.iterator = run.events()[Symbol.asyncIterator]();
|
|
4420
|
+
if (input.minScore !== void 0) {
|
|
4421
|
+
shared = { ...shared, minScore: input.minScore };
|
|
3538
4422
|
}
|
|
3539
|
-
|
|
3540
|
-
|
|
3541
|
-
iterator;
|
|
3542
|
-
nextEvent;
|
|
3543
|
-
phase = "active";
|
|
3544
|
-
segment() {
|
|
3545
|
-
if (this.phase === "approval") {
|
|
3546
|
-
this.phase = "active";
|
|
3547
|
-
}
|
|
3548
|
-
return new DefaultAgentStream(this);
|
|
4423
|
+
if (input.filter !== void 0) {
|
|
4424
|
+
shared = { ...shared, filter: cloneFrozenPlainData(input.filter) };
|
|
3549
4425
|
}
|
|
3550
|
-
|
|
3551
|
-
|
|
4426
|
+
if (input.retries !== void 0) {
|
|
4427
|
+
shared = { ...shared, retries: cloneFrozenPlainData(input.retries) };
|
|
3552
4428
|
}
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
outcome = await Promise.race([
|
|
3559
|
-
this.nextEvent.then((event) => ({ type: "event", event })),
|
|
3560
|
-
this.run.waitForApproval().then(() => ({ type: "approval" }))
|
|
3561
|
-
]);
|
|
3562
|
-
} catch (error) {
|
|
3563
|
-
this.phase = "terminal";
|
|
3564
|
-
throw error;
|
|
3565
|
-
}
|
|
3566
|
-
if (outcome.type === "approval") {
|
|
3567
|
-
this.phase = "approval";
|
|
3568
|
-
const pending = this.run.approvalEvent();
|
|
3569
|
-
approvalContinuations.set(pending, {
|
|
3570
|
-
agent: this.agent,
|
|
3571
|
-
mode: "stream",
|
|
3572
|
-
resolve: (decision) => this.run.resolveApproval(decision),
|
|
3573
|
-
resume: () => this.segment(),
|
|
3574
|
-
cancel: (reason) => this.cancel(reason)
|
|
3575
|
-
});
|
|
3576
|
-
yield pending;
|
|
3577
|
-
return;
|
|
3578
|
-
}
|
|
3579
|
-
this.nextEvent = void 0;
|
|
3580
|
-
if (outcome.event.done) {
|
|
3581
|
-
this.phase = "terminal";
|
|
3582
|
-
return;
|
|
3583
|
-
}
|
|
3584
|
-
yield outcome.event.value;
|
|
3585
|
-
}
|
|
4429
|
+
if (format !== void 0) {
|
|
4430
|
+
shared = {
|
|
4431
|
+
...shared,
|
|
4432
|
+
format: (result) => format.call(input, result)
|
|
4433
|
+
};
|
|
3586
4434
|
}
|
|
3587
|
-
|
|
3588
|
-
return
|
|
4435
|
+
if (!("models" in input) || input.models === void 0) {
|
|
4436
|
+
return Object.freeze({ ...shared, store: input.store, model: input.model });
|
|
3589
4437
|
}
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
await this.iterator.return?.();
|
|
3598
|
-
} catch {
|
|
3599
|
-
}
|
|
4438
|
+
let context = {
|
|
4439
|
+
...shared,
|
|
4440
|
+
store: input.store,
|
|
4441
|
+
models: input.models
|
|
4442
|
+
};
|
|
4443
|
+
if (input.fusion !== void 0) {
|
|
4444
|
+
context = { ...context, fusion: input.fusion };
|
|
3600
4445
|
}
|
|
3601
|
-
|
|
3602
|
-
function createStreamExecution(agent, run) {
|
|
3603
|
-
return new StreamExecution(agent, run).segment();
|
|
4446
|
+
return Object.freeze(context);
|
|
3604
4447
|
}
|
|
3605
|
-
|
|
3606
|
-
|
|
3607
|
-
|
|
4448
|
+
function snapshotGuardrailPolicy(policy) {
|
|
4449
|
+
return Object.freeze({
|
|
4450
|
+
...policy,
|
|
4451
|
+
input: Object.freeze([...policy.input]),
|
|
4452
|
+
output: Object.freeze([...policy.output])
|
|
4453
|
+
});
|
|
4454
|
+
}
|
|
4455
|
+
|
|
4456
|
+
// src/agent/tool-catalog.ts
|
|
4457
|
+
function prepareAgentTools(options) {
|
|
4458
|
+
assertUniqueMcpServerNames(options.mcpServers ?? []);
|
|
4459
|
+
const mcpServers = Object.freeze((options.mcpServers ?? []).map(snapshotMcpServer));
|
|
4460
|
+
const configuredTools = [...options.tools ?? []];
|
|
4461
|
+
const staticTools = [...configuredTools, ...mcpServers.flatMap((server) => server.tools)];
|
|
4462
|
+
const toolIndexes = (options.toolIndexes ?? []).map(snapshotToolIndex);
|
|
4463
|
+
const providerTools = (options.providerTools ?? []).map(snapshotProviderTool);
|
|
4464
|
+
assertUniqueAgentToolNames({ staticTools, providerTools, toolIndexes });
|
|
4465
|
+
const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
|
|
4466
|
+
for (const index of toolIndexes) {
|
|
4467
|
+
for (const tool of index.tools) {
|
|
4468
|
+
toolsByName.set(tool.name, tool);
|
|
4469
|
+
}
|
|
3608
4470
|
}
|
|
3609
|
-
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
4471
|
+
const tools = Object.freeze([...toolsByName.values()]);
|
|
4472
|
+
const publicState = Object.freeze({
|
|
4473
|
+
configuredTools: Object.freeze(configuredTools),
|
|
4474
|
+
staticTools: Object.freeze(staticTools),
|
|
4475
|
+
providerTools: Object.freeze(providerTools),
|
|
4476
|
+
toolIndexes: Object.freeze(toolIndexes)
|
|
4477
|
+
});
|
|
4478
|
+
return { mcpServers, tools, publicState, toolsByName };
|
|
4479
|
+
}
|
|
4480
|
+
function assertUniqueAgentToolNames(options) {
|
|
4481
|
+
const owners = /* @__PURE__ */ new Map();
|
|
4482
|
+
for (const tool of options.staticTools) {
|
|
4483
|
+
registerToolOwner(owners, tool.name, isMcpTool(tool) ? "MCP tool" : "local or skill tool");
|
|
3614
4484
|
}
|
|
3615
|
-
|
|
3616
|
-
|
|
4485
|
+
for (const tool of options.providerTools) {
|
|
4486
|
+
registerToolOwner(owners, tool.name, "provider tool");
|
|
3617
4487
|
}
|
|
3618
|
-
|
|
3619
|
-
if (
|
|
3620
|
-
throw new
|
|
3621
|
-
}
|
|
3622
|
-
if (this.consuming) {
|
|
3623
|
-
throw new Error("Agent stream is already running.");
|
|
4488
|
+
for (const [indexPosition, index] of options.toolIndexes.entries()) {
|
|
4489
|
+
if (!isToolIndex(index)) {
|
|
4490
|
+
throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
|
|
3624
4491
|
}
|
|
3625
|
-
|
|
3626
|
-
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
await this.execution.cancel("Agent stream consumer closed the stream.");
|
|
4492
|
+
assertPositiveSearchLimit(index.topK);
|
|
4493
|
+
assertFiniteMinScore(index.minScore);
|
|
4494
|
+
for (const tool of index.tools) {
|
|
4495
|
+
if (isMcpTool(tool)) {
|
|
4496
|
+
throw new TypeError(
|
|
4497
|
+
`MCP tool "${tool.name}" must be registered through Agent.mcpServers, not a tool index.`
|
|
4498
|
+
);
|
|
3633
4499
|
}
|
|
3634
|
-
|
|
3635
|
-
this.completed = true;
|
|
4500
|
+
registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);
|
|
3636
4501
|
}
|
|
3637
4502
|
}
|
|
3638
|
-
};
|
|
3639
|
-
async function cancelAgentApproval(pending, reason) {
|
|
3640
|
-
const continuation = approvalContinuations.get(pending);
|
|
3641
|
-
if (continuation === void 0) {
|
|
3642
|
-
return;
|
|
3643
|
-
}
|
|
3644
|
-
approvalContinuations.delete(pending);
|
|
3645
|
-
await continuation.cancel(reason);
|
|
3646
4503
|
}
|
|
3647
|
-
function
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
});
|
|
4504
|
+
function registerToolOwner(owners, name, owner) {
|
|
4505
|
+
const existing = owners.get(name);
|
|
4506
|
+
if (existing !== void 0) {
|
|
4507
|
+
throw new TypeError(
|
|
4508
|
+
`Tool name collision for "${name}" between ${existing} and ${owner}. Tool names must be unique across every Agent tool source.`
|
|
4509
|
+
);
|
|
3654
4510
|
}
|
|
3655
|
-
|
|
3656
|
-
const shared = {
|
|
3657
|
-
kind: "vector-context",
|
|
3658
|
-
store: input.store,
|
|
3659
|
-
topK: input.topK,
|
|
3660
|
-
...input.minScore === void 0 ? {} : { minScore: input.minScore },
|
|
3661
|
-
...input.filter === void 0 ? {} : { filter: cloneFrozenPlainData(input.filter) },
|
|
3662
|
-
...input.retries === void 0 ? {} : { retries: cloneFrozenPlainData(input.retries) },
|
|
3663
|
-
...format === void 0 ? {} : { format: (result) => format.call(input, result) }
|
|
3664
|
-
};
|
|
3665
|
-
return Object.freeze(
|
|
3666
|
-
"models" in input && input.models !== void 0 ? {
|
|
3667
|
-
...shared,
|
|
3668
|
-
store: input.store,
|
|
3669
|
-
models: input.models,
|
|
3670
|
-
...input.fusion === void 0 ? {} : { fusion: input.fusion }
|
|
3671
|
-
} : { ...shared, store: input.store, model: input.model }
|
|
3672
|
-
);
|
|
4511
|
+
owners.set(name, owner);
|
|
3673
4512
|
}
|
|
3674
4513
|
function snapshotProviderTool(tool) {
|
|
3675
|
-
|
|
3676
|
-
...tool
|
|
3677
|
-
|
|
3678
|
-
|
|
4514
|
+
let snapshot = {
|
|
4515
|
+
...tool
|
|
4516
|
+
};
|
|
4517
|
+
if (tool.configuration !== void 0) {
|
|
4518
|
+
snapshot = { ...snapshot, configuration: cloneFrozenPlainData(tool.configuration) };
|
|
4519
|
+
}
|
|
4520
|
+
return Object.freeze(snapshot);
|
|
3679
4521
|
}
|
|
3680
4522
|
function snapshotMcpServer(server) {
|
|
3681
4523
|
if (server.name.trim() === "") {
|
|
@@ -3692,27 +4534,42 @@ function snapshotMcpServer(server) {
|
|
|
3692
4534
|
}
|
|
3693
4535
|
}
|
|
3694
4536
|
const tools = server.tools.map(snapshotMcpTool);
|
|
3695
|
-
|
|
4537
|
+
let snapshot = {
|
|
3696
4538
|
name: server.name,
|
|
3697
|
-
tools: Object.freeze(tools)
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
}
|
|
4539
|
+
tools: Object.freeze(tools)
|
|
4540
|
+
};
|
|
4541
|
+
if (server.serverInfo !== void 0) {
|
|
4542
|
+
snapshot = { ...snapshot, serverInfo: cloneFrozenPlainData(server.serverInfo) };
|
|
4543
|
+
}
|
|
4544
|
+
if (server.capabilities !== void 0) {
|
|
4545
|
+
snapshot = { ...snapshot, capabilities: cloneFrozenPlainData(server.capabilities) };
|
|
4546
|
+
}
|
|
4547
|
+
if (server.instructions !== void 0) {
|
|
4548
|
+
snapshot = { ...snapshot, instructions: server.instructions };
|
|
4549
|
+
}
|
|
4550
|
+
return Object.freeze(snapshot);
|
|
3702
4551
|
}
|
|
3703
4552
|
function snapshotMcpTool(tool) {
|
|
3704
4553
|
if (Object.isFrozen(tool) && Object.isFrozen(tool.mcp)) {
|
|
3705
4554
|
return tool;
|
|
3706
4555
|
}
|
|
3707
4556
|
const parseInput = tool.parseInput;
|
|
3708
|
-
|
|
4557
|
+
let snapshot = {
|
|
3709
4558
|
name: tool.name,
|
|
3710
4559
|
mcp: Object.freeze({ ...tool.mcp }),
|
|
3711
|
-
...tool.requiresApproval === void 0 ? {} : { requiresApproval: tool.requiresApproval },
|
|
3712
4560
|
definition: (prompt) => tool.definition(prompt),
|
|
3713
|
-
call: (args, context) => tool.call(args, context)
|
|
3714
|
-
|
|
3715
|
-
|
|
4561
|
+
call: (args, context) => tool.call(args, context)
|
|
4562
|
+
};
|
|
4563
|
+
if (tool.requiresApproval !== void 0) {
|
|
4564
|
+
snapshot = { ...snapshot, requiresApproval: tool.requiresApproval };
|
|
4565
|
+
}
|
|
4566
|
+
if (parseInput !== void 0) {
|
|
4567
|
+
snapshot = {
|
|
4568
|
+
...snapshot,
|
|
4569
|
+
parseInput: (args) => parseInput.call(tool, args)
|
|
4570
|
+
};
|
|
4571
|
+
}
|
|
4572
|
+
return Object.freeze(snapshot);
|
|
3716
4573
|
}
|
|
3717
4574
|
function assertUniqueMcpServerNames(servers) {
|
|
3718
4575
|
const names = /* @__PURE__ */ new Set();
|
|
@@ -3725,69 +4582,118 @@ function assertUniqueMcpServerNames(servers) {
|
|
|
3725
4582
|
}
|
|
3726
4583
|
function snapshotToolIndex(index) {
|
|
3727
4584
|
const inspect = index.inspect;
|
|
3728
|
-
|
|
4585
|
+
let snapshot = {
|
|
3729
4586
|
kind: "tool-index",
|
|
3730
4587
|
tools: Object.freeze([...index.tools]),
|
|
3731
4588
|
topK: index.topK,
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
});
|
|
3737
|
-
}
|
|
3738
|
-
function snapshotGuardrailPolicy(policy) {
|
|
3739
|
-
return Object.freeze({
|
|
3740
|
-
...policy,
|
|
3741
|
-
input: Object.freeze([...policy.input]),
|
|
3742
|
-
output: Object.freeze([...policy.output])
|
|
3743
|
-
});
|
|
3744
|
-
}
|
|
3745
|
-
function snapshotAgentMemory(memory) {
|
|
3746
|
-
if (memory === void 0) {
|
|
3747
|
-
return void 0;
|
|
4589
|
+
search: (options) => index.search(options)
|
|
4590
|
+
};
|
|
4591
|
+
if (index.minScore !== void 0) {
|
|
4592
|
+
snapshot = { ...snapshot, minScore: index.minScore };
|
|
3748
4593
|
}
|
|
3749
|
-
|
|
3750
|
-
...
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
});
|
|
4594
|
+
if (index.filter !== void 0) {
|
|
4595
|
+
snapshot = { ...snapshot, filter: cloneFrozenPlainData(index.filter) };
|
|
4596
|
+
}
|
|
4597
|
+
if (inspect !== void 0) {
|
|
4598
|
+
snapshot = {
|
|
4599
|
+
...snapshot,
|
|
4600
|
+
inspect: (request) => inspect.call(index, request)
|
|
4601
|
+
};
|
|
4602
|
+
}
|
|
4603
|
+
return Object.freeze(snapshot);
|
|
3760
4604
|
}
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
4605
|
+
|
|
4606
|
+
// src/agent/agent.ts
|
|
4607
|
+
var DEFAULT_MAX_TURNS = 20;
|
|
4608
|
+
var Agent = class {
|
|
4609
|
+
id;
|
|
4610
|
+
name;
|
|
4611
|
+
description;
|
|
4612
|
+
model;
|
|
4613
|
+
instructions;
|
|
4614
|
+
context;
|
|
4615
|
+
temperature;
|
|
4616
|
+
maxTokens;
|
|
4617
|
+
providerOptions;
|
|
4618
|
+
retries;
|
|
4619
|
+
mcpServers;
|
|
4620
|
+
tools;
|
|
4621
|
+
toolChoice;
|
|
4622
|
+
defaultMaxTurns;
|
|
4623
|
+
lifecycle;
|
|
4624
|
+
outputSchema;
|
|
4625
|
+
observability;
|
|
4626
|
+
guardrails;
|
|
4627
|
+
middlewares;
|
|
4628
|
+
memory;
|
|
4629
|
+
constructor(options) {
|
|
4630
|
+
const resolved = resolveAgentOptions(options);
|
|
4631
|
+
this.id = normalizeAgentId(resolved.id);
|
|
4632
|
+
this.name = resolved.name;
|
|
4633
|
+
this.description = resolved.description;
|
|
4634
|
+
this.model = resolved.model;
|
|
4635
|
+
this.instructions = resolved.instructions;
|
|
4636
|
+
this.context = snapshotAgentContext(resolved.context);
|
|
4637
|
+
this.temperature = resolved.temperature;
|
|
4638
|
+
this.maxTokens = resolved.maxTokens;
|
|
4639
|
+
this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
|
|
4640
|
+
this.retries = cloneFrozenPlainData(resolved.retries);
|
|
4641
|
+
const preparedTools = prepareAgentTools(resolved);
|
|
4642
|
+
this.mcpServers = preparedTools.mcpServers;
|
|
4643
|
+
this.tools = preparedTools.tools;
|
|
4644
|
+
registerAgentToolState(this, preparedTools.publicState, preparedTools.toolsByName);
|
|
4645
|
+
this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);
|
|
4646
|
+
this.defaultMaxTurns = assertNonnegativeSafeInteger(
|
|
4647
|
+
resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,
|
|
4648
|
+
"maxTurns"
|
|
4649
|
+
);
|
|
4650
|
+
this.lifecycle = resolved.lifecycle;
|
|
4651
|
+
this.outputSchema = resolved.outputSchema;
|
|
4652
|
+
registerAgentProviderOutputSchema(this, resolved.outputSchema);
|
|
4653
|
+
this.observability = snapshotAgentObservability(resolved.observability);
|
|
4654
|
+
this.guardrails = snapshotGuardrailPolicies(resolved.guardrails);
|
|
4655
|
+
this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
|
|
4656
|
+
this.memory = snapshotAgentMemory(resolved.memory);
|
|
3764
4657
|
}
|
|
3765
|
-
|
|
3766
|
-
return
|
|
4658
|
+
generate(options) {
|
|
4659
|
+
return AgentRun.fromAgent(this, options).generate();
|
|
3767
4660
|
}
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
4661
|
+
stream(options) {
|
|
4662
|
+
const run = AgentRun.fromAgent(this, options);
|
|
4663
|
+
if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {
|
|
4664
|
+
throw new Error("This completion model does not support streaming");
|
|
4665
|
+
}
|
|
4666
|
+
return createAgentStream(run);
|
|
3771
4667
|
}
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
4668
|
+
asTool(options) {
|
|
4669
|
+
return createAgentTool(this, options);
|
|
4670
|
+
}
|
|
4671
|
+
getTool(toolName) {
|
|
4672
|
+
return getRegisteredAgentTool(this, toolName);
|
|
4673
|
+
}
|
|
4674
|
+
async callTool(toolName, args, context) {
|
|
4675
|
+
const tool = this.getTool(toolName);
|
|
4676
|
+
if (tool === void 0) {
|
|
4677
|
+
throw new ToolNotFoundError(toolName);
|
|
4678
|
+
}
|
|
4679
|
+
return prepareToolCall(tool, args).call(context ?? {});
|
|
4680
|
+
}
|
|
4681
|
+
};
|
|
3777
4682
|
|
|
3778
4683
|
export {
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
4684
|
+
agentInteractionRequestSchema,
|
|
4685
|
+
agentInteractionResponseSchema,
|
|
4686
|
+
agentContinuationSchema,
|
|
4687
|
+
parseAgentInteractionRequest,
|
|
4688
|
+
parseAgentInteractionResponse,
|
|
4689
|
+
parseAgentContinuation,
|
|
4690
|
+
assertAgentInteractionResponse,
|
|
3782
4691
|
getAgentToolState,
|
|
3783
4692
|
createHook,
|
|
3784
|
-
getAgentApprovalRequestDetails,
|
|
3785
4693
|
createVectorContext,
|
|
3786
4694
|
isVectorContext,
|
|
3787
4695
|
withInternalAgentRunOptions,
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
getResolvedAgentOptions,
|
|
3791
|
-
cancelAgentApproval
|
|
4696
|
+
markResolvedAgentOptions,
|
|
4697
|
+
Agent
|
|
3792
4698
|
};
|
|
3793
|
-
//# sourceMappingURL=chunk-
|
|
4699
|
+
//# sourceMappingURL=chunk-5GXSQYQT.js.map
|