@dsh-agentic-roleplay/core 0.3.2 → 0.3.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/lib/authoring.js +15 -255
- package/lib/child-CFjnaTZt.js +435 -0
- package/lib/client.js +2852 -586
- package/lib/client.js.map +1 -1
- package/lib/{deliver-BSsDtF6X.js → deliver-CpZOxBX5.js} +145 -1622
- package/lib/doctor-chat-ByDfCMeo.js +17 -0
- package/lib/doctor.js +171 -0
- package/lib/{gallery-DS5-qH9F.js → gallery-CtFDL22W.js} +2 -2
- package/lib/{generator-BzeepLd2.js → generator-B6FxlKOV.js} +2 -378
- package/lib/hooks-KTCR3fNJ.js +1060 -0
- package/lib/images.js +3 -3
- package/lib/index.js +1365 -201
- package/lib/language-DWVwi1R7.js +520 -0
- package/lib/orchestration.js +142 -1146
- package/lib/{documents-B5XAdfo2.js → pack-jail-CybSNzxr.js} +869 -80
- package/lib/{packs-BCGK9KZV.js → packs-BYjrAen6.js} +4 -518
- package/lib/{presenter-agent-Cp-J0onD.js → presenter-agent-CiEVKcjJ.js} +4 -3
- package/lib/reflection-waxFg1x-.js +1843 -0
- package/package.json +3 -2
- package/prompts/en/doctor/persona.md +1 -0
- package/prompts/en/doctor/procedure.md +5 -0
- package/prompts/en/doctor/welcome.md +1 -0
- package/prompts/en/import/character.md +1 -0
- package/prompts/en/roleplay/record-keeper.md +2 -2
- package/prompts/en/roleplay/reflection-check.md +5 -0
- package/prompts/en/roleplay/reflection.md +2 -0
- package/prompts/zh/doctor/persona.md +1 -0
- package/prompts/zh/doctor/procedure.md +5 -0
- package/prompts/zh/doctor/welcome.md +1 -0
- package/prompts/zh/import/character.md +1 -0
- package/prompts/zh/roleplay/record-keeper.md +2 -2
- package/prompts/zh/roleplay/reflection-check.md +5 -0
- package/prompts/zh/roleplay/reflection.md +2 -0
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
3
|
+
import { ReasoningEffortId, createUserMessage, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
|
|
4
|
+
import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
|
|
5
|
+
import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
|
|
6
|
+
//#region src/host/agents/budget.ts
|
|
7
|
+
/** Tokens a text of a number of characters comes to: a character of a script written without spaces takes about one and a half, of the others about a third. */
|
|
8
|
+
function tokensOf$1(characters, language) {
|
|
9
|
+
return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The most tokens to let a request produce, for an answer estimated at some tokens: the estimate with room to spare (`headroom` times it, rounded up to ten). The room is
|
|
13
|
+
* for a model that thinks or says a little before it answers; what is far more than that is a model that does not stop, and is cut off instead of waited for.
|
|
14
|
+
*/
|
|
15
|
+
function outputBudget(estimate, headroom) {
|
|
16
|
+
return Math.ceil(estimate * headroom / 10) * 10;
|
|
17
|
+
}
|
|
18
|
+
/** The estimate of an answer made of texts that each have a declared limit in characters. */
|
|
19
|
+
function estimateAnswer(limits, language) {
|
|
20
|
+
return limits.reduce((sum, limit) => sum + tokensOf$1(limit, language) + 8, 0);
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/host/orchestration/current-turn.ts
|
|
24
|
+
/** The last turn the session started. */
|
|
25
|
+
function currentTurn(agent) {
|
|
26
|
+
const events = agent.session.snapshotEvents();
|
|
27
|
+
for (let index = events.length - 1; index >= 0; index--) {
|
|
28
|
+
const event = events[index];
|
|
29
|
+
if (event?.type === "turn/start") return event.data.turn;
|
|
30
|
+
}
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/shared/usage.ts
|
|
35
|
+
const NO_TOKENS = {
|
|
36
|
+
input: 0,
|
|
37
|
+
cached: 0,
|
|
38
|
+
output: 0
|
|
39
|
+
};
|
|
40
|
+
const addTokens = (a, b) => ({
|
|
41
|
+
input: a.input + b.input,
|
|
42
|
+
cached: a.cached + b.cached,
|
|
43
|
+
output: a.output + b.output
|
|
44
|
+
});
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/host/agents/usage.ts
|
|
47
|
+
/** The tokens the model service reported for the requests it answered in a session's events; a request it reported nothing for adds nothing. */
|
|
48
|
+
function tokensOf(events) {
|
|
49
|
+
let total = NO_TOKENS;
|
|
50
|
+
for (const event of events) {
|
|
51
|
+
if (event.type !== "assistant/message") continue;
|
|
52
|
+
const usage = lastAssistantStreamChunk(event.data.stream, "usage")?.usage;
|
|
53
|
+
if (usage === void 0) continue;
|
|
54
|
+
total = addTokens(total, {
|
|
55
|
+
input: usage.inputTokens,
|
|
56
|
+
cached: usage.cacheReadTokens ?? 0,
|
|
57
|
+
output: usage.outputTokens
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return total;
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/shared/activity.ts
|
|
64
|
+
/** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
|
|
65
|
+
const MAX_RUN_TEXT = 4e3;
|
|
66
|
+
const MAX_RUN_PROMPT = 24e3;
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/host/agents/child.ts
|
|
69
|
+
/** The tool every child ends with: its arguments are the child's result. */
|
|
70
|
+
const SUBMIT_TOOL = "submit_result";
|
|
71
|
+
/** Said to every child once, after its persona, so it is the same for all of them and the start of every request stays the same. */
|
|
72
|
+
const SUBMIT_RULE = `When you are done, call ${SUBMIT_TOOL} with your result. It is the only way to finish: text you write instead is lost.`;
|
|
73
|
+
/** Calls a child may make before it is given up; a child that keeps going is not converging. */
|
|
74
|
+
const DEFAULT_MAX_CALLS = 40;
|
|
75
|
+
/** A child that stops without a result is told to submit this many times before it is given up. */
|
|
76
|
+
const MAX_REMINDERS = 2;
|
|
77
|
+
/** A child that goes on calling tools this many times past its budget, in spite of being told to submit, is stopped: it would otherwise loop for as long as the model keeps at it. */
|
|
78
|
+
const OVERRUN = 5;
|
|
79
|
+
/** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
|
|
80
|
+
const STEPS_AFTER_RETIRE = 3;
|
|
81
|
+
/** The most model steps a child may take past its call budget in all (calls the harness refuses before they run, such as a result that does not fit its schema, are not counted as calls). */
|
|
82
|
+
const STEPS_PAST_BUDGET = 20;
|
|
83
|
+
/** The same call, with the same arguments, that failed before is refused after this many repeats, and the child is stopped at twice that: the model is not reading the reasons it was given. */
|
|
84
|
+
const REPEATS_TOLD = 1;
|
|
85
|
+
const REPEATS_STOPPED = 4;
|
|
86
|
+
/** A result that is refused this many times is not going to be fixed by asking again: the child is stopped and the caller decides what to do without it. */
|
|
87
|
+
const MAX_REFUSALS = 5;
|
|
88
|
+
/**
|
|
89
|
+
* What the settings of a chat say about how a kind of helper is asked: prose is free, the keepers of records exact. A helper whose answer has a declared size (its `estimate`, in tokens)
|
|
90
|
+
* is let produce that with room to spare, no more than the chat's ceiling for its kind.
|
|
91
|
+
*/
|
|
92
|
+
function childSampling(settings, kind, estimate) {
|
|
93
|
+
const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
|
|
94
|
+
return {
|
|
95
|
+
temperature: settings.sampling[kind],
|
|
96
|
+
toolChoice: settings.sampling.tools,
|
|
97
|
+
maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
|
|
98
|
+
priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** What a caller passes as `trace`: files each run of a kind of helper under a label in the store's record of activity, with its detail when the chat keeps it. */
|
|
102
|
+
function childTrace(store, kind, label, extra = {}, named) {
|
|
103
|
+
const model = (named ?? store.settings().models[kind]).trim();
|
|
104
|
+
return (run) => {
|
|
105
|
+
const keep = store.settings().diagnostics.keepRuns;
|
|
106
|
+
const id = keep ? randomUUID() : void 0;
|
|
107
|
+
store.recordActivity({
|
|
108
|
+
at: Date.now(),
|
|
109
|
+
label,
|
|
110
|
+
model,
|
|
111
|
+
ms: run.ms,
|
|
112
|
+
calls: run.calls,
|
|
113
|
+
turn: run.turn,
|
|
114
|
+
tokens: run.tokens,
|
|
115
|
+
...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
|
|
116
|
+
...id === void 0 ? {} : { run: id }
|
|
117
|
+
}, keep ? {
|
|
118
|
+
...run.detail,
|
|
119
|
+
...extra
|
|
120
|
+
} : void 0);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
|
|
124
|
+
function childModel(settings, kind, override) {
|
|
125
|
+
const named = (override ?? settings.models[kind]).trim();
|
|
126
|
+
if (named === "") return {};
|
|
127
|
+
const slash = named.indexOf("/");
|
|
128
|
+
return { model: {
|
|
129
|
+
provider: named.slice(0, slash),
|
|
130
|
+
model: named.slice(slash + 1)
|
|
131
|
+
} };
|
|
132
|
+
}
|
|
133
|
+
const samplings = /* @__PURE__ */ new Map();
|
|
134
|
+
/** The controls set for a running child, by its session id. */
|
|
135
|
+
const childSamplingOf = (sessionId) => samplings.get(sessionId);
|
|
136
|
+
/**
|
|
137
|
+
* Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
|
|
138
|
+
* have tools of its own, so several can run side by side with different tools and different
|
|
139
|
+
* results from the same tool.
|
|
140
|
+
*
|
|
141
|
+
* This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
|
|
142
|
+
* composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
|
|
143
|
+
* `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
|
|
144
|
+
* this is accepted, which DSH version it is built against, and what to do when DSH changes.
|
|
145
|
+
* @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
|
|
146
|
+
*/
|
|
147
|
+
function childOptions(task) {
|
|
148
|
+
const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
|
|
149
|
+
const options = {
|
|
150
|
+
...task.reasoningEffort === void 0 || task.reasoningEffort === "" ? {} : { reasoningEffort: ReasoningEffortId(task.reasoningEffort) },
|
|
151
|
+
...maxTokens === void 0 ? {} : { maxTokens },
|
|
152
|
+
...task.model === void 0 ? {} : {
|
|
153
|
+
provider: task.model.provider,
|
|
154
|
+
model: task.model.model
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
return Object.keys(options).length === 0 ? void 0 : options;
|
|
158
|
+
}
|
|
159
|
+
/** The schema an answer is checked against: the one the model was given, without requiring what it was only asked for ({@link ChildTask.unenforced}). */
|
|
160
|
+
function enforcedSchema(task) {
|
|
161
|
+
const skipped = task.unenforced ?? [];
|
|
162
|
+
return skipped.length === 0 || task.result.required === void 0 ? task.result : {
|
|
163
|
+
...task.result,
|
|
164
|
+
required: task.result.required.filter((name) => !skipped.includes(name))
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** A model that is cut off in the middle of its tool call leaves an unfinished argument no one can read; asking again usually gives a whole one. */
|
|
168
|
+
const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
|
|
169
|
+
async function runChild(task) {
|
|
170
|
+
for (let attempt = 1;; attempt += 1) {
|
|
171
|
+
const began = Date.now();
|
|
172
|
+
const stats = {
|
|
173
|
+
calls: 0,
|
|
174
|
+
record: []
|
|
175
|
+
};
|
|
176
|
+
const detail = () => ({
|
|
177
|
+
persona: task.persona.slice(0, MAX_RUN_PROMPT),
|
|
178
|
+
prompt: task.prompt.slice(0, MAX_RUN_PROMPT),
|
|
179
|
+
calls: stats.record,
|
|
180
|
+
...stats.result === void 0 ? {} : { result: stats.result }
|
|
181
|
+
});
|
|
182
|
+
try {
|
|
183
|
+
const result = await execute(task, stats);
|
|
184
|
+
task.trace?.({
|
|
185
|
+
ms: Date.now() - began,
|
|
186
|
+
calls: stats.calls,
|
|
187
|
+
detail: detail(),
|
|
188
|
+
turn: currentTurn(task.parent),
|
|
189
|
+
tokens: stats.tokens ?? NO_TOKENS
|
|
190
|
+
});
|
|
191
|
+
return result;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
task.trace?.({
|
|
194
|
+
ms: Date.now() - began,
|
|
195
|
+
calls: stats.calls,
|
|
196
|
+
error: error instanceof Error ? error.message : String(error),
|
|
197
|
+
detail: detail(),
|
|
198
|
+
turn: currentTurn(task.parent),
|
|
199
|
+
tokens: stats.tokens ?? NO_TOKENS
|
|
200
|
+
});
|
|
201
|
+
if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The thinking level a child may be given on its model: the one asked for when the model offers it, none when it does not (a model chosen for a
|
|
207
|
+
* helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
|
|
208
|
+
*/
|
|
209
|
+
async function supportedEffort(task) {
|
|
210
|
+
const level = task.reasoningEffort;
|
|
211
|
+
if (level === void 0 || level === "" || task.model === void 0) return level;
|
|
212
|
+
try {
|
|
213
|
+
return (await task.parent.ctx.llm.resolveModelInfo(task.model.provider, task.model.model, task.signal)).reasoning?.efforts.some((effort) => effort.id === level) === true ? level : void 0;
|
|
214
|
+
} catch {
|
|
215
|
+
return level;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const cut = (value, limit = MAX_RUN_TEXT) => {
|
|
219
|
+
const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
|
|
220
|
+
return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
|
|
221
|
+
};
|
|
222
|
+
async function execute(task, stats) {
|
|
223
|
+
const { parent, signal } = task;
|
|
224
|
+
const reasoningEffort = await supportedEffort(task);
|
|
225
|
+
let submitted;
|
|
226
|
+
let reminders = 0;
|
|
227
|
+
let stopped;
|
|
228
|
+
let retire;
|
|
229
|
+
let stepsAfterRetire = -1;
|
|
230
|
+
let overran = false;
|
|
231
|
+
let refusals = 0;
|
|
232
|
+
let lastRefusal = "";
|
|
233
|
+
let previous;
|
|
234
|
+
const budget = task.maxCalls ?? DEFAULT_MAX_CALLS;
|
|
235
|
+
const counted = (tool) => ({
|
|
236
|
+
...tool,
|
|
237
|
+
execute: async (args, exec) => {
|
|
238
|
+
stats.calls += 1;
|
|
239
|
+
const note = (outcome, failed) => {
|
|
240
|
+
if (stats.record.length < 60) stats.record.push({
|
|
241
|
+
tool: tool.name,
|
|
242
|
+
args: cut(args),
|
|
243
|
+
outcome: cut(outcome),
|
|
244
|
+
failed
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
if (stats.calls > budget + OVERRUN) {
|
|
248
|
+
overran = true;
|
|
249
|
+
stopped?.();
|
|
250
|
+
}
|
|
251
|
+
if (stats.calls > budget) {
|
|
252
|
+
const message = `you have made ${budget} calls: submit your result now and say what is still missing`;
|
|
253
|
+
note(message, true);
|
|
254
|
+
throw new Error(message);
|
|
255
|
+
}
|
|
256
|
+
const signature = JSON.stringify(args);
|
|
257
|
+
const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
|
|
258
|
+
if (repeats >= REPEATS_STOPPED) {
|
|
259
|
+
overran = true;
|
|
260
|
+
stopped?.();
|
|
261
|
+
}
|
|
262
|
+
if (repeats >= REPEATS_TOLD) {
|
|
263
|
+
previous = {
|
|
264
|
+
name: tool.name,
|
|
265
|
+
args: signature,
|
|
266
|
+
failed: true,
|
|
267
|
+
repeats
|
|
268
|
+
};
|
|
269
|
+
const message = "this is exactly the call that just failed, with the same arguments, so it fails for the same reasons: read the reasons the last result gave and change the arguments to fix every one of them";
|
|
270
|
+
note(message, true);
|
|
271
|
+
throw new Error(message);
|
|
272
|
+
}
|
|
273
|
+
previous = {
|
|
274
|
+
name: tool.name,
|
|
275
|
+
args: signature,
|
|
276
|
+
failed: false,
|
|
277
|
+
repeats
|
|
278
|
+
};
|
|
279
|
+
try {
|
|
280
|
+
const outcome = await tool.execute(args, exec);
|
|
281
|
+
note(outcome, false);
|
|
282
|
+
return outcome;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
if (previous !== void 0) previous.failed = true;
|
|
285
|
+
note(error instanceof Error ? error.message : String(error), true);
|
|
286
|
+
throw error;
|
|
287
|
+
} finally {
|
|
288
|
+
if (stats.calls >= budget) retire?.();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
const submit = {
|
|
293
|
+
name: SUBMIT_TOOL,
|
|
294
|
+
description: "Submit your final result. Call it exactly once, when you are done; the arguments are the result.",
|
|
295
|
+
parameters: task.result,
|
|
296
|
+
output: {
|
|
297
|
+
schema: {
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: { recorded: {
|
|
300
|
+
type: "boolean",
|
|
301
|
+
const: true
|
|
302
|
+
} },
|
|
303
|
+
required: ["recorded"],
|
|
304
|
+
additionalProperties: false
|
|
305
|
+
},
|
|
306
|
+
render: () => [{
|
|
307
|
+
type: "text",
|
|
308
|
+
text: "Result recorded."
|
|
309
|
+
}]
|
|
310
|
+
},
|
|
311
|
+
execute(args, exec) {
|
|
312
|
+
const violations = validateJsonSchemaValue(enforcedSchema(task), args);
|
|
313
|
+
if (violations.length > 0) throw new ToolArgsError(violations);
|
|
314
|
+
const refusal = task.beforeSubmit?.(args);
|
|
315
|
+
if (refusal !== void 0) {
|
|
316
|
+
if (stats.record.length < 60) stats.record.push({
|
|
317
|
+
tool: SUBMIT_TOOL,
|
|
318
|
+
args: cut(args),
|
|
319
|
+
outcome: cut(refusal),
|
|
320
|
+
failed: true
|
|
321
|
+
});
|
|
322
|
+
refusals += 1;
|
|
323
|
+
lastRefusal = refusal;
|
|
324
|
+
if (refusals >= MAX_REFUSALS) {
|
|
325
|
+
overran = true;
|
|
326
|
+
stopped?.();
|
|
327
|
+
}
|
|
328
|
+
throw new Error(refusal);
|
|
329
|
+
}
|
|
330
|
+
submitted = { value: args };
|
|
331
|
+
stats.result = cut(args, MAX_RUN_PROMPT);
|
|
332
|
+
if (stats.record.length < 60) stats.record.push({
|
|
333
|
+
tool: SUBMIT_TOOL,
|
|
334
|
+
args: cut(args),
|
|
335
|
+
outcome: "Result recorded.",
|
|
336
|
+
failed: false
|
|
337
|
+
});
|
|
338
|
+
exec.concludeTurn();
|
|
339
|
+
return Promise.resolve({ recorded: true });
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
const depth = resolveChildDepth(parent, void 0);
|
|
343
|
+
const inherited = captureDelegatedPolicyOverrides(parent);
|
|
344
|
+
const sessionId = SessionId(randomUUID());
|
|
345
|
+
if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
|
|
346
|
+
const handle = await parent.ctx.agents.create({
|
|
347
|
+
sessionId,
|
|
348
|
+
parentAgent: parent,
|
|
349
|
+
meta: childSessionMeta(parent, depth, false),
|
|
350
|
+
agentOptions: resolveChildAgentOptions(parent, childOptions({
|
|
351
|
+
...task,
|
|
352
|
+
...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
|
|
353
|
+
}), depth),
|
|
354
|
+
signal,
|
|
355
|
+
setup: (childCtx, child) => {
|
|
356
|
+
appendDelegatedPolicyOverrides(child.session, inherited);
|
|
357
|
+
applyChildComposition(childCtx, parent, {
|
|
358
|
+
persona: `${task.persona}\n\n${SUBMIT_RULE}`,
|
|
359
|
+
toolFilter: { allow: [...task.external ?? []] }
|
|
360
|
+
});
|
|
361
|
+
const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
|
|
362
|
+
retire = () => {
|
|
363
|
+
for (const dispose of registered) dispose();
|
|
364
|
+
if (stepsAfterRetire < 0) stepsAfterRetire = 0;
|
|
365
|
+
};
|
|
366
|
+
let steps = 0;
|
|
367
|
+
childCtx.on("agent/pre-step", async (_payload, next) => {
|
|
368
|
+
const decision = await next();
|
|
369
|
+
steps += 1;
|
|
370
|
+
if (steps > budget + STEPS_PAST_BUDGET && submitted === void 0) {
|
|
371
|
+
overran = true;
|
|
372
|
+
stopped?.();
|
|
373
|
+
}
|
|
374
|
+
if (stepsAfterRetire < 0) return decision;
|
|
375
|
+
stepsAfterRetire += 1;
|
|
376
|
+
if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
|
|
377
|
+
overran = true;
|
|
378
|
+
stopped?.();
|
|
379
|
+
}
|
|
380
|
+
return decision;
|
|
381
|
+
});
|
|
382
|
+
childCtx.tools.register(submit);
|
|
383
|
+
childCtx.on("agent/turn-stopping", () => {
|
|
384
|
+
if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
|
|
385
|
+
reminders += 1;
|
|
386
|
+
child.steer(createUserMessage({
|
|
387
|
+
content: [{
|
|
388
|
+
type: "text",
|
|
389
|
+
text: `You have not finished: call ${SUBMIT_TOOL} with your result, as the tool lists it.`
|
|
390
|
+
}],
|
|
391
|
+
source: { kind: "roleplay" }
|
|
392
|
+
}));
|
|
393
|
+
});
|
|
394
|
+
childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
stopped = () => {
|
|
398
|
+
handle.agent.cancel({ kind: "parent" });
|
|
399
|
+
};
|
|
400
|
+
const onAbort = () => {
|
|
401
|
+
handle.agent.cancel({ kind: "parent" });
|
|
402
|
+
};
|
|
403
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
404
|
+
try {
|
|
405
|
+
handle.agent.followup(createUserMessage({
|
|
406
|
+
content: [{
|
|
407
|
+
type: "text",
|
|
408
|
+
text: task.prompt
|
|
409
|
+
}, ...(task.images ?? []).map((attachment) => ({
|
|
410
|
+
type: "image",
|
|
411
|
+
attachment
|
|
412
|
+
}))],
|
|
413
|
+
source: { kind: "user" }
|
|
414
|
+
}));
|
|
415
|
+
await handle.agent.whenIdle();
|
|
416
|
+
} finally {
|
|
417
|
+
signal.removeEventListener("abort", onAbort);
|
|
418
|
+
stats.tokens = tokensOf(handle.agent.session.snapshotEvents());
|
|
419
|
+
samplings.delete(sessionId);
|
|
420
|
+
await handle.dispose();
|
|
421
|
+
}
|
|
422
|
+
if (signal.aborted) throw new Error("cancelled");
|
|
423
|
+
if (overran && submitted === void 0) throw new Error(refusals >= MAX_REFUSALS ? `the result was refused ${refusals} times and the agent was stopped; the last reason: ${lastRefusal}` : `the agent went on past its ${budget} calls, or kept repeating a call that failed, without submitting a result and was stopped`);
|
|
424
|
+
if (submitted === void 0) {
|
|
425
|
+
const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
|
|
426
|
+
const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
|
|
427
|
+
if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
|
|
428
|
+
throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
|
|
429
|
+
}
|
|
430
|
+
return submitted.value;
|
|
431
|
+
}
|
|
432
|
+
//#endregion
|
|
433
|
+
export { runChild as a, addTokens as c, tokensOf$1 as d, childTrace as i, currentTurn as l, childSampling as n, tokensOf as o, childSamplingOf as r, NO_TOKENS as s, childModel as t, estimateAnswer as u };
|
|
434
|
+
|
|
435
|
+
//# sourceMappingURL=child-CFjnaTZt.js.map
|