@dsh-agentic-roleplay/core 0.7.3 → 0.8.2
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 +1 -1
- package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
- package/lib/authoring-tools-BgmC2oqU.js +3691 -0
- package/lib/authoring.js +59 -24
- package/lib/{child-CyCViUKa.js → child-lYYeOwl2.js} +147 -46
- package/lib/client.js +931 -860
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +8 -13
- package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
- package/lib/doctor.js +6 -8
- package/lib/{gallery-DmBZ2L5l.js → gallery-D1V4h8vh.js} +3 -4
- package/lib/{generator-BmdoTIL2.js → generator-CLPosooC.js} +3 -4
- package/lib/helper.js +2 -3
- package/lib/{hooks-C8eELrni.js → hooks-rQTTeOC4.js} +144 -88
- package/lib/images.js +4 -4
- package/lib/index.js +1024 -913
- package/lib/{library-lVNf9qG_.js → library-Dfu0dgRj.js} +32 -21
- package/lib/{lorebook-author-tools-BDOs4i5C.js → lorebook-author-tools-BAaAqZZm.js} +11 -14
- package/lib/lorebook-authoring.js +5 -6
- package/lib/{narration-DvFBqmqe.js → narration-CjB_KwwY.js} +58 -20
- package/lib/orchestration.js +138 -72
- package/lib/{pack-jail-DeTscGT2.js → pack-jail-CN-314ln.js} +94 -137
- package/lib/{packs-CY8ms8v_.js → packs-DIj5BEfq.js} +6 -10
- package/lib/{presenter-agent-cFR4sos3.js → presenter-agent-DR0KvLE0.js} +13 -19
- package/lib/{preset-n4-j6k4S.js → preset-CscHj1-Y.js} +5 -5
- package/lib/{preset-author-tools-2m4BLtws.js → preset-author-tools-CxluF8qc.js} +13 -15
- package/lib/preset-authoring.js +6 -7
- package/lib/presets-HB8kJTaE.js +3993 -0
- package/lib/{reflection-CJB5s0ip.js → reflection-Dg1xtOTW.js} +137 -148
- package/lib/{text-Cwl5s0j0.js → text-DyRN4nDP.js} +13 -7
- package/lib/{turn-guard-BvCs1VxB.js → turn-guard-g_hDn0jR.js} +6 -7
- package/package.json +29 -29
- package/prompts/en/import/casting.md +14 -0
- package/prompts/en/import/character.md +1 -0
- package/prompts/en/import/classifier.md +9 -0
- package/prompts/en/import/finish-draft.md +1 -0
- package/prompts/en/import/generator.md +8 -0
- package/prompts/en/import/notice-repair.md +4 -0
- package/prompts/en/import/repair-again.md +3 -0
- package/prompts/en/import/roster.md +1 -0
- package/prompts/en/import/variables.md +1 -0
- package/prompts/en/roleplay/game-master.md +3 -0
- package/prompts/en/roleplay/standing.md +1 -0
- package/prompts/en/world/author.md +1 -1
- package/prompts/zh/import/casting.md +14 -0
- package/prompts/zh/import/character.md +1 -0
- package/prompts/zh/import/classifier.md +9 -0
- package/prompts/zh/import/finish-draft.md +1 -0
- package/prompts/zh/import/generator.md +8 -0
- package/prompts/zh/import/notice-repair.md +4 -0
- package/prompts/zh/import/repair-again.md +3 -0
- package/prompts/zh/import/roster.md +1 -0
- package/prompts/zh/import/variables.md +1 -0
- package/prompts/zh/roleplay/game-master.md +3 -0
- package/prompts/zh/roleplay/standing.md +1 -0
- package/prompts/zh/world/author.md +1 -1
- package/lib/authoring-tools-CIsWbq0B.js +0 -6317
- package/lib/route-C6SHz9j2.js +0 -518
package/lib/authoring.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import "./
|
|
2
|
-
import {
|
|
3
|
-
import { C as
|
|
4
|
-
import { G as
|
|
5
|
-
import { i as translator, r as languageOf } from "./text-
|
|
6
|
-
import {
|
|
7
|
-
import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-
|
|
8
|
-
import
|
|
1
|
+
import { Q as checkWorld, R as parseWorldInfoEdit, Vt as authoredWorldOf, a as importHooks, h as editsSince, l as isReviewing, n as limitAuthoringAgents, o as importTools } from "./authoring-tools-BgmC2oqU.js";
|
|
2
|
+
import { t as guardAuthoringTurns } from "./turn-guard-g_hDn0jR.js";
|
|
3
|
+
import { $ as matchPieces, B as readWorldInfo, C as readWorldEditor, F as loadWorldParts, H as translateTools, K as finishUpdate, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, Q as diffText, R as presetTools, Z as cardChanges, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, et as worldFieldChanges, i as checkWorldPack, l as deleteAuthoredEntity, nt as entitiesByPiece, o as listWorldPacks, q as pendingUpdate, r as registerPackJail, rt as readSource, s as AUTHORED_ENTITY_KINDS, tt as cardTools, u as readAuthoredEntityDocument, v as editWorldRelation, z as editWorldInfo } from "./pack-jail-CN-314ln.js";
|
|
4
|
+
import { Et as InvalidEditProblems, G as listWorldPrompts, K as readWorldPrompt, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, jt as parseRelationEdit, q as writeWorldPrompt } from "./presets-HB8kJTaE.js";
|
|
5
|
+
import { i as translator, r as languageOf } from "./text-DyRN4nDP.js";
|
|
6
|
+
import { J as formatIssue, V as parsePlotsFile, at as shippedPromptsDirectory } from "./hooks-rQTTeOC4.js";
|
|
7
|
+
import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-DIj5BEfq.js";
|
|
8
|
+
import "./access-CfQWbNZP.js";
|
|
9
9
|
import { join, relative } from "node:path";
|
|
10
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
10
11
|
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
11
12
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
12
|
-
import { readFile, readdir } from "node:fs/promises";
|
|
13
13
|
import { isDeepStrictEqual } from "node:util";
|
|
14
|
-
|
|
14
|
+
// src/host/authoring/read-tools.ts
|
|
15
15
|
const output$4 = (value) => [{
|
|
16
16
|
type: "text",
|
|
17
17
|
text: JSON.stringify(value, null, 2)
|
|
@@ -119,6 +119,16 @@ function authoredWorldReadTools(reader) {
|
|
|
119
119
|
return json$1(await readWorldInfo((await reader.read(exec)).record.directory));
|
|
120
120
|
}
|
|
121
121
|
}),
|
|
122
|
+
defineTool({
|
|
123
|
+
name: "world_check",
|
|
124
|
+
description: "Check the world as starting a story from it would: every file reads and everything that refers to something refers to something that is there. It names the problems of the first part of the world that has any (characters, factions, places, calendar, dice, items, lore, tracked values, triggers, plots), so run it again after fixing them to see whether another part has some. Run it before you say a world is done.",
|
|
125
|
+
parameters: {},
|
|
126
|
+
output: jsonOutput$3,
|
|
127
|
+
isConcurrencySafe: () => true,
|
|
128
|
+
async execute(_args, exec) {
|
|
129
|
+
return json$1(await checkWorld((await reader.read(exec)).record));
|
|
130
|
+
}
|
|
131
|
+
}),
|
|
122
132
|
listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
|
|
123
133
|
key: entry.key,
|
|
124
134
|
name: entry.name,
|
|
@@ -251,8 +261,7 @@ function authoredWorldReadTools(reader) {
|
|
|
251
261
|
})
|
|
252
262
|
];
|
|
253
263
|
}
|
|
254
|
-
|
|
255
|
-
//#region src/host/authoring/pack-tools.ts
|
|
264
|
+
// src/host/authoring/pack-tools.ts
|
|
256
265
|
const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
|
|
257
266
|
const output$3 = (value) => [{
|
|
258
267
|
type: "text",
|
|
@@ -360,8 +369,7 @@ function worldPackTools(reader) {
|
|
|
360
369
|
})
|
|
361
370
|
];
|
|
362
371
|
}
|
|
363
|
-
|
|
364
|
-
//#region src/host/authoring/prompt-tools.ts
|
|
372
|
+
// src/host/authoring/prompt-tools.ts
|
|
365
373
|
const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
|
|
366
374
|
const output$2 = (value) => [{
|
|
367
375
|
type: "text",
|
|
@@ -456,8 +464,7 @@ function worldPromptTools(reader, shipped = shippedPromptsDirectory()) {
|
|
|
456
464
|
})
|
|
457
465
|
];
|
|
458
466
|
}
|
|
459
|
-
|
|
460
|
-
//#region src/host/authoring/approval-summary.ts
|
|
467
|
+
// src/host/authoring/approval-summary.ts
|
|
461
468
|
const MAX_FIELDS = 5;
|
|
462
469
|
function clip(value, max) {
|
|
463
470
|
const flat = (typeof value === "string" ? `“${value}”` : JSON.stringify(value) ?? "").replace(/\s+/g, " ");
|
|
@@ -524,8 +531,7 @@ function plain(value, max = 220) {
|
|
|
524
531
|
zh: text
|
|
525
532
|
};
|
|
526
533
|
}
|
|
527
|
-
|
|
528
|
-
//#region src/host/authoring/write-tools.ts
|
|
534
|
+
// src/host/authoring/write-tools.ts
|
|
529
535
|
const output$1 = (value) => [{
|
|
530
536
|
type: "text",
|
|
531
537
|
text: JSON.stringify(value, null, 2)
|
|
@@ -592,6 +598,38 @@ function plotDocument(value) {
|
|
|
592
598
|
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
593
599
|
return parsed.value[0];
|
|
594
600
|
}
|
|
601
|
+
/** The most problems a write reports back; `world_check` lists the rest. */
|
|
602
|
+
const REPORTED_PROBLEMS = 8;
|
|
603
|
+
/**
|
|
604
|
+
* A write is allowed to leave the world unfinished (a character first, its place next), so the check is advice, not a refusal: the assistant sees at once what its edit
|
|
605
|
+
* left open instead of finding out when a story is started.
|
|
606
|
+
*/
|
|
607
|
+
function withWorldCheck(reader, tool) {
|
|
608
|
+
const run = tool.execute;
|
|
609
|
+
return {
|
|
610
|
+
...tool,
|
|
611
|
+
async execute(args, exec) {
|
|
612
|
+
const done = await run(args, exec);
|
|
613
|
+
if (done === null || typeof done !== "object") return done;
|
|
614
|
+
const { record } = await reader.read(exec);
|
|
615
|
+
const check = await checkWorld(record);
|
|
616
|
+
if (check.ok) return {
|
|
617
|
+
...done,
|
|
618
|
+
world_check: "ok: a story could start from this world"
|
|
619
|
+
};
|
|
620
|
+
const shown = check.problems.slice(0, REPORTED_PROBLEMS).map((problem) => `${problem.where}: ${problem.message}`);
|
|
621
|
+
return {
|
|
622
|
+
...done,
|
|
623
|
+
world_check: {
|
|
624
|
+
ok: false,
|
|
625
|
+
still_open: shown,
|
|
626
|
+
more: check.problems.length - shown.length + check.more,
|
|
627
|
+
note: "Not an error of this edit; fix what the world still needs before the end of the turn (world_check lists all)."
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
}
|
|
595
633
|
function authoredWorldWriteTools(reader) {
|
|
596
634
|
return [
|
|
597
635
|
defineTool({
|
|
@@ -761,7 +799,7 @@ function authoredWorldWriteTools(reader) {
|
|
|
761
799
|
});
|
|
762
800
|
}
|
|
763
801
|
})
|
|
764
|
-
];
|
|
802
|
+
].map((tool) => withWorldCheck(reader, tool));
|
|
765
803
|
}
|
|
766
804
|
/**
|
|
767
805
|
* Every change to the world files is put to the person, except in the turn that has just imported a card into the world: it reviews and corrects what it made.
|
|
@@ -878,8 +916,7 @@ async function detailOf(exec, kind, key, current) {
|
|
|
878
916
|
default: return;
|
|
879
917
|
}
|
|
880
918
|
}
|
|
881
|
-
|
|
882
|
-
//#region src/host/import/update-tools.ts
|
|
919
|
+
// src/host/import/update-tools.ts
|
|
883
920
|
const MAX_HUNKS = 10;
|
|
884
921
|
const MAX_PIECES = 60;
|
|
885
922
|
const PREVIEW_CHARS = 300;
|
|
@@ -1062,8 +1099,7 @@ function updateHooks(ctx, worlds, languageOf$1) {
|
|
|
1062
1099
|
}));
|
|
1063
1100
|
});
|
|
1064
1101
|
}
|
|
1065
|
-
|
|
1066
|
-
//#region src/authoring.ts
|
|
1102
|
+
// src/authoring.ts
|
|
1067
1103
|
const name = "@dsh-agentic-roleplay/core/authoring";
|
|
1068
1104
|
const inject = [
|
|
1069
1105
|
"roleplayWorlds",
|
|
@@ -1146,7 +1182,6 @@ function apply(ctx) {
|
|
|
1146
1182
|
text: (context) => ctx.roleplayPrompts.text(id, languageOf(context))
|
|
1147
1183
|
});
|
|
1148
1184
|
}
|
|
1149
|
-
//#endregion
|
|
1150
1185
|
export { apply, inject, name };
|
|
1151
1186
|
|
|
1152
1187
|
//# sourceMappingURL=authoring.js.map
|
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
3
3
|
import { ReasoningEffortId, createUserMessage, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
|
|
4
4
|
import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
|
|
5
|
-
|
|
5
|
+
// src/host/agents/budget.ts
|
|
6
6
|
/** 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. */
|
|
7
7
|
function tokensOf$1(characters, language) {
|
|
8
8
|
return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
|
|
@@ -18,8 +18,7 @@ function outputBudget(estimate, headroom) {
|
|
|
18
18
|
function estimateAnswer(limits, language) {
|
|
19
19
|
return limits.reduce((sum, limit) => sum + tokensOf$1(limit, language) + 8, 0);
|
|
20
20
|
}
|
|
21
|
-
|
|
22
|
-
//#region src/host/agents/cut-off.ts
|
|
21
|
+
// src/host/agents/cut-off.ts
|
|
23
22
|
/** How the model's last reply ended (`stop`, `tool-calls`, `max-tokens`), or nothing when it has made none. */
|
|
24
23
|
function finishOf(agent) {
|
|
25
24
|
const last = agent.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
|
|
@@ -28,8 +27,7 @@ function finishOf(agent) {
|
|
|
28
27
|
}
|
|
29
28
|
/** Whether the model's last reply ended because it reached the most it may write in one request. */
|
|
30
29
|
const cutOff = (agent) => finishOf(agent) === "max-tokens";
|
|
31
|
-
|
|
32
|
-
//#region src/host/orchestration/current-turn.ts
|
|
30
|
+
// src/host/orchestration/current-turn.ts
|
|
33
31
|
/** The last turn the session started. */
|
|
34
32
|
function currentTurn(agent) {
|
|
35
33
|
const events = agent.session.snapshotEvents();
|
|
@@ -39,8 +37,7 @@ function currentTurn(agent) {
|
|
|
39
37
|
}
|
|
40
38
|
return 0;
|
|
41
39
|
}
|
|
42
|
-
|
|
43
|
-
//#region src/shared/usage.ts
|
|
40
|
+
// src/shared/usage.ts
|
|
44
41
|
const NO_TOKENS = {
|
|
45
42
|
input: 0,
|
|
46
43
|
cached: 0,
|
|
@@ -51,8 +48,7 @@ const addTokens = (a, b) => ({
|
|
|
51
48
|
cached: a.cached + b.cached,
|
|
52
49
|
output: a.output + b.output
|
|
53
50
|
});
|
|
54
|
-
|
|
55
|
-
//#region src/host/agents/usage.ts
|
|
51
|
+
// src/host/agents/usage.ts
|
|
56
52
|
/** The tokens the model service reported for the requests it answered in a session's events; a request it reported nothing for adds nothing. */
|
|
57
53
|
function tokensOf(events) {
|
|
58
54
|
let total = NO_TOKENS;
|
|
@@ -68,13 +64,17 @@ function tokensOf(events) {
|
|
|
68
64
|
}
|
|
69
65
|
return total;
|
|
70
66
|
}
|
|
71
|
-
|
|
72
|
-
//#region src/shared/activity.ts
|
|
67
|
+
// src/shared/activity.ts
|
|
73
68
|
/** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
|
|
74
69
|
const MAX_RUN_TEXT = 4e3;
|
|
75
70
|
const MAX_RUN_PROMPT = 24e3;
|
|
76
|
-
|
|
77
|
-
|
|
71
|
+
// src/host/agents/limits.ts
|
|
72
|
+
/**
|
|
73
|
+
* How long a child that was stopped has to wind down. Found live twice: a stopped child's activation never settled and the caller waited for ever (an import stood still for
|
|
74
|
+
* minutes, a game master's turn never ended), so what the stop decided is not waited on past this.
|
|
75
|
+
*/
|
|
76
|
+
const STOP_GRACE_MS = 15e3;
|
|
77
|
+
// src/shared/sampling.ts
|
|
78
78
|
/** The controls beyond temperature, which apply to the game master and the characters (the helpers that must be exact are never asked more freely). */
|
|
79
79
|
const SHARED_SAMPLING = [
|
|
80
80
|
"topP",
|
|
@@ -149,27 +149,12 @@ function parseSampling(value, where, problems) {
|
|
|
149
149
|
function sharedSamplingOf(settings) {
|
|
150
150
|
return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
|
|
151
151
|
}
|
|
152
|
-
|
|
153
|
-
//#region src/host/agents/child.ts
|
|
152
|
+
// src/host/agents/child.ts
|
|
154
153
|
/** The tool every child ends with: its arguments are the child's result. */
|
|
155
154
|
const SUBMIT_TOOL = "submit_result";
|
|
156
155
|
/** 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. */
|
|
157
156
|
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.`;
|
|
158
|
-
|
|
159
|
-
const DEFAULT_MAX_CALLS = 40;
|
|
160
|
-
/** A child that stops without a result is told to submit this many times before it is given up. */
|
|
161
|
-
const MAX_REMINDERS = 2;
|
|
162
|
-
/** 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. */
|
|
163
|
-
const OVERRUN = 5;
|
|
164
|
-
/** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
|
|
165
|
-
const STEPS_AFTER_RETIRE = 3;
|
|
166
|
-
/** 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). */
|
|
167
|
-
const STEPS_PAST_BUDGET = 20;
|
|
168
|
-
/** 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. */
|
|
169
|
-
const REPEATS_TOLD = 1;
|
|
170
|
-
const REPEATS_STOPPED = 4;
|
|
171
|
-
/** 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. */
|
|
172
|
-
const MAX_REFUSALS = 5;
|
|
157
|
+
const STRUCTURED_RULE = "Your whole reply is the result, as one JSON object of the shape you were given: write nothing before or after it.";
|
|
173
158
|
/** A child ran out of the time it was given; asking again would only spend it again. */
|
|
174
159
|
var ChildTimeoutError = class extends Error {
|
|
175
160
|
constructor(minutes) {
|
|
@@ -320,6 +305,56 @@ async function supportedEffort(task) {
|
|
|
320
305
|
return level;
|
|
321
306
|
}
|
|
322
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* A JSON text that was cut off, closed after the last whole entry it holds: what a reply that ran into its limit in the middle of a long list still says. Nothing when no such cut makes it JSON.
|
|
310
|
+
*/
|
|
311
|
+
function repairedJson(text, accepts = () => true) {
|
|
312
|
+
const cuts = [];
|
|
313
|
+
for (const marks of ["}]", ","]) for (let at = text.length - 1, found = 0; at >= 0 && found < 300; at -= 1) if (marks.includes(text[at])) {
|
|
314
|
+
cuts.push(at);
|
|
315
|
+
found += 1;
|
|
316
|
+
}
|
|
317
|
+
for (const at of cuts) {
|
|
318
|
+
const head = text.slice(0, text[at] === "," ? at : at + 1);
|
|
319
|
+
const stack = [];
|
|
320
|
+
let inString = false;
|
|
321
|
+
for (let index = 0; index < head.length; index += 1) {
|
|
322
|
+
const char = head[index];
|
|
323
|
+
if (inString) {
|
|
324
|
+
if (char === "\\") index += 1;
|
|
325
|
+
else if (char === "\"") inString = false;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (char === "\"") inString = true;
|
|
329
|
+
else if (char === "{") stack.push("}");
|
|
330
|
+
else if (char === "[") stack.push("]");
|
|
331
|
+
else if (char === "}" || char === "]") stack.pop();
|
|
332
|
+
}
|
|
333
|
+
if (inString) continue;
|
|
334
|
+
const closed = head + stack.reverse().join("");
|
|
335
|
+
try {
|
|
336
|
+
if (accepts(JSON.parse(closed))) return closed;
|
|
337
|
+
} catch {
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/** The result in the last reply of a structured child: its JSON, which must fit the schema; else what is wrong with it. */
|
|
343
|
+
function structuredReply(child, schema, cut = false) {
|
|
344
|
+
const message = child.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
|
|
345
|
+
const text = (message?.type === "assistant/message" ? message.data.message.content : []).flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
|
|
346
|
+
if (text === "") return { problem: "the reply is empty" };
|
|
347
|
+
let value;
|
|
348
|
+
try {
|
|
349
|
+
value = JSON.parse(text);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
const mended = cut ? repairedJson(text, (candidate) => validateJsonSchemaValue(schema, candidate).length === 0) : void 0;
|
|
352
|
+
if (mended === void 0) return { problem: `the reply is not valid JSON (${error instanceof Error ? error.message : String(error)})` };
|
|
353
|
+
value = JSON.parse(mended);
|
|
354
|
+
}
|
|
355
|
+
const violations = validateJsonSchemaValue(schema, value);
|
|
356
|
+
return violations.length > 0 ? { problem: violations.map((violation) => String(violation)).join("; ") } : { value };
|
|
357
|
+
}
|
|
323
358
|
const cut = (value, limit = MAX_RUN_TEXT) => {
|
|
324
359
|
const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
|
|
325
360
|
return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
|
|
@@ -330,6 +365,10 @@ async function execute(task, stats) {
|
|
|
330
365
|
let submitted;
|
|
331
366
|
let reminders = 0;
|
|
332
367
|
let stopped;
|
|
368
|
+
let giveUp;
|
|
369
|
+
const gaveUp = new Promise((resolve) => {
|
|
370
|
+
giveUp = resolve;
|
|
371
|
+
});
|
|
333
372
|
let retire;
|
|
334
373
|
let stepsAfterRetire = -1;
|
|
335
374
|
let overran = false;
|
|
@@ -337,7 +376,7 @@ async function execute(task, stats) {
|
|
|
337
376
|
let refusals = 0;
|
|
338
377
|
let lastRefusal = "";
|
|
339
378
|
let previous;
|
|
340
|
-
const budget = task.maxCalls ??
|
|
379
|
+
const budget = task.maxCalls ?? 40;
|
|
341
380
|
const counted = (tool) => ({
|
|
342
381
|
...tool,
|
|
343
382
|
execute: async (args, exec) => {
|
|
@@ -350,7 +389,7 @@ async function execute(task, stats) {
|
|
|
350
389
|
failed
|
|
351
390
|
});
|
|
352
391
|
};
|
|
353
|
-
if (stats.calls > budget +
|
|
392
|
+
if (stats.calls > budget + 5) {
|
|
354
393
|
overran = true;
|
|
355
394
|
stopped?.();
|
|
356
395
|
}
|
|
@@ -361,11 +400,11 @@ async function execute(task, stats) {
|
|
|
361
400
|
}
|
|
362
401
|
const signature = JSON.stringify(args);
|
|
363
402
|
const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
|
|
364
|
-
if (repeats >=
|
|
403
|
+
if (repeats >= 4) {
|
|
365
404
|
overran = true;
|
|
366
405
|
stopped?.();
|
|
367
406
|
}
|
|
368
|
-
if (repeats >=
|
|
407
|
+
if (repeats >= 1) {
|
|
369
408
|
previous = {
|
|
370
409
|
name: tool.name,
|
|
371
410
|
args: signature,
|
|
@@ -427,7 +466,7 @@ async function execute(task, stats) {
|
|
|
427
466
|
});
|
|
428
467
|
refusals += 1;
|
|
429
468
|
lastRefusal = refusal;
|
|
430
|
-
if (refusals >=
|
|
469
|
+
if (refusals >= 5) {
|
|
431
470
|
overran = true;
|
|
432
471
|
stopped?.();
|
|
433
472
|
}
|
|
@@ -447,11 +486,14 @@ async function execute(task, stats) {
|
|
|
447
486
|
};
|
|
448
487
|
const childId = SessionId(randomUUID());
|
|
449
488
|
const entry = {
|
|
450
|
-
persona: `${task.persona}\n\n${SUBMIT_RULE}`,
|
|
489
|
+
persona: `${task.persona}\n\n${task.structured === true ? STRUCTURED_RULE : SUBMIT_RULE}`,
|
|
451
490
|
setup(child) {
|
|
452
491
|
entry.agent = child;
|
|
453
492
|
stopped = () => {
|
|
454
493
|
child.cancel({ kind: "parent" });
|
|
494
|
+
setTimeout(() => {
|
|
495
|
+
giveUp?.();
|
|
496
|
+
}, STOP_GRACE_MS);
|
|
455
497
|
};
|
|
456
498
|
const childCtx = child.ctx;
|
|
457
499
|
childCtx.tools.restrict({ allow: [...task.external ?? []] });
|
|
@@ -464,28 +506,70 @@ async function execute(task, stats) {
|
|
|
464
506
|
childCtx.on("agent/pre-step", async (_payload, next) => {
|
|
465
507
|
const decision = await next();
|
|
466
508
|
steps += 1;
|
|
467
|
-
if (steps > budget +
|
|
509
|
+
if (steps > budget + 20 && submitted === void 0) {
|
|
468
510
|
overran = true;
|
|
469
511
|
stopped?.();
|
|
470
512
|
}
|
|
471
513
|
if (stepsAfterRetire < 0) return decision;
|
|
472
514
|
stepsAfterRetire += 1;
|
|
473
|
-
if (stepsAfterRetire >
|
|
515
|
+
if (stepsAfterRetire > 3 && submitted === void 0) {
|
|
474
516
|
overran = true;
|
|
475
517
|
stopped?.();
|
|
476
518
|
}
|
|
477
519
|
return decision;
|
|
478
520
|
});
|
|
479
|
-
childCtx.tools.register(submit);
|
|
521
|
+
if (task.structured !== true) childCtx.tools.register(submit);
|
|
480
522
|
childCtx.on("agent/turn-stopping", () => {
|
|
481
523
|
if (submitted !== void 0) return;
|
|
524
|
+
if (task.structured === true) {
|
|
525
|
+
const reply = structuredReply(child, enforcedSchema(task), cutOff(child));
|
|
526
|
+
if (cutOff(child) && !("value" in reply)) {
|
|
527
|
+
rambled = true;
|
|
528
|
+
overran = true;
|
|
529
|
+
stopped?.();
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const refusal = "value" in reply ? task.beforeSubmit?.(reply.value) : reply.problem;
|
|
533
|
+
if ("value" in reply && refusal === void 0) {
|
|
534
|
+
submitted = { value: reply.value };
|
|
535
|
+
stats.result = cut(reply.value, MAX_RUN_PROMPT);
|
|
536
|
+
if (stats.record.length < 60) stats.record.push({
|
|
537
|
+
tool: "reply",
|
|
538
|
+
args: "",
|
|
539
|
+
outcome: cut(reply.value),
|
|
540
|
+
failed: false
|
|
541
|
+
});
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
refusals += 1;
|
|
545
|
+
lastRefusal = refusal ?? "";
|
|
546
|
+
if (stats.record.length < 60) stats.record.push({
|
|
547
|
+
tool: "reply",
|
|
548
|
+
args: "",
|
|
549
|
+
outcome: cut(lastRefusal),
|
|
550
|
+
failed: true
|
|
551
|
+
});
|
|
552
|
+
if (refusals >= 5) {
|
|
553
|
+
overran = true;
|
|
554
|
+
stopped?.();
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
child.steer(createUserMessage({
|
|
558
|
+
content: [{
|
|
559
|
+
type: "text",
|
|
560
|
+
text: `That reply cannot be used: ${lastRefusal}\nReply again with the whole result as one JSON object.`
|
|
561
|
+
}],
|
|
562
|
+
source: { kind: "roleplay" }
|
|
563
|
+
}));
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
482
566
|
if (cutOff(child)) {
|
|
483
567
|
rambled = true;
|
|
484
568
|
overran = true;
|
|
485
569
|
stopped?.();
|
|
486
570
|
return;
|
|
487
571
|
}
|
|
488
|
-
if (reminders >=
|
|
572
|
+
if (reminders >= 2) return;
|
|
489
573
|
reminders += 1;
|
|
490
574
|
child.steer(createUserMessage({
|
|
491
575
|
content: [{
|
|
@@ -499,7 +583,23 @@ async function execute(task, stats) {
|
|
|
499
583
|
}
|
|
500
584
|
};
|
|
501
585
|
helpers.set(childId, entry);
|
|
502
|
-
if (task.
|
|
586
|
+
if (task.structured === true) {
|
|
587
|
+
const { toolChoice: _unused, ...rest } = task.sampling ?? {};
|
|
588
|
+
samplings.set(childId, {
|
|
589
|
+
...rest,
|
|
590
|
+
body: {
|
|
591
|
+
...rest.body,
|
|
592
|
+
response_format: {
|
|
593
|
+
type: "json_schema",
|
|
594
|
+
json_schema: {
|
|
595
|
+
name: "result",
|
|
596
|
+
strict: true,
|
|
597
|
+
schema: task.result
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
} else if (task.sampling !== void 0) samplings.set(childId, task.sampling);
|
|
503
603
|
try {
|
|
504
604
|
const subagents = parent.ctx.get("subagents");
|
|
505
605
|
if (subagents === void 0) throw new Error("the sub-agent service is not loaded");
|
|
@@ -527,12 +627,14 @@ async function execute(task, stats) {
|
|
|
527
627
|
}
|
|
528
628
|
});
|
|
529
629
|
try {
|
|
530
|
-
await activation.result;
|
|
630
|
+
await Promise.race([activation.result, gaveUp]);
|
|
531
631
|
} catch (error) {
|
|
532
632
|
if (submitted === void 0 && !overran && !signal.aborted) throw error;
|
|
533
633
|
} finally {
|
|
534
634
|
if (entry.agent !== void 0) stats.tokens = tokensOf(entry.agent.session.snapshotEvents());
|
|
535
|
-
await activation.dispose()
|
|
635
|
+
await (overran ? Promise.race([activation.dispose(), new Promise((resolve) => {
|
|
636
|
+
setTimeout(resolve, STOP_GRACE_MS);
|
|
637
|
+
})]) : activation.dispose());
|
|
536
638
|
}
|
|
537
639
|
} finally {
|
|
538
640
|
helpers.delete(childId);
|
|
@@ -540,7 +642,7 @@ async function execute(task, stats) {
|
|
|
540
642
|
}
|
|
541
643
|
if (signal.aborted) throw new Error("cancelled");
|
|
542
644
|
if (rambled && submitted === void 0) throw new Error(`the agent wrote text up to the limit of ${task.maxTokens ?? task.sampling?.maxTokens ?? "its model"} tokens and never called ${SUBMIT_TOOL}, and was stopped`);
|
|
543
|
-
if (overran && submitted === void 0) throw new Error(refusals >=
|
|
645
|
+
if (overran && submitted === void 0) throw new Error(refusals >= 5 ? `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`);
|
|
544
646
|
if (submitted === void 0) {
|
|
545
647
|
const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
|
|
546
648
|
const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
|
|
@@ -549,7 +651,6 @@ async function execute(task, stats) {
|
|
|
549
651
|
}
|
|
550
652
|
return submitted.value;
|
|
551
653
|
}
|
|
552
|
-
//#endregion
|
|
553
654
|
export { finishOf as _, childTrace as a, runChild as c, sharedSamplingOf as d, tokensOf as f, cutOff as g, currentTurn as h, childSamplingOf as i, SAMPLING_RANGES as l, addTokens as m, childModel as n, helpers as o, NO_TOKENS as p, childSampling as r, namedModel as s, ChildTimeoutError as t, parseSampling as u, estimateAnswer as v, tokensOf$1 as y };
|
|
554
655
|
|
|
555
|
-
//# sourceMappingURL=child-
|
|
656
|
+
//# sourceMappingURL=child-lYYeOwl2.js.map
|