@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,17 @@
|
|
|
1
|
+
//#region src/shared/doctor-chat.ts
|
|
2
|
+
const PREFIX = "doctor-";
|
|
3
|
+
const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
4
|
+
/** Stable DSH chat identity for the session doctor of one roleplay session. */
|
|
5
|
+
function doctorChatSessionId(sessionId) {
|
|
6
|
+
return `${PREFIX}${sessionId}`;
|
|
7
|
+
}
|
|
8
|
+
/** The roleplay session a session doctor chat looks after. */
|
|
9
|
+
function doctorSessionOf(chat) {
|
|
10
|
+
if (!chat.startsWith(PREFIX)) return void 0;
|
|
11
|
+
const id = chat.slice(7);
|
|
12
|
+
return UUID_V4.test(id) ? id : void 0;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { doctorSessionOf as n, doctorChatSessionId as t };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=doctor-chat-ByDfCMeo.js.map
|
package/lib/doctor.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { n as chatSessionId } from "./access-EbNdZFbk.js";
|
|
2
|
+
import "./language-DWVwi1R7.js";
|
|
3
|
+
import { d as externalTools } from "./deliver-CpZOxBX5.js";
|
|
4
|
+
import { a as liveSettings } from "./narration-DK2kiIjE.js";
|
|
5
|
+
import { n as doctorSessionOf } from "./doctor-chat-ByDfCMeo.js";
|
|
6
|
+
import { t as externalToolLimit } from "./hooks-KTCR3fNJ.js";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
10
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
11
|
+
import { createTools, isSessionId, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
|
|
12
|
+
//#region src/host/agent/doctor-undo.ts
|
|
13
|
+
const UNDO_SNAPSHOT = "doctor-undo";
|
|
14
|
+
const UNDO_KEY = "doctor.undo";
|
|
15
|
+
var UndoRefusedError = class extends Error {};
|
|
16
|
+
/** Keeps the story as it stands, to put back after the one approved edit that is about to be applied. */
|
|
17
|
+
function keepBeforeEdit(deps, id) {
|
|
18
|
+
const dir = deps.sessionsDir();
|
|
19
|
+
deps.state.snapshot(dir, id, UNDO_SNAPSHOT);
|
|
20
|
+
const { metadata } = deps.state.openSession(dir, id);
|
|
21
|
+
metadata.setValue(UNDO_KEY, { turns: metadata.get().turns });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Puts the story back as it was before the last edit the doctor applied. The story is not taken back across a turn: what a later turn recorded
|
|
25
|
+
* and the conversation it went with would no longer match.
|
|
26
|
+
* @throws {UndoRefusedError} when nothing was kept, a turn was played or is playing since, or the edit was undone already.
|
|
27
|
+
*/
|
|
28
|
+
async function undoLastEdit(deps, id) {
|
|
29
|
+
const dir = deps.sessionsDir();
|
|
30
|
+
const session = deps.state.openSession(dir, id);
|
|
31
|
+
const kept = session.metadata.getValue(UNDO_KEY);
|
|
32
|
+
if (kept === void 0 || !deps.state.snapshots(dir, id).includes("doctor-undo")) throw new UndoRefusedError("there is no edit of mine to undo: nothing was kept, or it was undone already");
|
|
33
|
+
if (deps.busy(id)) throw new UndoRefusedError("a turn is being played: undo after it has been delivered, and only if no turn is played after it");
|
|
34
|
+
if (session.metadata.get().turns !== kept.turns) throw new UndoRefusedError("a turn was played after the edit, so the story cannot be put back without losing it: mend what is wrong with a new edit instead");
|
|
35
|
+
await deps.halt(id);
|
|
36
|
+
deps.state.restore(dir, id, UNDO_SNAPSHOT);
|
|
37
|
+
deps.state.removeSnapshot(dir, id, UNDO_SNAPSHOT);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/doctor.ts
|
|
41
|
+
const name = "@dsh-agentic-roleplay/core/doctor";
|
|
42
|
+
const inject = [
|
|
43
|
+
"roleplayState",
|
|
44
|
+
"roleplayRoot",
|
|
45
|
+
"roleplayPrompts",
|
|
46
|
+
"roleplayOrchestration",
|
|
47
|
+
"tools",
|
|
48
|
+
"systemPrompt",
|
|
49
|
+
"agents"
|
|
50
|
+
];
|
|
51
|
+
const DOCTOR_TOOL = "edit_records";
|
|
52
|
+
const UNDO_TOOL = "undo_last_edit";
|
|
53
|
+
const SHOWN_EDIT = 700;
|
|
54
|
+
/** What the person is asked to approve: the edit, as it will be applied. */
|
|
55
|
+
function doctorApproval(exec) {
|
|
56
|
+
if (exec.agent === void 0 || doctorSessionOf(exec.agent.session.id) === void 0) return void 0;
|
|
57
|
+
if (exec.name === UNDO_TOOL) return {
|
|
58
|
+
kind: "ask",
|
|
59
|
+
reason: "put the story back as it was before my last edit",
|
|
60
|
+
displayReason: {
|
|
61
|
+
en: "Put the story back as it was before the last edit?",
|
|
62
|
+
zh: "把故事恢复到上一次修改之前?"
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
if (exec.name !== DOCTOR_TOOL) return void 0;
|
|
66
|
+
const { turn: _turn, ...edit } = exec.arguments;
|
|
67
|
+
if (Object.keys(edit).length === 0) return {
|
|
68
|
+
kind: "deny",
|
|
69
|
+
reason: "the edit changes nothing: put what to change in it (for example states, beliefs, relationships, item_changes)"
|
|
70
|
+
};
|
|
71
|
+
const text = JSON.stringify(edit);
|
|
72
|
+
const shown = text.length > SHOWN_EDIT ? `${text.slice(0, SHOWN_EDIT)}…` : text;
|
|
73
|
+
return {
|
|
74
|
+
kind: "ask",
|
|
75
|
+
reason: `change the story's records: ${shown}`,
|
|
76
|
+
displayReason: {
|
|
77
|
+
en: `Change the story's records?\n${shown}`,
|
|
78
|
+
zh: `修改故事的记录?\n${shown}`
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function apply(ctx) {
|
|
83
|
+
const sessionsDir = () => join(ctx.roleplayRoot.path, "sessions");
|
|
84
|
+
const resolve = (chat) => {
|
|
85
|
+
const id = doctorSessionOf(chat);
|
|
86
|
+
if (id === void 0 || !isSessionId(id) || !existsSync(sessionDatabase(sessionsDir(), id))) return void 0;
|
|
87
|
+
const session = ctx.roleplayState.openSession(sessionsDir(), id);
|
|
88
|
+
const settings = liveSettings(sessionFolder(sessionsDir(), id));
|
|
89
|
+
return {
|
|
90
|
+
session,
|
|
91
|
+
turn: session.metadata.get().turns,
|
|
92
|
+
policy: settings.memory,
|
|
93
|
+
timeZone: settings.clock.timeZone
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
ctx.effect(() => ctx.roleplayState.bind(resolve), "roleplay: session doctor reads");
|
|
97
|
+
const undo = {
|
|
98
|
+
state: ctx.roleplayState,
|
|
99
|
+
sessionsDir,
|
|
100
|
+
busy: (id) => {
|
|
101
|
+
const agent = ctx.agents.get(SessionId(chatSessionId(id)));
|
|
102
|
+
return agent !== void 0 && agent.status !== "idle";
|
|
103
|
+
},
|
|
104
|
+
halt: (id) => ctx.roleplayOrchestration.halt(chatSessionId(id))
|
|
105
|
+
};
|
|
106
|
+
for (const tool of createTools(resolve, { write: true }).filter((candidate) => candidate.name === DOCTOR_TOOL)) ctx.tools.register(inTurn(tool, resolve, (id) => keepBeforeEdit(undo, id)));
|
|
107
|
+
ctx.tools.register(undoTool(undo));
|
|
108
|
+
ctx.on("tools/pre-execute", async (exec, next) => doctorApproval(exec) ?? await next());
|
|
109
|
+
ctx.on("agent/created", ({ agent }) => {
|
|
110
|
+
if (doctorSessionOf(agent.session.id) !== void 0 && agent.session.header.origin !== "subagent") externalToolLimit(agent, externalTools(agent.ctx.tools).map((tool) => tool.name));
|
|
111
|
+
});
|
|
112
|
+
const languageOf = (context) => {
|
|
113
|
+
const chat = context.agent?.session.id;
|
|
114
|
+
const id = chat === void 0 ? void 0 : doctorSessionOf(chat);
|
|
115
|
+
return id !== void 0 && isSessionId(id) && existsSync(sessionDatabase(sessionsDir(), id)) ? liveSettings(sessionFolder(sessionsDir(), id)).prompts.language : "en";
|
|
116
|
+
};
|
|
117
|
+
for (const [section, order, id] of [[
|
|
118
|
+
"SESSION_DOCTOR_PERSONA",
|
|
119
|
+
ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
|
|
120
|
+
"doctor/persona"
|
|
121
|
+
], [
|
|
122
|
+
"SESSION_DOCTOR_PROCEDURE",
|
|
123
|
+
ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_SUFFIX"),
|
|
124
|
+
"doctor/procedure"
|
|
125
|
+
]]) ctx.systemPrompt.section({
|
|
126
|
+
name: section,
|
|
127
|
+
order,
|
|
128
|
+
interpolate: false,
|
|
129
|
+
text: (context) => ctx.roleplayPrompts.text(id, languageOf(context))
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** The edit is written at the turn the story is at (the first, in a story with none played), whatever turn the model put in it. */
|
|
133
|
+
function inTurn(tool, resolve, keep) {
|
|
134
|
+
return {
|
|
135
|
+
...tool,
|
|
136
|
+
async execute(args, exec) {
|
|
137
|
+
const link = exec.agent === void 0 ? void 0 : resolve(exec.agent.session.id);
|
|
138
|
+
const story = exec.agent === void 0 ? void 0 : doctorSessionOf(exec.agent.session.id);
|
|
139
|
+
if (story !== void 0) keep(story);
|
|
140
|
+
return await tool.execute(link === void 0 ? args : {
|
|
141
|
+
...args,
|
|
142
|
+
turn: Math.max(1, link.turn)
|
|
143
|
+
}, exec);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function undoTool(deps) {
|
|
148
|
+
return defineTool({
|
|
149
|
+
name: UNDO_TOOL,
|
|
150
|
+
description: "Put the story back as it was before the last edit you applied, when that edit turned out wrong. Only possible while no turn has been played since, and only once: the player is asked first.",
|
|
151
|
+
parameters: {},
|
|
152
|
+
output: {
|
|
153
|
+
schema: { type: "json" },
|
|
154
|
+
render: (_args, value) => [{
|
|
155
|
+
type: "text",
|
|
156
|
+
text: value.text
|
|
157
|
+
}]
|
|
158
|
+
},
|
|
159
|
+
isConcurrencySafe: () => false,
|
|
160
|
+
async execute(_args, exec) {
|
|
161
|
+
const story = exec.agent === void 0 ? void 0 : doctorSessionOf(exec.agent.session.id);
|
|
162
|
+
if (story === void 0) throw new Error("this tool is for a session doctor chat");
|
|
163
|
+
await undoLastEdit(deps, story);
|
|
164
|
+
return { text: "The story is as it was before the last edit. Read the records again before saying what stands." };
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
export { apply, doctorApproval, inject, name };
|
|
170
|
+
|
|
171
|
+
//# sourceMappingURL=doctor.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-
|
|
1
|
+
import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
|
|
2
2
|
import { join, sep } from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
@@ -192,4 +192,4 @@ async function updateImage(sessionFolder, path, update) {
|
|
|
192
192
|
//#endregion
|
|
193
193
|
export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
|
|
194
194
|
|
|
195
|
-
//# sourceMappingURL=gallery-
|
|
195
|
+
//# sourceMappingURL=gallery-CtFDL22W.js.map
|
|
@@ -1,383 +1,7 @@
|
|
|
1
1
|
import { dirname, extname, join } from "node:path";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
5
|
-
import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
6
|
-
import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
|
|
7
|
-
import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
|
|
8
4
|
import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
9
|
-
//#region src/host/agents/budget.ts
|
|
10
|
-
/** 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. */
|
|
11
|
-
function tokensOf(characters, language) {
|
|
12
|
-
return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* 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
|
|
16
|
-
* 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.
|
|
17
|
-
*/
|
|
18
|
-
function outputBudget(estimate, headroom) {
|
|
19
|
-
return Math.ceil(estimate * headroom / 10) * 10;
|
|
20
|
-
}
|
|
21
|
-
/** The estimate of an answer made of texts that each have a declared limit in characters. */
|
|
22
|
-
function estimateAnswer(limits, language) {
|
|
23
|
-
return limits.reduce((sum, limit) => sum + tokensOf(limit, language) + 8, 0);
|
|
24
|
-
}
|
|
25
|
-
//#endregion
|
|
26
|
-
//#region src/shared/activity.ts
|
|
27
|
-
/** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
|
|
28
|
-
const MAX_RUN_TEXT = 4e3;
|
|
29
|
-
const MAX_RUN_PROMPT = 24e3;
|
|
30
|
-
//#endregion
|
|
31
|
-
//#region src/host/agents/child.ts
|
|
32
|
-
/** The tool every child ends with: its arguments are the child's result. */
|
|
33
|
-
const SUBMIT_TOOL = "submit_result";
|
|
34
|
-
/** 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. */
|
|
35
|
-
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.`;
|
|
36
|
-
/** Calls a child may make before it is given up; a child that keeps going is not converging. */
|
|
37
|
-
const DEFAULT_MAX_CALLS = 40;
|
|
38
|
-
/** A child that stops without a result is told to submit this many times before it is given up. */
|
|
39
|
-
const MAX_REMINDERS = 2;
|
|
40
|
-
/** 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. */
|
|
41
|
-
const OVERRUN = 5;
|
|
42
|
-
/** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
|
|
43
|
-
const STEPS_AFTER_RETIRE = 3;
|
|
44
|
-
/** 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. */
|
|
45
|
-
const REPEATS_TOLD = 1;
|
|
46
|
-
const REPEATS_STOPPED = 4;
|
|
47
|
-
/** 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. */
|
|
48
|
-
const MAX_REFUSALS = 5;
|
|
49
|
-
/**
|
|
50
|
-
* 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)
|
|
51
|
-
* is let produce that with room to spare, no more than the chat's ceiling for its kind.
|
|
52
|
-
*/
|
|
53
|
-
function childSampling(settings, kind, estimate) {
|
|
54
|
-
const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
|
|
55
|
-
return {
|
|
56
|
-
temperature: settings.sampling[kind],
|
|
57
|
-
toolChoice: settings.sampling.tools,
|
|
58
|
-
maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
|
|
59
|
-
priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
/** 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. */
|
|
63
|
-
function childTrace(store, kind, label, extra = {}, named) {
|
|
64
|
-
const model = (named ?? store.settings().models[kind]).trim();
|
|
65
|
-
return (run) => {
|
|
66
|
-
const keep = store.settings().diagnostics.keepRuns;
|
|
67
|
-
const id = keep ? randomUUID() : void 0;
|
|
68
|
-
store.recordActivity({
|
|
69
|
-
at: Date.now(),
|
|
70
|
-
label,
|
|
71
|
-
model,
|
|
72
|
-
ms: run.ms,
|
|
73
|
-
calls: run.calls,
|
|
74
|
-
...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
|
|
75
|
-
...id === void 0 ? {} : { run: id }
|
|
76
|
-
}, keep ? {
|
|
77
|
-
...run.detail,
|
|
78
|
-
...extra
|
|
79
|
-
} : void 0);
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
/** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
|
|
83
|
-
function childModel(settings, kind, override) {
|
|
84
|
-
const named = (override ?? settings.models[kind]).trim();
|
|
85
|
-
if (named === "") return {};
|
|
86
|
-
const slash = named.indexOf("/");
|
|
87
|
-
return { model: {
|
|
88
|
-
provider: named.slice(0, slash),
|
|
89
|
-
model: named.slice(slash + 1)
|
|
90
|
-
} };
|
|
91
|
-
}
|
|
92
|
-
const samplings = /* @__PURE__ */ new Map();
|
|
93
|
-
/** The controls set for a running child, by its session id. */
|
|
94
|
-
const childSamplingOf = (sessionId) => samplings.get(sessionId);
|
|
95
|
-
/**
|
|
96
|
-
* Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
|
|
97
|
-
* have tools of its own, so several can run side by side with different tools and different
|
|
98
|
-
* results from the same tool.
|
|
99
|
-
*
|
|
100
|
-
* This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
|
|
101
|
-
* composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
|
|
102
|
-
* `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
|
|
103
|
-
* this is accepted, which DSH version it is built against, and what to do when DSH changes.
|
|
104
|
-
* @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
|
|
105
|
-
*/
|
|
106
|
-
function childOptions(task) {
|
|
107
|
-
const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
|
|
108
|
-
const options = {
|
|
109
|
-
...task.reasoningEffort === void 0 || task.reasoningEffort === "" ? {} : { reasoningEffort: ReasoningEffortId(task.reasoningEffort) },
|
|
110
|
-
...maxTokens === void 0 ? {} : { maxTokens },
|
|
111
|
-
...task.model === void 0 ? {} : {
|
|
112
|
-
provider: task.model.provider,
|
|
113
|
-
model: task.model.model
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
return Object.keys(options).length === 0 ? void 0 : options;
|
|
117
|
-
}
|
|
118
|
-
/** The schema an answer is checked against: the one the model was given, without requiring what it was only asked for ({@link ChildTask.unenforced}). */
|
|
119
|
-
function enforcedSchema(task) {
|
|
120
|
-
const skipped = task.unenforced ?? [];
|
|
121
|
-
return skipped.length === 0 || task.result.required === void 0 ? task.result : {
|
|
122
|
-
...task.result,
|
|
123
|
-
required: task.result.required.filter((name) => !skipped.includes(name))
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
/** 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. */
|
|
127
|
-
const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
|
|
128
|
-
async function runChild(task) {
|
|
129
|
-
for (let attempt = 1;; attempt += 1) {
|
|
130
|
-
const began = Date.now();
|
|
131
|
-
const stats = {
|
|
132
|
-
calls: 0,
|
|
133
|
-
record: []
|
|
134
|
-
};
|
|
135
|
-
const detail = () => ({
|
|
136
|
-
persona: task.persona.slice(0, MAX_RUN_PROMPT),
|
|
137
|
-
prompt: task.prompt.slice(0, MAX_RUN_PROMPT),
|
|
138
|
-
calls: stats.record,
|
|
139
|
-
...stats.result === void 0 ? {} : { result: stats.result }
|
|
140
|
-
});
|
|
141
|
-
try {
|
|
142
|
-
const result = await execute(task, stats);
|
|
143
|
-
task.trace?.({
|
|
144
|
-
ms: Date.now() - began,
|
|
145
|
-
calls: stats.calls,
|
|
146
|
-
detail: detail()
|
|
147
|
-
});
|
|
148
|
-
return result;
|
|
149
|
-
} catch (error) {
|
|
150
|
-
task.trace?.({
|
|
151
|
-
ms: Date.now() - began,
|
|
152
|
-
calls: stats.calls,
|
|
153
|
-
error: error instanceof Error ? error.message : String(error),
|
|
154
|
-
detail: detail()
|
|
155
|
-
});
|
|
156
|
-
if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* 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
|
|
162
|
-
* helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
|
|
163
|
-
*/
|
|
164
|
-
async function supportedEffort(task) {
|
|
165
|
-
const level = task.reasoningEffort;
|
|
166
|
-
if (level === void 0 || level === "" || task.model === void 0) return level;
|
|
167
|
-
try {
|
|
168
|
-
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;
|
|
169
|
-
} catch {
|
|
170
|
-
return level;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
const cut = (value, limit = MAX_RUN_TEXT) => {
|
|
174
|
-
const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
|
|
175
|
-
return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
|
|
176
|
-
};
|
|
177
|
-
async function execute(task, stats) {
|
|
178
|
-
const { parent, signal } = task;
|
|
179
|
-
const reasoningEffort = await supportedEffort(task);
|
|
180
|
-
let submitted;
|
|
181
|
-
let reminders = 0;
|
|
182
|
-
let stopped;
|
|
183
|
-
let retire;
|
|
184
|
-
let stepsAfterRetire = -1;
|
|
185
|
-
let overran = false;
|
|
186
|
-
let refusals = 0;
|
|
187
|
-
let lastRefusal = "";
|
|
188
|
-
let previous;
|
|
189
|
-
const budget = task.maxCalls ?? DEFAULT_MAX_CALLS;
|
|
190
|
-
const counted = (tool) => ({
|
|
191
|
-
...tool,
|
|
192
|
-
execute: async (args, exec) => {
|
|
193
|
-
stats.calls += 1;
|
|
194
|
-
const note = (outcome, failed) => {
|
|
195
|
-
if (stats.record.length < 60) stats.record.push({
|
|
196
|
-
tool: tool.name,
|
|
197
|
-
args: cut(args),
|
|
198
|
-
outcome: cut(outcome),
|
|
199
|
-
failed
|
|
200
|
-
});
|
|
201
|
-
};
|
|
202
|
-
if (stats.calls > budget + OVERRUN) {
|
|
203
|
-
overran = true;
|
|
204
|
-
stopped?.();
|
|
205
|
-
}
|
|
206
|
-
if (stats.calls > budget) {
|
|
207
|
-
const message = `you have made ${budget} calls: submit your result now and say what is still missing`;
|
|
208
|
-
note(message, true);
|
|
209
|
-
throw new Error(message);
|
|
210
|
-
}
|
|
211
|
-
const signature = JSON.stringify(args);
|
|
212
|
-
const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
|
|
213
|
-
if (repeats >= REPEATS_STOPPED) {
|
|
214
|
-
overran = true;
|
|
215
|
-
stopped?.();
|
|
216
|
-
}
|
|
217
|
-
if (repeats >= REPEATS_TOLD) {
|
|
218
|
-
previous = {
|
|
219
|
-
name: tool.name,
|
|
220
|
-
args: signature,
|
|
221
|
-
failed: true,
|
|
222
|
-
repeats
|
|
223
|
-
};
|
|
224
|
-
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";
|
|
225
|
-
note(message, true);
|
|
226
|
-
throw new Error(message);
|
|
227
|
-
}
|
|
228
|
-
previous = {
|
|
229
|
-
name: tool.name,
|
|
230
|
-
args: signature,
|
|
231
|
-
failed: false,
|
|
232
|
-
repeats
|
|
233
|
-
};
|
|
234
|
-
try {
|
|
235
|
-
const outcome = await tool.execute(args, exec);
|
|
236
|
-
note(outcome, false);
|
|
237
|
-
return outcome;
|
|
238
|
-
} catch (error) {
|
|
239
|
-
if (previous !== void 0) previous.failed = true;
|
|
240
|
-
note(error instanceof Error ? error.message : String(error), true);
|
|
241
|
-
throw error;
|
|
242
|
-
} finally {
|
|
243
|
-
if (stats.calls >= budget) retire?.();
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
});
|
|
247
|
-
const submit = {
|
|
248
|
-
name: SUBMIT_TOOL,
|
|
249
|
-
description: "Submit your final result. Call it exactly once, when you are done; the arguments are the result.",
|
|
250
|
-
parameters: task.result,
|
|
251
|
-
output: {
|
|
252
|
-
schema: {
|
|
253
|
-
type: "object",
|
|
254
|
-
properties: { recorded: {
|
|
255
|
-
type: "boolean",
|
|
256
|
-
const: true
|
|
257
|
-
} },
|
|
258
|
-
required: ["recorded"],
|
|
259
|
-
additionalProperties: false
|
|
260
|
-
},
|
|
261
|
-
render: () => [{
|
|
262
|
-
type: "text",
|
|
263
|
-
text: "Result recorded."
|
|
264
|
-
}]
|
|
265
|
-
},
|
|
266
|
-
execute(args, exec) {
|
|
267
|
-
const violations = validateJsonSchemaValue(enforcedSchema(task), args);
|
|
268
|
-
if (violations.length > 0) throw new ToolArgsError(violations);
|
|
269
|
-
const refusal = task.beforeSubmit?.(args);
|
|
270
|
-
if (refusal !== void 0) {
|
|
271
|
-
if (stats.record.length < 60) stats.record.push({
|
|
272
|
-
tool: SUBMIT_TOOL,
|
|
273
|
-
args: cut(args),
|
|
274
|
-
outcome: cut(refusal),
|
|
275
|
-
failed: true
|
|
276
|
-
});
|
|
277
|
-
refusals += 1;
|
|
278
|
-
lastRefusal = refusal;
|
|
279
|
-
if (refusals >= MAX_REFUSALS) {
|
|
280
|
-
overran = true;
|
|
281
|
-
stopped?.();
|
|
282
|
-
}
|
|
283
|
-
throw new Error(refusal);
|
|
284
|
-
}
|
|
285
|
-
submitted = { value: args };
|
|
286
|
-
stats.result = cut(args, MAX_RUN_PROMPT);
|
|
287
|
-
if (stats.record.length < 60) stats.record.push({
|
|
288
|
-
tool: SUBMIT_TOOL,
|
|
289
|
-
args: cut(args),
|
|
290
|
-
outcome: "Result recorded.",
|
|
291
|
-
failed: false
|
|
292
|
-
});
|
|
293
|
-
exec.concludeTurn();
|
|
294
|
-
return Promise.resolve({ recorded: true });
|
|
295
|
-
}
|
|
296
|
-
};
|
|
297
|
-
const depth = resolveChildDepth(parent, void 0);
|
|
298
|
-
const inherited = captureDelegatedPolicyOverrides(parent);
|
|
299
|
-
const sessionId = SessionId(randomUUID());
|
|
300
|
-
if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
|
|
301
|
-
const handle = await parent.ctx.agents.create({
|
|
302
|
-
sessionId,
|
|
303
|
-
parentAgent: parent,
|
|
304
|
-
meta: childSessionMeta(parent, depth, false),
|
|
305
|
-
agentOptions: resolveChildAgentOptions(parent, childOptions({
|
|
306
|
-
...task,
|
|
307
|
-
...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
|
|
308
|
-
}), depth),
|
|
309
|
-
signal,
|
|
310
|
-
setup: (childCtx, child) => {
|
|
311
|
-
appendDelegatedPolicyOverrides(child.session, inherited);
|
|
312
|
-
applyChildComposition(childCtx, parent, {
|
|
313
|
-
persona: `${task.persona}\n\n${SUBMIT_RULE}`,
|
|
314
|
-
toolFilter: { allow: [...task.external ?? []] }
|
|
315
|
-
});
|
|
316
|
-
const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
|
|
317
|
-
retire = () => {
|
|
318
|
-
for (const dispose of registered) dispose();
|
|
319
|
-
if (stepsAfterRetire < 0) stepsAfterRetire = 0;
|
|
320
|
-
};
|
|
321
|
-
childCtx.on("agent/pre-step", async (_payload, next) => {
|
|
322
|
-
const decision = await next();
|
|
323
|
-
if (stepsAfterRetire < 0) return decision;
|
|
324
|
-
stepsAfterRetire += 1;
|
|
325
|
-
if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
|
|
326
|
-
overran = true;
|
|
327
|
-
stopped?.();
|
|
328
|
-
}
|
|
329
|
-
return decision;
|
|
330
|
-
});
|
|
331
|
-
childCtx.tools.register(submit);
|
|
332
|
-
childCtx.on("agent/turn-stopping", () => {
|
|
333
|
-
if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
|
|
334
|
-
reminders += 1;
|
|
335
|
-
child.steer(createUserMessage({
|
|
336
|
-
content: [{
|
|
337
|
-
type: "text",
|
|
338
|
-
text: `You have not finished: call ${SUBMIT_TOOL} with your result, as the tool lists it.`
|
|
339
|
-
}],
|
|
340
|
-
source: { kind: "roleplay" }
|
|
341
|
-
}));
|
|
342
|
-
});
|
|
343
|
-
childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
|
|
344
|
-
}
|
|
345
|
-
});
|
|
346
|
-
stopped = () => {
|
|
347
|
-
handle.agent.cancel({ kind: "parent" });
|
|
348
|
-
};
|
|
349
|
-
const onAbort = () => {
|
|
350
|
-
handle.agent.cancel({ kind: "parent" });
|
|
351
|
-
};
|
|
352
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
353
|
-
try {
|
|
354
|
-
handle.agent.followup(createUserMessage({
|
|
355
|
-
content: [{
|
|
356
|
-
type: "text",
|
|
357
|
-
text: task.prompt
|
|
358
|
-
}, ...(task.images ?? []).map((attachment) => ({
|
|
359
|
-
type: "image",
|
|
360
|
-
attachment
|
|
361
|
-
}))],
|
|
362
|
-
source: { kind: "user" }
|
|
363
|
-
}));
|
|
364
|
-
await handle.agent.whenIdle();
|
|
365
|
-
} finally {
|
|
366
|
-
signal.removeEventListener("abort", onAbort);
|
|
367
|
-
samplings.delete(sessionId);
|
|
368
|
-
await handle.dispose();
|
|
369
|
-
}
|
|
370
|
-
if (signal.aborted) throw new Error("cancelled");
|
|
371
|
-
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`);
|
|
372
|
-
if (submitted === void 0) {
|
|
373
|
-
const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
|
|
374
|
-
const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
|
|
375
|
-
if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
|
|
376
|
-
throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
|
|
377
|
-
}
|
|
378
|
-
return submitted.value;
|
|
379
|
-
}
|
|
380
|
-
//#endregion
|
|
381
5
|
//#region src/host/import/run.ts
|
|
382
6
|
/** Runs `work` on every item, at most `limit` at a time, and returns the results in the order of the items. */
|
|
383
7
|
async function mapLimit(items, limit, work) {
|
|
@@ -846,6 +470,6 @@ async function generateTransientImage(service, request) {
|
|
|
846
470
|
return path;
|
|
847
471
|
}
|
|
848
472
|
//#endregion
|
|
849
|
-
export {
|
|
473
|
+
export { norm as C, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
|
|
850
474
|
|
|
851
|
-
//# sourceMappingURL=generator-
|
|
475
|
+
//# sourceMappingURL=generator-B6FxlKOV.js.map
|