@dsh-agentic-roleplay/core 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{access-CfQWbNZP.js → access-CXtaZNbx.js} +50 -2
- package/lib/{authoring-tools-C_l07RYn.js → authoring-tools-B4mEdKp_.js} +144 -58
- package/lib/authoring.js +7 -7
- package/lib/{child-lYYeOwl2.js → child-Dtv76jNx.js} +116 -11
- package/lib/client.js +2805 -790
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +3 -3
- package/lib/doctor.js +3 -3
- package/lib/{gallery-q7niLtWn.js → gallery-BZJleAeH.js} +5 -9
- package/lib/{generator-BpjPrvHe.js → generator-Cg6CQc5S.js} +2 -2
- package/lib/helper.js +1 -1
- package/lib/{hooks-DNaDzMjW.js → hooks-DTjHWTfx.js} +132 -25
- package/lib/images.js +4 -4
- package/lib/index.js +362 -33
- package/lib/{library-CIkxhf_R.js → library-GIlrkOim.js} +6 -13
- package/lib/{lorebook-author-tools-BiMDmdFi.js → lorebook-author-tools-BCFFJSle.js} +6 -6
- package/lib/lorebook-authoring.js +4 -4
- package/lib/{narration-CjB_KwwY.js → narration-BVzew4-K.js} +7 -52
- package/lib/orchestration.js +155 -10
- package/lib/{pack-jail-B35Vx3hT.js → pack-jail-hsNQNTOf.js} +10 -10
- package/lib/{packs-BajKw7S9.js → packs-UpK_cvI4.js} +2 -2
- package/lib/{presenter-agent-jgtuTwZr.js → presenter-agent-DZOgBOR9.js} +12 -17
- package/lib/{preset-DWgkcPau.js → preset-Cyoj1ZWa.js} +4 -4
- package/lib/{preset-author-tools-BhuYIKms.js → preset-author-tools-RSta6pHK.js} +6 -6
- package/lib/preset-authoring.js +5 -5
- package/lib/{presets-9GzaSELc.js → presets-CvpsW_10.js} +7 -8
- package/lib/{reflection-4L0Plvct.js → reflection-0qTvw2It.js} +53 -26
- package/lib/{turn-guard-sCUXmp-5.js → turn-guard-BzNeGNnc.js} +3 -3
- package/package.json +2 -2
- package/prompts/en/checks/conflict.md +1 -1
- package/prompts/en/checks/decide-conflict.md +1 -1
- package/prompts/en/checks/decide-opening.md +1 -1
- package/prompts/en/checks/decide-same-value.md +1 -1
- package/prompts/en/checks/decide-sheet.md +1 -1
- package/prompts/en/checks/fidelity.md +1 -0
- package/prompts/zh/checks/conflict.md +1 -1
- package/prompts/zh/checks/decide-conflict.md +1 -1
- package/prompts/zh/checks/decide-opening.md +1 -1
- package/prompts/zh/checks/decide-same-value.md +1 -1
- package/prompts/zh/checks/decide-sheet.md +1 -1
- package/prompts/zh/checks/fidelity.md +1 -0
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { basename, dirname, join } from "node:path";
|
|
2
|
+
import { chmodSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
1
5
|
// src/shared/chat.ts
|
|
2
6
|
const CHAT_PREFIX = "session-";
|
|
3
7
|
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}$/;
|
|
@@ -135,6 +139,50 @@ const VARIABLE_VISIBILITIES = [
|
|
|
135
139
|
always: false,
|
|
136
140
|
builtin: true
|
|
137
141
|
}));
|
|
142
|
+
// src/host/atomic-write.ts
|
|
143
|
+
/**
|
|
144
|
+
* Replaces a file in one step: the data goes to a temporary file in the same folder and is renamed over the file, so an interruption leaves the old file or the new one,
|
|
145
|
+
* never half of either. Every writer of a file someone else may read at the same time goes through here.
|
|
146
|
+
*/
|
|
147
|
+
async function atomicWrite(file, data, options = {}) {
|
|
148
|
+
if (options.createDirectory === true) await mkdir(dirname(file), { recursive: true });
|
|
149
|
+
const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
|
|
150
|
+
try {
|
|
151
|
+
const mode = options.mode ?? await stat(file).then((value) => value.mode & 511, (error) => {
|
|
152
|
+
if (error.code === "ENOENT") return 420;
|
|
153
|
+
throw error;
|
|
154
|
+
});
|
|
155
|
+
await writeFile(temporary, data, { mode });
|
|
156
|
+
await chmod(temporary, mode);
|
|
157
|
+
await rename(temporary, file);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
await rm(temporary, { force: true });
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** A JSON file written the same way, with the indentation given (none by default) and a final newline when it is indented. */
|
|
164
|
+
async function atomicWriteJson(file, value, options = {}) {
|
|
165
|
+
const { indent, ...rest } = options;
|
|
166
|
+
await atomicWrite(file, indent === void 0 ? JSON.stringify(value) : `${JSON.stringify(value, null, indent)}\n`, rest);
|
|
167
|
+
}
|
|
168
|
+
/** The synchronous form, for the few writers that cannot wait (the chat settings, read at every step). */
|
|
169
|
+
function atomicWriteSync(file, data) {
|
|
170
|
+
const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
|
|
171
|
+
try {
|
|
172
|
+
let mode = 420;
|
|
173
|
+
try {
|
|
174
|
+
mode = statSync(file).mode & 511;
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (error.code !== "ENOENT") throw error;
|
|
177
|
+
}
|
|
178
|
+
writeFileSync(temporary, data, { mode });
|
|
179
|
+
chmodSync(temporary, mode);
|
|
180
|
+
renameSync(temporary, file);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
rmSync(temporary, { force: true });
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
138
186
|
// src/host/prompts/access.ts
|
|
139
187
|
/** The prompt `id` in `language`, from the library of the agent's own context. */
|
|
140
188
|
function promptFor(agent, id, language, variables) {
|
|
@@ -142,6 +190,6 @@ function promptFor(agent, id, language, variables) {
|
|
|
142
190
|
if (library === void 0) throw new Error("the prompt library is not running");
|
|
143
191
|
return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
|
|
144
192
|
}
|
|
145
|
-
export {
|
|
193
|
+
export { VARIABLE_KINDS as a, chatSessionId as c, atomicWriteSync as i, roleplaySessionOf as l, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
|
|
146
194
|
|
|
147
|
-
//# sourceMappingURL=access-
|
|
195
|
+
//# sourceMappingURL=access-CXtaZNbx.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import "./access-
|
|
2
|
-
import { A as sourcesFor, B as noAt, C as inert, Ct as CHARACTER_FILE_NAME, D as pruneLoreSubjects, Dt as InvalidEditProblems, E as pruneLinks, Et as readIdentifier, F as isLeftOut, Ft as LORE_SCOPES, H as yesAt, It as WEEKDAY_NAMES, J as cleanText, L as askYesNo, Lt as DEFAULT_SLOTS, M as classifyItems, N as findEntity, O as pruneMembers, P as ROLES, Pt as LORE_KINDS, Q as IMPORT_FOLDER, S as extractVariables, St as parseFactionFile, T as pruneKnowledge, Tt as readVariableValues, Y as itemise, Z as withPlayer, _ as characterDocument, _t as ITEM_FILE_NAME, a as isPresetName, b as extractStyle, bt as parseSlotsFile, ft as variableProblems, g as asWritten, gt as parseLocationFile, h as addLore, ht as LOCATION_FILE_NAME, it as readImportFolder, j as buildRoster, k as pruneRelationships, lt as VARIABLES_FILE_NAME, mt as parseLoreFile, nt as openingText, pt as LORE_FILE_NAME, st as parseImportCommand, tt as PICTURE_FILE, ut as loadVariables, v as emptyExtracted, vt as SLOTS_FILE_NAME, w as loreDocuments, wt as parseCharacterFile, xt as FACTION_FILE_NAME, y as extractEntities, yt as parseItemFile } from "./presets-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { n as atomicWrite, r as atomicWriteJson } from "./access-CXtaZNbx.js";
|
|
2
|
+
import { A as sourcesFor, B as noAt, C as inert, Ct as CHARACTER_FILE_NAME, D as pruneLoreSubjects, Dt as InvalidEditProblems, E as pruneLinks, Et as readIdentifier, F as isLeftOut, Ft as LORE_SCOPES, H as yesAt, It as WEEKDAY_NAMES, J as cleanText, L as askYesNo, Lt as DEFAULT_SLOTS, M as classifyItems, N as findEntity, O as pruneMembers, P as ROLES, Pt as LORE_KINDS, Q as IMPORT_FOLDER, S as extractVariables, St as parseFactionFile, T as pruneKnowledge, Tt as readVariableValues, Y as itemise, Z as withPlayer, _ as characterDocument, _t as ITEM_FILE_NAME, a as isPresetName, b as extractStyle, bt as parseSlotsFile, ft as variableProblems, g as asWritten, gt as parseLocationFile, h as addLore, ht as LOCATION_FILE_NAME, it as readImportFolder, j as buildRoster, k as pruneRelationships, lt as VARIABLES_FILE_NAME, mt as parseLoreFile, nt as openingText, pt as LORE_FILE_NAME, st as parseImportCommand, tt as PICTURE_FILE, ut as loadVariables, v as emptyExtracted, vt as SLOTS_FILE_NAME, w as loreDocuments, wt as parseCharacterFile, xt as FACTION_FILE_NAME, y as extractEntities, yt as parseItemFile } from "./presets-CvpsW_10.js";
|
|
3
|
+
import { f as parseSwitchboard } from "./narration-BVzew4-K.js";
|
|
4
|
+
import { G as commandFlagKey, J as Reader, Q as PROMPTS_FOLDER, U as plotReferenceProblems, V as loadPlots, X as errorMessage, Y as formatIssue, a as externalWithheld, at as shippedLanguages, et as copyWorldPrompts, gt as COMPARISONS, it as promptProblem, q as readDocument$1, r as externalGiven, rt as listFiles, st as shippedText, t as externalToolLimit, ut as InvalidWorldError } from "./hooks-DTjHWTfx.js";
|
|
5
5
|
import { t as trimCharacters } from "./text-CbGQhK1-.js";
|
|
6
|
-
import { c as runChild,
|
|
7
|
-
import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-
|
|
6
|
+
import { c as runChild, s as namedModel, t as ChildTimeoutError, u as parseSampling, v as currentTurn } from "./child-Dtv76jNx.js";
|
|
7
|
+
import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-GIlrkOim.js";
|
|
8
8
|
import { dirname, join, relative } from "node:path";
|
|
9
9
|
import { existsSync, readFileSync } from "node:fs";
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
@@ -1313,6 +1313,37 @@ function populateTriggers(session, definitions) {
|
|
|
1313
1313
|
})));
|
|
1314
1314
|
for (const definition of definitions) session.triggers.add(definition, "world", 0);
|
|
1315
1315
|
}
|
|
1316
|
+
// src/host/worlds/scratch.ts
|
|
1317
|
+
/**
|
|
1318
|
+
* Runs `use` against an in-memory story made from the world's files, the way a session start fills one, and closes it again. The populate functions only use the repositories
|
|
1319
|
+
* a store has; the search a session adds is not needed.
|
|
1320
|
+
*/
|
|
1321
|
+
function withScratchStory(parts, use) {
|
|
1322
|
+
const scratch = createSessionStore(":memory:", {
|
|
1323
|
+
id: "scratch",
|
|
1324
|
+
name: "scratch",
|
|
1325
|
+
world: {
|
|
1326
|
+
id: "scratch",
|
|
1327
|
+
name: "scratch"
|
|
1328
|
+
}
|
|
1329
|
+
}, { vectors: false });
|
|
1330
|
+
try {
|
|
1331
|
+
const session = scratch;
|
|
1332
|
+
if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
|
|
1333
|
+
populateLocations(session, parts.locations);
|
|
1334
|
+
populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
|
|
1335
|
+
populateItems(session, parts.items, parts.slots, parts.locations);
|
|
1336
|
+
populateVariables(session, parts.variables, {
|
|
1337
|
+
characters: parts.characters,
|
|
1338
|
+
items: parts.items,
|
|
1339
|
+
locations: parts.locations,
|
|
1340
|
+
values: void 0
|
|
1341
|
+
});
|
|
1342
|
+
return use(session);
|
|
1343
|
+
} finally {
|
|
1344
|
+
scratch.close();
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1316
1347
|
// src/host/worlds/validated-world.ts
|
|
1317
1348
|
/**
|
|
1318
1349
|
* Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
|
|
@@ -1408,6 +1439,16 @@ async function loadValidatedWorld(world) {
|
|
|
1408
1439
|
path: world.directory,
|
|
1409
1440
|
message
|
|
1410
1441
|
})));
|
|
1442
|
+
withScratchStory({
|
|
1443
|
+
characters,
|
|
1444
|
+
locations,
|
|
1445
|
+
items,
|
|
1446
|
+
slots,
|
|
1447
|
+
variables: declared.defs,
|
|
1448
|
+
calendar
|
|
1449
|
+
}, (story) => {
|
|
1450
|
+
populateTriggers(story, scripted.triggers);
|
|
1451
|
+
});
|
|
1411
1452
|
return {
|
|
1412
1453
|
characters,
|
|
1413
1454
|
factions,
|
|
@@ -3603,37 +3644,6 @@ async function loadWorldParts(directory) {
|
|
|
3603
3644
|
calendar
|
|
3604
3645
|
};
|
|
3605
3646
|
}
|
|
3606
|
-
// src/host/worlds/scratch.ts
|
|
3607
|
-
/**
|
|
3608
|
-
* Runs `use` against an in-memory story made from the world's files, the way a session start fills one, and closes it again. The populate functions only use the repositories
|
|
3609
|
-
* a store has; the search a session adds is not needed.
|
|
3610
|
-
*/
|
|
3611
|
-
function withScratchStory(parts, use) {
|
|
3612
|
-
const scratch = createSessionStore(":memory:", {
|
|
3613
|
-
id: "scratch",
|
|
3614
|
-
name: "scratch",
|
|
3615
|
-
world: {
|
|
3616
|
-
id: "scratch",
|
|
3617
|
-
name: "scratch"
|
|
3618
|
-
}
|
|
3619
|
-
}, { vectors: false });
|
|
3620
|
-
try {
|
|
3621
|
-
const session = scratch;
|
|
3622
|
-
if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
|
|
3623
|
-
populateLocations(session, parts.locations);
|
|
3624
|
-
populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
|
|
3625
|
-
populateItems(session, parts.items, parts.slots, parts.locations);
|
|
3626
|
-
populateVariables(session, parts.variables, {
|
|
3627
|
-
characters: parts.characters,
|
|
3628
|
-
items: parts.items,
|
|
3629
|
-
locations: parts.locations,
|
|
3630
|
-
values: void 0
|
|
3631
|
-
});
|
|
3632
|
-
return use(session);
|
|
3633
|
-
} finally {
|
|
3634
|
-
scratch.close();
|
|
3635
|
-
}
|
|
3636
|
-
}
|
|
3637
3647
|
// src/host/worlds/world-info.ts
|
|
3638
3648
|
const textOf = (value) => typeof value === "string" ? value : "";
|
|
3639
3649
|
const toolsOf = (value) => {
|
|
@@ -4329,6 +4339,22 @@ async function verdictOf(model, state, key, instructions, ask) {
|
|
|
4329
4339
|
by: "language"
|
|
4330
4340
|
};
|
|
4331
4341
|
}
|
|
4342
|
+
/** A decision model's no only rules a pair out when it is this sure: the language model that follows must quote both sides, so passing on a doubtful pair costs a request, and dropping it loses a finding. */
|
|
4343
|
+
const RULED_OUT_CONFIDENCE = .95;
|
|
4344
|
+
/** Whether a pair is worth the language model's reading: everything except what the decision model is very sure is nothing. */
|
|
4345
|
+
async function worthReading(model, state, key, instructions) {
|
|
4346
|
+
if (model.decide === void 0) return true;
|
|
4347
|
+
try {
|
|
4348
|
+
const probability = (await model.decide(state, [{
|
|
4349
|
+
key,
|
|
4350
|
+
instructions
|
|
4351
|
+
}])).get(key);
|
|
4352
|
+
return probability === void 0 || probability > noAt(RULED_OUT_CONFIDENCE);
|
|
4353
|
+
} catch (error) {
|
|
4354
|
+
if (model.cancelled?.() === true) throw error;
|
|
4355
|
+
return true;
|
|
4356
|
+
}
|
|
4357
|
+
}
|
|
4332
4358
|
// src/host/checks/results.ts
|
|
4333
4359
|
/** Where a world keeps what its checks found: a dot folder, so what is published leaves it out, like the import's. */
|
|
4334
4360
|
const CHECKS_FOLDER = ".checks";
|
|
@@ -4446,27 +4472,46 @@ async function embedded(model, directory, texts, hashes, missing, known, stored)
|
|
|
4446
4472
|
}), { createDirectory: true });
|
|
4447
4473
|
return result;
|
|
4448
4474
|
}
|
|
4449
|
-
/**
|
|
4475
|
+
/** How many of its nearest neighbours set how crowded an entry's neighbourhood is. */
|
|
4476
|
+
const CROWD = 5;
|
|
4477
|
+
/** The most pairs asked however large the world, and the share of its entries a world may ask about. */
|
|
4478
|
+
const MOST_ASKED = 30;
|
|
4479
|
+
const ASKED_PER_ENTRY = 1 / 3;
|
|
4480
|
+
/**
|
|
4481
|
+
* The pairs of vectors that reach `threshold` and that `allowed` accepts, at most `limit`, best first. In a world of one theme everything is close to everything, so a double is
|
|
4482
|
+
* not among the closest by cosine; a pair is ranked by how much closer it is than each of the two is to its own neighbours (cosine minus the mean of each side's nearest, doubled
|
|
4483
|
+
* for the pair itself), which puts a copy of a crowded entry ahead of two crowded entries that merely share the theme.
|
|
4484
|
+
*/
|
|
4450
4485
|
function nearPairs(vectors, allowed, threshold, limit) {
|
|
4451
|
-
const
|
|
4486
|
+
const scored = [];
|
|
4487
|
+
const around = vectors.map(() => []);
|
|
4452
4488
|
for (let a = 0; a < vectors.length; a++) for (let b = a + 1; b < vectors.length; b++) {
|
|
4453
4489
|
if (!allowed(a, b)) continue;
|
|
4454
4490
|
const score = cosine(vectors[a], vectors[b]);
|
|
4455
|
-
|
|
4491
|
+
around[a].push(score);
|
|
4492
|
+
around[b].push(score);
|
|
4493
|
+
if (score >= threshold) scored.push({
|
|
4456
4494
|
a,
|
|
4457
4495
|
b,
|
|
4458
4496
|
score
|
|
4459
4497
|
});
|
|
4460
4498
|
}
|
|
4461
|
-
|
|
4499
|
+
const crowd = around.map((scores) => {
|
|
4500
|
+
const nearest = scores.sort((x, y) => y - x).slice(0, CROWD);
|
|
4501
|
+
return nearest.length === 0 ? 0 : nearest.reduce((sum, score) => sum + score, 0) / nearest.length;
|
|
4502
|
+
});
|
|
4503
|
+
const rank = (pair) => 2 * pair.score - crowd[pair.a] - crowd[pair.b];
|
|
4504
|
+
return scored.sort((x, y) => rank(y) - rank(x)).slice(0, limit);
|
|
4462
4505
|
}
|
|
4506
|
+
/** What a world of `entries` asks about: the base number, more for a large world. */
|
|
4507
|
+
const askedFor = (entries, base) => Math.min(MOST_ASKED, Math.max(base, Math.ceil(entries * ASKED_PER_ENTRY)));
|
|
4463
4508
|
/**
|
|
4464
4509
|
* The pairs of texts worth asking a model about: the closest in meaning when there is an embedding provider, otherwise, when asked to, the first `limit` pairs `allowed` accepts (for a short list), else nothing. Closeness only
|
|
4465
4510
|
* says two texts are about the same thing (trust and affection are close, and not one value), so it picks what to ask and never what is true.
|
|
4466
4511
|
*/
|
|
4467
4512
|
async function candidates(model, directory, texts, allowed, threshold, limit, withoutProvider = "none") {
|
|
4468
4513
|
const vectors = await vectorsOf(model, directory, texts);
|
|
4469
|
-
if (vectors !== void 0) return nearPairs(vectors, allowed, threshold, limit);
|
|
4514
|
+
if (vectors !== void 0) return nearPairs(vectors, allowed, threshold, askedFor(texts.length, limit));
|
|
4470
4515
|
if (withoutProvider === "none") return void 0;
|
|
4471
4516
|
const pairs = [];
|
|
4472
4517
|
for (let a = 0; a < texts.length && pairs.length < limit; a++) for (let b = a + 1; b < texts.length && pairs.length < limit; b++) if (allowed(a, b)) pairs.push({
|
|
@@ -4547,6 +4592,15 @@ const coverage = {
|
|
|
4547
4592
|
return foundBy("card-coverage", found);
|
|
4548
4593
|
}
|
|
4549
4594
|
};
|
|
4595
|
+
/** Which documents of the world a model found to say a piece in other words, by the piece's id: they were made from it, though their words no longer show it. */
|
|
4596
|
+
const rescuedBy = /* @__PURE__ */ new WeakMap();
|
|
4597
|
+
function rescued(input, piece, where) {
|
|
4598
|
+
if (input.memo === void 0) return;
|
|
4599
|
+
const all = rescuedBy.get(input.memo) ?? /* @__PURE__ */ new Map();
|
|
4600
|
+
all.set(piece, [.../* @__PURE__ */ new Set([...all.get(piece) ?? [], where])]);
|
|
4601
|
+
rescuedBy.set(input.memo, all);
|
|
4602
|
+
}
|
|
4603
|
+
const rescuedFor = (input, piece) => input.memo === void 0 ? [] : rescuedBy.get(input.memo)?.get(piece) ?? [];
|
|
4550
4604
|
/** The ids of the pieces whose facts a document of the world says in other words (or another language): the closest documents by meaning, and a model's yes. */
|
|
4551
4605
|
async function sayingByMeaning(input, pieces) {
|
|
4552
4606
|
const model = input.model;
|
|
@@ -4599,6 +4653,7 @@ async function lookedByMeaning(input, model, pieces, saved) {
|
|
|
4599
4653
|
})).covered;
|
|
4600
4654
|
})).yes) {
|
|
4601
4655
|
saved.add(piece.id);
|
|
4656
|
+
rescued(input, piece.id, document.where);
|
|
4602
4657
|
return;
|
|
4603
4658
|
}
|
|
4604
4659
|
}
|
|
@@ -4628,10 +4683,15 @@ const names = {
|
|
|
4628
4683
|
const source = basis(evidence);
|
|
4629
4684
|
const world = await loaded.text(input);
|
|
4630
4685
|
const text = folded([source.card.name, ...source.pieces.map((piece) => piece.text)].join("\n"));
|
|
4686
|
+
const wide = /[\u3000-\u9fff\uac00-\ud7af]/u;
|
|
4687
|
+
const cardHasWide = wide.test(text);
|
|
4688
|
+
const cardHasLatin = /[a-z]/u.test(text);
|
|
4689
|
+
const comparable = (names) => names.every((name) => wide.test(name) ? cardHasWide : !/[a-z]/iu.test(name) || cardHasLatin);
|
|
4631
4690
|
const named = (candidate) => {
|
|
4632
4691
|
return [candidate, candidate.replace(/\s*[((][^))]*[))]/gu, "").trim()].some((name) => folded(name).trim() !== "" && text.includes(folded(name).trim()));
|
|
4633
4692
|
};
|
|
4634
|
-
const checked = world.names.filter((thing) => !thing.playable && thing.names.length > 0);
|
|
4693
|
+
const checked = world.names.filter((thing) => !thing.playable && thing.names.length > 0 && comparable(thing.names));
|
|
4694
|
+
const elsewhere = world.names.filter((thing) => !thing.playable && thing.names.length > 0 && !comparable(thing.names)).length;
|
|
4635
4695
|
const missing = checked.filter((thing) => !thing.names.some(named));
|
|
4636
4696
|
if (checked.length >= MIN_NAMES_FOR_PATTERN && missing.length / checked.length > MOSTLY_MISSING) return foundBy("card-names", [{
|
|
4637
4697
|
severity: "info",
|
|
@@ -4640,6 +4700,13 @@ const names = {
|
|
|
4640
4700
|
message: `${missing.length} of ${checked.length} names do not occur in the card: the world is probably in another language than the card, or was made from another card`,
|
|
4641
4701
|
hint: "Compare by meaning instead; the judged checks do."
|
|
4642
4702
|
}]);
|
|
4703
|
+
if (elsewhere > 0 && missing.length === 0) return foundBy("card-names", [{
|
|
4704
|
+
severity: "info",
|
|
4705
|
+
code: "names-elsewhere",
|
|
4706
|
+
where: "(the world)",
|
|
4707
|
+
message: `${elsewhere} names are in another script than the card, so they cannot be looked for in it: the world is in another language than the card`,
|
|
4708
|
+
hint: "Compare by meaning instead; the judged checks do."
|
|
4709
|
+
}]);
|
|
4643
4710
|
return foundBy("card-names", missing.map((thing) => ({
|
|
4644
4711
|
severity: thing.kind === "items" ? "info" : "warning",
|
|
4645
4712
|
code: "name-not-in-card",
|
|
@@ -4809,7 +4876,7 @@ const fidelityChecks = [
|
|
|
4809
4876
|
const world = await loaded.text(input);
|
|
4810
4877
|
const made = await loaded.made(input, evidence, "about");
|
|
4811
4878
|
const from = /* @__PURE__ */ new Map();
|
|
4812
|
-
for (const piece of usedPieces(source)) for (const where of made.get(baseId(piece.id)) ?? []) from.set(where, [...from.get(where) ?? [], piece]);
|
|
4879
|
+
for (const piece of usedPieces(source)) for (const where of /* @__PURE__ */ new Set([...made.get(baseId(piece.id)) ?? [], ...rescuedFor(input, piece.id)])) from.set(where, [...from.get(where) ?? [], piece]);
|
|
4813
4880
|
const ranked = [...from].map(([where, pieces]) => ({
|
|
4814
4881
|
where,
|
|
4815
4882
|
pieces,
|
|
@@ -4994,17 +5061,20 @@ const VALUES_CLOSE = .55;
|
|
|
4994
5061
|
const THINGS_CLOSE = .6;
|
|
4995
5062
|
const LORE_CLOSE = .6;
|
|
4996
5063
|
const TEXT_CHARS = 1200;
|
|
4997
|
-
const yesNo = (key) => ({
|
|
5064
|
+
const yesNo = (key, meaning) => ({
|
|
4998
5065
|
type: "object",
|
|
4999
5066
|
properties: {
|
|
5000
5067
|
reason: { type: "string" },
|
|
5001
|
-
[key]: {
|
|
5068
|
+
[key]: {
|
|
5069
|
+
type: "boolean",
|
|
5070
|
+
description: meaning
|
|
5071
|
+
}
|
|
5002
5072
|
},
|
|
5003
5073
|
required: ["reason", key],
|
|
5004
5074
|
additionalProperties: false
|
|
5005
5075
|
});
|
|
5006
5076
|
/** The pairs a model says yes to, each with the reason the language model gave (the decision model gives none). */
|
|
5007
|
-
async function asked(model, pairs, prompt, key, extra = {}) {
|
|
5077
|
+
async function asked(model, pairs, prompt, key, meaning, extra = {}) {
|
|
5008
5078
|
const instructions = model.text(prompt);
|
|
5009
5079
|
return (await mapLimit(pairs, model.concurrency, async (pair) => {
|
|
5010
5080
|
if (model.cancelled?.() === true) return void 0;
|
|
@@ -5017,7 +5087,7 @@ async function asked(model, pairs, prompt, key, extra = {}) {
|
|
|
5017
5087
|
const answer = await model.run({
|
|
5018
5088
|
persona: instructions,
|
|
5019
5089
|
prompt: `A:\n${pair.first}\n\nB:\n${pair.second}`,
|
|
5020
|
-
result: yesNo(key),
|
|
5090
|
+
result: yesNo(key, meaning),
|
|
5021
5091
|
maxTokens: 500
|
|
5022
5092
|
});
|
|
5023
5093
|
reason = answer.reason;
|
|
@@ -5045,7 +5115,7 @@ const sameValue = {
|
|
|
5045
5115
|
near: entry,
|
|
5046
5116
|
first: valueText(defs[entry.a]),
|
|
5047
5117
|
second: valueText(defs[entry.b])
|
|
5048
|
-
})), "checks/decide-same-value", "same");
|
|
5118
|
+
})), "checks/decide-same-value", "same", "true only when A and B are one and the same value; false when they are different, or one is a kind, cause or part of the other");
|
|
5049
5119
|
return foundBy("duplicate-values-meaning", said.map(({ pair, reason }) => {
|
|
5050
5120
|
const a = defs[pair.near.a];
|
|
5051
5121
|
const b = defs[pair.near.b];
|
|
@@ -5089,13 +5159,22 @@ const nearNames = {
|
|
|
5089
5159
|
b,
|
|
5090
5160
|
score: 1
|
|
5091
5161
|
});
|
|
5092
|
-
const byMeaning =
|
|
5162
|
+
const byMeaning = [];
|
|
5163
|
+
for (const kind of new Set(things.map((thing) => thing.kind))) {
|
|
5164
|
+
const members = things.flatMap((thing, at) => thing.kind === kind ? [at] : []);
|
|
5165
|
+
const own = await candidates(model, input.world.directory, members.map((at) => things[at].text), (a, b) => sameKind(members[a], members[b]), THINGS_CLOSE, PAIRS_ASKED);
|
|
5166
|
+
byMeaning.push(...(own ?? []).map((entry) => ({
|
|
5167
|
+
...entry,
|
|
5168
|
+
a: members[entry.a],
|
|
5169
|
+
b: members[entry.b]
|
|
5170
|
+
})));
|
|
5171
|
+
}
|
|
5093
5172
|
const seen = new Set(byName.map((entry) => `${entry.a}:${entry.b}`));
|
|
5094
|
-
const said = await asked(model, [...byName, ...byMeaning.filter((entry) => !seen.has(`${entry.a}:${entry.b}`))].
|
|
5173
|
+
const said = await asked(model, [...byName, ...byMeaning.filter((entry) => !seen.has(`${entry.a}:${entry.b}`))].map((entry) => ({
|
|
5095
5174
|
near: entry,
|
|
5096
5175
|
first: `${things[entry.a].kind} ${things[entry.a].text}`,
|
|
5097
5176
|
second: `${things[entry.b].kind} ${things[entry.b].text}`
|
|
5098
|
-
})), "checks/decide-same-thing", "same");
|
|
5177
|
+
})), "checks/decide-same-thing", "same", "true only when A and B are one and the same entry written twice; false when they are different, or one is a part of the other");
|
|
5099
5178
|
return foundBy("name-near", said.map(({ pair, reason }) => {
|
|
5100
5179
|
const a = things[pair.near.a];
|
|
5101
5180
|
const b = things[pair.near.b];
|
|
@@ -5162,10 +5241,15 @@ const semanticChecks = [
|
|
|
5162
5241
|
first: `entry ${lore[entry.a].id}:\n${loreText(lore[entry.a])}`,
|
|
5163
5242
|
second: `entry ${lore[entry.b].id}:\n${loreText(lore[entry.b])}`
|
|
5164
5243
|
}));
|
|
5165
|
-
const
|
|
5244
|
+
const screening = model.text("checks/decide-conflict");
|
|
5245
|
+
const kept = await mapLimit(pairs, model.concurrency, async (pair) => model.cancelled?.() === true ? false : worthReading(model, {
|
|
5246
|
+
first: pair.first,
|
|
5247
|
+
second: pair.second
|
|
5248
|
+
}, "conflict", screening));
|
|
5249
|
+
const screened = pairs.filter((_, at) => kept[at]);
|
|
5166
5250
|
const instructions = model.text("checks/conflict");
|
|
5167
5251
|
const found = [];
|
|
5168
|
-
await mapLimit(screened
|
|
5252
|
+
await mapLimit(screened, model.concurrency, async (pair) => {
|
|
5169
5253
|
if (model.cancelled?.() === true) return;
|
|
5170
5254
|
const first = loreText(lore[pair.near.a]);
|
|
5171
5255
|
const second = loreText(lore[pair.near.b]);
|
|
@@ -5196,8 +5280,10 @@ const semanticChecks = [
|
|
|
5196
5280
|
}
|
|
5197
5281
|
];
|
|
5198
5282
|
// src/host/checks/quality.ts
|
|
5199
|
-
/** A place described in fewer
|
|
5283
|
+
/** A place described in fewer letters than this has nothing to play with (a Chinese, Japanese or Korean character counts as three: it says as much as a short word). */
|
|
5200
5284
|
const THIN_PLACE = 20;
|
|
5285
|
+
const WIDE = /[\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]/gu;
|
|
5286
|
+
const lettersOf = (value) => value.length + 2 * (value.match(WIDE)?.length ?? 0);
|
|
5201
5287
|
const SHEET_CHARS = 3e3;
|
|
5202
5288
|
const DIGEST_CHARS = 7e3;
|
|
5203
5289
|
const GAPS_LISTED = 8;
|
|
@@ -5261,7 +5347,7 @@ const places = {
|
|
|
5261
5347
|
async run(input) {
|
|
5262
5348
|
const { locations } = await loaded.locations(input);
|
|
5263
5349
|
return foundBy("quality-places", locations.flatMap((place) => {
|
|
5264
|
-
const length = text(place.description)
|
|
5350
|
+
const length = lettersOf(text(place.description));
|
|
5265
5351
|
if (length === 0) return [{
|
|
5266
5352
|
severity: "warning",
|
|
5267
5353
|
code: "place-undescribed",
|
|
@@ -6201,6 +6287,6 @@ function limitAuthoringAgents(ctx, kindOf) {
|
|
|
6201
6287
|
return await next();
|
|
6202
6288
|
});
|
|
6203
6289
|
}
|
|
6204
|
-
export {
|
|
6290
|
+
export { parseWorldFile as $, pictureOf as $t, entitiesByPiece as A, routineProblems as At, readOrigin as B, loadFactions as Bt, readWorldInfo as C, populateItems as Ct, baseId as D, populateRoutines as Dt, UPDATE_FOLDER as E, populateLore as Et, writeSnapshot as F, LOCATIONS_DIR as Ft, candidateUrls as G, loadCalendar as Gt, CatalogueError as H, loadDice as Ht, describeChanges as I, loadLocations as It, mergeReports as J, loadCharacters as Jt, fetchPictures as K, parseCalendarFile as Kt, hashWorld as L, ITEMS_DIR as Lt, CHECK_COMMANDS as M, loadTriggers as Mt, recordProvenance as N, LORE_DIR as Nt, cardPieces as O, populateTriggers as Ot, editsSince as P, loadLore as Pt, WORLD_FILE_NAME as Q, isPng as Qt, isUnchanged as R, loadItems as Rt, editWorldInfo as S, populateFactions as St, loadCardEvidence as T, populateLocations as Tt, addressKey as U, parseDiceFile as Ut, writeOrigin as V, DICE_FILE_NAME as Vt, addressesToFetch as W, CALENDAR_FILE_NAME as Wt, cardCharacter as X, knownOutputCeiling as Xt, vetUrl as Y, subfolders as Yt, writePortrait as Z, ImportCardError as Zt, runChecks as _, knowsCharacter as _t, importHooks as a, authoringChatSessionId as an, entriesOf as at, matchPieces as b, populateClock as bt, importPhase as c, loadLorebook as ct, markReady as d, reserveLorebook as dt, readCard as en, parseWorldInfoEdit as et, settleDraft as f, updateLorebookInfo as ft, CHECKS as g, withScratchStory as gt, presentReport as h, loadValidatedWorld as ht, contextOf as i, authoredWorldOf as in, deleteLorebookEntry as it, readSource as j, TRIGGERS_FILE_NAME as jt, cardTools as k, populateVariables as kt, isReviewing as l, lorebookDirectory as lt, checkImported as m, checkWorld as mt, limitAuthoringAgents as n, DICE_READINGS as nn, createLorebook as nt, importTools as o, isLorebookName as ot, structureImport as p, writeLorebookEntry as pt, guardedLookup as q, CHARACTERS_DIR as qt, MAX_PREVIEW_TEXT as r, DICE_RESULTS as rn, deleteLorebook as rt, worldOf as s, listLorebooks as st, AuthoringTools as t, DICE_COMPARISONS as tn, addLorebookEntries as tt, keepDraft as u, readLorebook as ut, cardChanges as v, populateCalendar as vt, loadWorldParts as w, populateKnowledge as wt, worldFieldChanges as x, populateDice as xt, diffText as y, populateCharacters as yt, localChanges as z, FACTIONS_DIR as zt };
|
|
6205
6291
|
|
|
6206
|
-
//# sourceMappingURL=authoring-tools-
|
|
6292
|
+
//# sourceMappingURL=authoring-tools-B4mEdKp_.js.map
|
package/lib/authoring.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { t as guardAuthoringTurns } from "./turn-guard-
|
|
3
|
-
import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation, z as translateTools } from "./pack-jail-
|
|
4
|
-
import { Dt as InvalidEditProblems, G as listWorldPrompts, K as readWorldPrompt, Mt as parseRelationEdit, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, ct as parseAuthoringCommand, q as writeWorldPrompt } from "./presets-
|
|
1
|
+
import { A as entitiesByPiece, C as readWorldInfo, M as CHECK_COMMANDS, P as editsSince, S as editWorldInfo, T as loadCardEvidence, _ as runChecks, a as importHooks, b as matchPieces, et as parseWorldInfoEdit, g as CHECKS, h as presentReport, i as contextOf, in as authoredWorldOf, j as readSource, k as cardTools, l as isReviewing, m as checkImported, mt as checkWorld, n as limitAuthoringAgents, o as importTools, v as cardChanges, w as loadWorldParts, x as worldFieldChanges, y as diffText } from "./authoring-tools-B4mEdKp_.js";
|
|
2
|
+
import { t as guardAuthoringTurns } from "./turn-guard-BzNeGNnc.js";
|
|
3
|
+
import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation, z as translateTools } from "./pack-jail-hsNQNTOf.js";
|
|
4
|
+
import { Dt as InvalidEditProblems, G as listWorldPrompts, K as readWorldPrompt, Mt as parseRelationEdit, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, ct as parseAuthoringCommand, q as writeWorldPrompt } from "./presets-CvpsW_10.js";
|
|
5
5
|
import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
|
|
6
|
-
import {
|
|
7
|
-
import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-
|
|
8
|
-
import "./access-
|
|
6
|
+
import { H as parsePlotsFile, Y as formatIssue, ot as shippedPromptsDirectory } from "./hooks-DTjHWTfx.js";
|
|
7
|
+
import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-UpK_cvI4.js";
|
|
8
|
+
import "./access-CXtaZNbx.js";
|
|
9
9
|
import { join, relative } from "node:path";
|
|
10
10
|
import { readFile, readdir } from "node:fs/promises";
|
|
11
11
|
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
@@ -43,11 +43,15 @@ const NO_TOKENS = {
|
|
|
43
43
|
cached: 0,
|
|
44
44
|
output: 0
|
|
45
45
|
};
|
|
46
|
-
const addTokens = (a, b) =>
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
46
|
+
const addTokens = (a, b) => {
|
|
47
|
+
const unreported = (a.unreported ?? 0) + (b.unreported ?? 0);
|
|
48
|
+
return {
|
|
49
|
+
input: a.input + b.input,
|
|
50
|
+
cached: a.cached + b.cached,
|
|
51
|
+
output: a.output + b.output,
|
|
52
|
+
...unreported > 0 ? { unreported } : {}
|
|
53
|
+
};
|
|
54
|
+
};
|
|
51
55
|
// src/host/agents/usage.ts
|
|
52
56
|
/** The tokens the model service reported for the requests it answered in a session's events; a request it reported nothing for adds nothing. */
|
|
53
57
|
function tokensOf(events) {
|
|
@@ -59,11 +63,104 @@ function tokensOf(events) {
|
|
|
59
63
|
total = addTokens(total, {
|
|
60
64
|
input: usage.inputTokens,
|
|
61
65
|
cached: usage.cacheReadTokens ?? 0,
|
|
62
|
-
output: usage.outputTokens
|
|
66
|
+
output: usage.outputTokens,
|
|
67
|
+
...usage.cacheReadTokens === void 0 ? { unreported: usage.inputTokens } : {}
|
|
63
68
|
});
|
|
64
69
|
}
|
|
65
70
|
return total;
|
|
66
71
|
}
|
|
72
|
+
// src/host/diagnostics/estimate.ts
|
|
73
|
+
const WIDE = /[ -鿿가--]/gu;
|
|
74
|
+
/** What a text costs in tokens, roughly: a token holds about four letters of a western script and less than one character of a Chinese, Japanese or Korean one. Only for telling the parts of a prompt apart; the service's own count is what is reported for the whole. */
|
|
75
|
+
function estimateTokens(text) {
|
|
76
|
+
if (text === "") return 0;
|
|
77
|
+
const wide = text.match(WIDE)?.length ?? 0;
|
|
78
|
+
return Math.ceil((text.length - wide) / 4 + wide * .7);
|
|
79
|
+
}
|
|
80
|
+
/** The text a block of a model message puts in the prompt. */
|
|
81
|
+
function blockText(block) {
|
|
82
|
+
if (typeof block !== "object" || block === null) return "";
|
|
83
|
+
const entry = block;
|
|
84
|
+
if (typeof entry.text === "string") return entry.text;
|
|
85
|
+
if (entry.type === "tool-call") return `${typeof entry.name === "string" ? entry.name : ""}${typeof entry.arguments === "string" ? entry.arguments : JSON.stringify(entry.arguments ?? "")}`;
|
|
86
|
+
if (entry.type === "image") return "";
|
|
87
|
+
return JSON.stringify(block);
|
|
88
|
+
}
|
|
89
|
+
/** The tokens of the content of one message of the log. */
|
|
90
|
+
function messageTokens(message) {
|
|
91
|
+
const content = message?.content;
|
|
92
|
+
if (typeof content === "string") return estimateTokens(content);
|
|
93
|
+
return Array.isArray(content) ? content.reduce((sum, block) => sum + estimateTokens(blockText(block)), 0) : 0;
|
|
94
|
+
}
|
|
95
|
+
// src/host/agents/requests.ts
|
|
96
|
+
/** What a request's prompt was made of: the parts the log shows, and whatever else the service counted (the earlier turns of the conversation). */
|
|
97
|
+
function parts(held, prompt) {
|
|
98
|
+
const known = Object.keys(held).filter((id) => held[id] > 0).map((id) => ({
|
|
99
|
+
id,
|
|
100
|
+
tokens: held[id]
|
|
101
|
+
}));
|
|
102
|
+
const rest = prompt === void 0 ? 0 : prompt - known.reduce((sum, part) => sum + part.tokens, 0);
|
|
103
|
+
const all = rest > 0 ? [...known, {
|
|
104
|
+
id: "earlier",
|
|
105
|
+
tokens: rest
|
|
106
|
+
}] : known;
|
|
107
|
+
return all.length === 0 ? {} : { parts: all };
|
|
108
|
+
}
|
|
109
|
+
const KEEP_WAITING = /* @__PURE__ */ new Set([
|
|
110
|
+
"block-start",
|
|
111
|
+
"text-delta",
|
|
112
|
+
"reasoning-delta"
|
|
113
|
+
]);
|
|
114
|
+
/**
|
|
115
|
+
* The requests a session's events record, in order. The wait is measured from the start of the step to the first block the model opened;
|
|
116
|
+
* whatever DSH took to assemble the request is in it, which is small beside a model's own time to read the prompt.
|
|
117
|
+
*/
|
|
118
|
+
function requestsOf(events) {
|
|
119
|
+
const stats = [];
|
|
120
|
+
const began = /* @__PURE__ */ new Map();
|
|
121
|
+
const held = {
|
|
122
|
+
system: 0,
|
|
123
|
+
tools: 0,
|
|
124
|
+
notices: 0,
|
|
125
|
+
input: 0,
|
|
126
|
+
steps: 0
|
|
127
|
+
};
|
|
128
|
+
for (const event of events) {
|
|
129
|
+
const data = event.data;
|
|
130
|
+
const key = `${data?.turn ?? 0}:${data?.step ?? 0}`;
|
|
131
|
+
if (event.type === "step/start" && event.time !== void 0) began.set(key, event.time);
|
|
132
|
+
if (event.type === "turn/start") held.notices = held.input = held.steps = 0;
|
|
133
|
+
if (event.type === "system/message") held.system = messageTokens(data?.message);
|
|
134
|
+
if (event.type === "request/header") held.tools = estimateTokens(JSON.stringify(data?.header?.tools ?? []));
|
|
135
|
+
if (event.type === "user/message") held[data?.source?.kind === "roleplay" ? "notices" : "input"] += messageTokens(data);
|
|
136
|
+
if (event.type === "tool/result") held.steps += messageTokens(data?.message);
|
|
137
|
+
if (event.type !== "assistant/message") continue;
|
|
138
|
+
const sent = { ...held };
|
|
139
|
+
if (data?.message !== void 0) held.steps += messageTokens(data.message);
|
|
140
|
+
if (data?.stream === void 0 || stats.length >= 40) continue;
|
|
141
|
+
const start = began.get(key);
|
|
142
|
+
const chunks = data.stream.flatMap((entry) => entry.chunk === void 0 ? [] : [{
|
|
143
|
+
time: entry.time,
|
|
144
|
+
chunk: entry.chunk
|
|
145
|
+
}]);
|
|
146
|
+
const usage = chunks.findLast((entry) => entry.chunk.type === "usage")?.chunk.usage ?? data.usage;
|
|
147
|
+
const first = chunks.find((entry) => KEEP_WAITING.has(entry.chunk.type))?.time;
|
|
148
|
+
const stop = chunks.findLast((entry) => entry.chunk.type === "finish")?.chunk.reason?.kind ?? "stop";
|
|
149
|
+
const cached = usage?.cacheReadTokens;
|
|
150
|
+
const prompt = usage?.inputTokens === void 0 ? void 0 : usage.inputTokens + (cached ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
151
|
+
stats.push({
|
|
152
|
+
step: data.step ?? 0,
|
|
153
|
+
...prompt === void 0 ? {} : { prompt },
|
|
154
|
+
...usage?.outputTokens === void 0 ? {} : { output: usage.outputTokens },
|
|
155
|
+
...cached === void 0 ? {} : { cached },
|
|
156
|
+
...start === void 0 || first === void 0 ? {} : { waitMs: Math.max(0, first - start) },
|
|
157
|
+
...start === void 0 || event.time === void 0 ? {} : { ms: Math.max(0, event.time - start) },
|
|
158
|
+
stop,
|
|
159
|
+
...parts(sent, prompt)
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return stats;
|
|
163
|
+
}
|
|
67
164
|
// src/shared/activity.ts
|
|
68
165
|
/** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
|
|
69
166
|
const MAX_RUN_TEXT = 4e3;
|
|
@@ -187,8 +284,10 @@ function childTrace(store, kind, label, extra = {}, named) {
|
|
|
187
284
|
model,
|
|
188
285
|
ms: run.ms,
|
|
189
286
|
calls: run.calls,
|
|
287
|
+
...run.detail.calls.some((call) => call.failed) ? { refused: run.detail.calls.filter((call) => call.failed).length } : {},
|
|
190
288
|
turn: run.turn,
|
|
191
289
|
tokens: run.tokens,
|
|
290
|
+
...(run.requests ?? []).length === 0 ? {} : { requests: run.requests },
|
|
192
291
|
...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
|
|
193
292
|
...id === void 0 ? {} : { run: id }
|
|
194
293
|
}, keep ? {
|
|
@@ -273,7 +372,8 @@ async function runChild(task) {
|
|
|
273
372
|
calls: stats.calls,
|
|
274
373
|
detail: detail(),
|
|
275
374
|
turn: currentTurn(task.parent),
|
|
276
|
-
tokens: stats.tokens ?? NO_TOKENS
|
|
375
|
+
tokens: stats.tokens ?? NO_TOKENS,
|
|
376
|
+
requests: stats.requests ?? []
|
|
277
377
|
});
|
|
278
378
|
return result;
|
|
279
379
|
} catch (cause) {
|
|
@@ -284,7 +384,8 @@ async function runChild(task) {
|
|
|
284
384
|
error: error instanceof Error ? error.message : String(error),
|
|
285
385
|
detail: detail(),
|
|
286
386
|
turn: currentTurn(task.parent),
|
|
287
|
-
tokens: stats.tokens ?? NO_TOKENS
|
|
387
|
+
tokens: stats.tokens ?? NO_TOKENS,
|
|
388
|
+
requests: stats.requests ?? []
|
|
288
389
|
});
|
|
289
390
|
if (attempt >= 2 || task.signal.aborted || error instanceof ChildTimeoutError || !isUnfinishedCall(error)) throw error;
|
|
290
391
|
} finally {
|
|
@@ -631,7 +732,11 @@ async function execute(task, stats) {
|
|
|
631
732
|
} catch (error) {
|
|
632
733
|
if (submitted === void 0 && !overran && !signal.aborted) throw error;
|
|
633
734
|
} finally {
|
|
634
|
-
if (entry.agent !== void 0)
|
|
735
|
+
if (entry.agent !== void 0) {
|
|
736
|
+
const events = entry.agent.session.snapshotEvents();
|
|
737
|
+
stats.tokens = tokensOf(events);
|
|
738
|
+
stats.requests = requestsOf(events);
|
|
739
|
+
}
|
|
635
740
|
await (overran ? Promise.race([activation.dispose(), new Promise((resolve) => {
|
|
636
741
|
setTimeout(resolve, STOP_GRACE_MS);
|
|
637
742
|
})]) : activation.dispose());
|
|
@@ -651,6 +756,6 @@ async function execute(task, stats) {
|
|
|
651
756
|
}
|
|
652
757
|
return submitted.value;
|
|
653
758
|
}
|
|
654
|
-
export {
|
|
759
|
+
export { tokensOf$1 as S, addTokens as _, childTrace as a, finishOf as b, runChild as c, sharedSamplingOf as d, requestsOf as f, NO_TOKENS as g, tokensOf as h, childSamplingOf as i, SAMPLING_RANGES as l, estimateTokens as m, childModel as n, helpers as o, blockText as p, childSampling as r, namedModel as s, ChildTimeoutError as t, parseSampling as u, currentTurn as v, estimateAnswer as x, cutOff as y };
|
|
655
760
|
|
|
656
|
-
//# sourceMappingURL=child-
|
|
761
|
+
//# sourceMappingURL=child-Dtv76jNx.js.map
|