@dsh-agentic-roleplay/core 0.1.1 → 0.2.1

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.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/lib/{activity-BbqFG9-3.js → activity-t7OBgHlc.js} +255 -61
  3. package/lib/authoring.js +295 -14
  4. package/lib/client.js +1896 -453
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/{documents-ZVoUTnD2.js → documents-Bu5uYRZB.js} +3 -3
  8. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  9. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +638 -14
  12. package/lib/{narration-DcnCqA1l.js → narration-BRyHU0H2.js} +10 -4
  13. package/lib/orchestration.js +303 -161
  14. package/lib/packs-ByP1J-zj.js +1334 -0
  15. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-G43ODV8I.js} +3 -3
  16. package/package.json +4 -3
  17. package/prompts/en/roleplay/ask-answerer.md +3 -0
  18. package/prompts/en/roleplay/ask-question.md +2 -0
  19. package/prompts/en/roleplay/character-decide.md +1 -1
  20. package/prompts/en/roleplay/character-lookup.md +1 -1
  21. package/prompts/en/roleplay/game-master.md +5 -1
  22. package/prompts/en/roleplay/ooc-empty.md +1 -1
  23. package/prompts/en/world/procedure.md +1 -1
  24. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  25. package/prompts/zh/roleplay/ask-question.md +2 -0
  26. package/prompts/zh/roleplay/character-decide.md +1 -1
  27. package/prompts/zh/roleplay/character-lookup.md +1 -1
  28. package/prompts/zh/roleplay/game-master.md +5 -1
  29. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  30. package/prompts/zh/world/procedure.md +1 -1
  31. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  32. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  33. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  34. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  35. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  36. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  37. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  38. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  39. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  40. package/lib/worlds-DYgjdH8O.js +0 -504
package/lib/authoring.js CHANGED
@@ -1,18 +1,19 @@
1
- import { C as endReview, E as isReviewing, J as listWorldPrompts, K as PROSE_PROMPTS, O as survey, S as build, T as importPhase, X as writeWorldPrompt, Y as readWorldPrompt, _t as parseImportCommand, a as replaceAuthoredEntity, b as authoredWorldOf, d as editWorldPlots, f as editWorldRelation, g as readWorldEditor, i as readAuthoredEntityDocument, lt as InvalidEditProblems, mt as parseRelationEdit, n as createAuthoredEntity, nt as IMPORT_FOLDER, q as deleteWorldPrompt, r as deleteAuthoredEntity, t as AUTHORED_ENTITY_KINDS, w as finish } from "./documents-ZVoUTnD2.js";
2
- import { i as parsePlotsFile, l as formatIssue, v as shippedPromptsDirectory } from "./worlds-DYgjdH8O.js";
3
- import { A as runChild } from "./generator-NYnNdpWb.js";
4
- import { join } from "node:path";
1
+ import { C as endReview, E as isReviewing, J as listWorldPrompts, K as PROSE_PROMPTS, O as survey, S as build, T as importPhase, X as writeWorldPrompt, Y as readWorldPrompt, _t as parseImportCommand, a as replaceAuthoredEntity, b as authoredWorldOf, d as editWorldPlots, f as editWorldRelation, g as readWorldEditor, i as readAuthoredEntityDocument, lt as InvalidEditProblems, mt as parseRelationEdit, n as createAuthoredEntity, nt as IMPORT_FOLDER, q as deleteWorldPrompt, r as deleteAuthoredEntity, t as AUTHORED_ENTITY_KINDS, w as finish } from "./documents-Bu5uYRZB.js";
2
+ import { P as shippedPromptsDirectory, T as formatIssue, a as packIds, b as parsePlotsFile, d as packPath, f as readPack, g as SURFACE_NAMES, h as PACK_MEDIA_TYPES, l as isPackId, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-ByP1J-zj.js";
3
+ import { A as runChild } from "./generator-HPifO3Kk.js";
4
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { existsSync, lstatSync } from "node:fs";
5
6
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
6
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
7
- import { readFile } from "node:fs/promises";
8
+ import { mkdir, readFile, rename } from "node:fs/promises";
8
9
  //#region src/host/authoring/read-tools.ts
9
- const output$3 = (value) => [{
10
+ const output$4 = (value) => [{
10
11
  type: "text",
11
12
  text: JSON.stringify(value, null, 2)
12
13
  }];
13
- const jsonOutput$2 = {
14
+ const jsonOutput$3 = {
14
15
  schema: { type: "json" },
15
- render: (_args, value) => output$3(value)
16
+ render: (_args, value) => output$4(value)
16
17
  };
17
18
  const keyParameter$1 = {
18
19
  type: "string",
@@ -46,7 +47,7 @@ function listTool(reader, name, description, select, summarize) {
46
47
  name,
47
48
  description,
48
49
  parameters: {},
49
- output: jsonOutput$2,
50
+ output: jsonOutput$3,
50
51
  isConcurrencySafe: () => true,
51
52
  async execute(_args, exec) {
52
53
  return json$1(select((await reader.read(exec)).state).map(summarize));
@@ -58,7 +59,7 @@ function getTool(reader, name, description, select) {
58
59
  name,
59
60
  description,
60
61
  parameters: { key: keyParameter$1 },
61
- output: jsonOutput$2,
62
+ output: jsonOutput$3,
62
63
  isConcurrencySafe: () => true,
63
64
  async execute(args, exec) {
64
65
  const found = select((await reader.read(exec)).state).find((entry) => entry.key === args.key);
@@ -74,7 +75,7 @@ function authoredWorldReadTools(reader) {
74
75
  name: "get_world_overview",
75
76
  description: "Read the authored world’s top-level identity, description, rules, opening, tags, author and element counts.",
76
77
  parameters: {},
77
- output: jsonOutput$2,
78
+ output: jsonOutput$3,
78
79
  isConcurrencySafe: () => true,
79
80
  async execute(_args, exec) {
80
81
  const { record, state } = await reader.read(exec);
@@ -154,7 +155,7 @@ function authoredWorldReadTools(reader) {
154
155
  },
155
156
  key: keyParameter$1
156
157
  },
157
- output: jsonOutput$2,
158
+ output: jsonOutput$3,
158
159
  isConcurrencySafe: () => true,
159
160
  async execute(args, exec) {
160
161
  const { record } = await reader.read(exec);
@@ -197,7 +198,7 @@ function authoredWorldReadTools(reader) {
197
198
  description: "Only edges whose target has this stable key."
198
199
  }
199
200
  },
200
- output: jsonOutput$2,
201
+ output: jsonOutput$3,
201
202
  isConcurrencySafe: () => true,
202
203
  async execute(args, exec) {
203
204
  return json$1((await reader.read(exec)).state.relations.filter((relation) => (args.kind === void 0 || relation.kind === args.kind) && (args.from === void 0 || relation.from.key === args.from) && (args.to === void 0 || relation.to.key === args.to)));
@@ -206,6 +207,168 @@ function authoredWorldReadTools(reader) {
206
207
  ];
207
208
  }
208
209
  //#endregion
210
+ //#region src/host/interface/world-packs.ts
211
+ /** The kinds of file an assistant may write, as text. */
212
+ const TEXT_EXTENSIONS = [
213
+ "html",
214
+ "css",
215
+ "js",
216
+ "json",
217
+ "txt",
218
+ "svg"
219
+ ];
220
+ const folderOf = (directory, pack) => join(directory, "ui", pack);
221
+ function checked(directory, pack) {
222
+ if (!isPackId(pack)) throw new Error(`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`);
223
+ return folderOf(directory, pack);
224
+ }
225
+ /** What every pack the world carries holds and what is wrong with it. */
226
+ function listWorldPacks(directory) {
227
+ return packIds(directory).map((id) => {
228
+ const { pack, problems } = readPack(folderOf(directory, id), id, (file) => file);
229
+ const files = pack === void 0 ? [] : [...pack.files.keys()];
230
+ return {
231
+ id,
232
+ name: pack?.manifest.name ?? id,
233
+ problems,
234
+ files
235
+ };
236
+ });
237
+ }
238
+ /** What is wrong with a pack (nothing when it can be used). */
239
+ function checkWorldPack(directory, pack) {
240
+ const folder = checked(directory, pack);
241
+ if (!existsSync(folder)) throw new Error(`the world carries no pack "${pack}"`);
242
+ return readPack(folder, pack, (file) => file).problems;
243
+ }
244
+ /** Moves a file of a pack into the world's `.trash`. @returns where it went, and what is wrong with the pack now. */
245
+ async function deleteWorldPackFile(directory, pack, path) {
246
+ const relative = packPath(path);
247
+ if (relative === void 0 || !(extname(relative).slice(1).toLowerCase() in PACK_MEDIA_TYPES)) throw new Error(`"${path}" is not a file of a pack`);
248
+ const folder = checked(directory, pack);
249
+ const file = join(folder, ...relative.split("/"));
250
+ if (!existsSync(file)) throw new Error(`the pack "${pack}" has no file "${path}"`);
251
+ const aside = join(directory, ".trash", "ui", pack, `${relative.replaceAll("/", "__")}.${Date.now()}`);
252
+ await mkdir(dirname(aside), { recursive: true });
253
+ await rename(file, aside);
254
+ return {
255
+ trashPath: aside,
256
+ problems: existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (address) => address).problems : [{
257
+ file: "pack.json",
258
+ message: "the pack has no pack.json"
259
+ }]
260
+ };
261
+ }
262
+ //#endregion
263
+ //#region src/host/authoring/pack-tools.ts
264
+ const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
265
+ const output$3 = (value) => [{
266
+ type: "text",
267
+ text: JSON.stringify(value, null, 2)
268
+ }];
269
+ const jsonOutput$2 = {
270
+ schema: { type: "json" },
271
+ render: (_args, value) => output$3(value)
272
+ };
273
+ /** A path as the file tools take it: relative to the chat's folder when it has one, which is short and hard to mistype. */
274
+ function relativeTo(exec, path) {
275
+ const cwd = exec.agent?.session.header.cwd;
276
+ return cwd === void 0 ? path : relative(cwd, path);
277
+ }
278
+ const packParameter = {
279
+ type: "string",
280
+ required: true,
281
+ description: "The pack name (its folder under ui/), such as atlas."
282
+ };
283
+ const pathParameter = {
284
+ type: "string",
285
+ required: true,
286
+ description: "A path inside the pack with \"/\", such as pack.json or img/map.svg."
287
+ };
288
+ /** What an assistant needs to write a pack; the same facts the author docs give a person. */
289
+ const PACK_GUIDE = `Write and read the files of a pack with the file tools write, edit and read, at the path <world folder>/ui/<pack>/<file>. Use the short relative path given with this guide (such as my-world/ui/atlas/pack.json), not the long absolute one, which is easy to mistype; in this chat they reach nothing else, only text files, and every change asks the person first. Delete a file with delete_world_pack_file.
290
+
291
+ An interface pack changes how a story looks and adds small pieces of interface. It is a folder ui/<pack>/ of the world with a pack.json and the files it names. Sessions started from the world copy it; a pack with problems stops the session from starting, so check it with check_world_pack after writing.
292
+
293
+ pack.json (api 1): { "name", "version", "description", "api": 1, "theme": { "--dsw-alias-<token>": { "light": "#...", "dark": "#..." } }, "skin": "skin.css", "actions": [${PACK_ACTIONS.map((action) => `"${action}"`).join(", ")}], "surfaces": { "hud": { "file": "hud.html", "height": 48 }, "tab": { "file": "map.html", "title": "Map" } } }. Surfaces: ${SURFACE_NAMES.join(", ")} (hud is a strip above the input box and its controls, dock a strip just above the input box for buttons, opening a card shown only until the first turn is played, backdrop a layer behind the story's text that takes no clicks, tab a page beside Chat, sidebar a page of any size in the right sidebar with a Back button above it; the strips hud, dock and opening ask for their height with rp.resize). actions lists what the pages may do for the player: say (send words as the player), fill (put words in the input box), choose (take a suggested action as the input), open (show the pack's tab or sidebar page); leave out what is not needed.
294
+
295
+ skin.css restyles the story's own elements and nothing else: every part of every selector must name one with [data-rp="..."], and url() may point only to files of the pack. Elements: narration (a turn), prose (a narration paragraph), utterance (a spoken line) with avatar, speaker and words inside, ooc, suggestions and suggestion, turns, and the frames hud, dock, opening and backdrop. Only style rules, @media, @supports, @keyframes and @font-face are allowed; no @import, nesting or escapes outside strings.
296
+
297
+ A surface is an HTML file with its own css and js files beside it (relative addresses). It runs in a sandbox: no cookies, storage or access to the page, and no network except fetching the pack's own files; workers, WebAssembly, canvas and WebGL work. The page gives it an rp object: rp.state() (a promise of the player view: use await or .then) and rp.watch(fn) (calls fn(view) at once and after every change; the usual way to draw a surface). The view is story {name, turn}, player {key, name, summary, publicState}, place {key, name, description, features, exits [{name, open}], items [{name, quantity}], here [{key, name, publicState}]}, time {iso, zone, text}, carried [{name, quantity, where}], variables [{subject, name, value}], map {places [{key, name, parent?, here}], routes [{from, to}]}, suggestions []), rp.on('turn' | 'suggestions' | 'theme', fn), rp.say(text), rp.fill(text), rp.choose(index), rp.open('tab' | 'sidebar'), rp.history(n) (the last turns as the story stands: {turn, player, segments [{type, name?, text}], note?}), rp.storage.get/set/remove (JSON, 64 KB), rp.resize(height) (24 to 320; the opening card 120 to 640), rp.theme(). The frame has the DSH colours as CSS variables such as var(--dsw-alias-label-primary), var(--dsw-alias-bg-layer-1), var(--dsw-alias-border-l3), var(--dsw-alias-brand-primary); use them so the page fits light and dark.
298
+
299
+ Limits: ${PACK_LIMITS.files} files, ${PACK_LIMITS.bytes / 1024 / 1024} MB, ${PACK_LIMITS.fileBytes / 1024} KB per file, ${PACK_LIMITS.depth} folders deep; names use letters, digits, "-", "_" and "."; only text files (html, css, js, json, txt, svg) can be written; pictures and fonts are added by hand.`;
300
+ /**
301
+ * Read, write and check the interface packs a world carries. The files are the ones session start copies,
302
+ * so they are checked as it checks them.
303
+ */
304
+ function worldPackTools(reader) {
305
+ return [
306
+ defineTool({
307
+ name: "world_pack_guide",
308
+ description: "How to write an interface pack: where its files go (the folder is returned with the guide), the manifest, the skin, the surfaces, the rp object a surface gets, what it is told, and the limits. Read it before writing a pack.",
309
+ parameters: {},
310
+ output: jsonOutput$2,
311
+ isConcurrencySafe: () => true,
312
+ async execute(_args, exec) {
313
+ const { record } = await reader.read(exec);
314
+ return {
315
+ folder: join(record.directory, "ui"),
316
+ relative: relativeTo(exec, join(record.directory, "ui")),
317
+ guide: PACK_GUIDE
318
+ };
319
+ }
320
+ }),
321
+ defineTool({
322
+ name: "list_world_packs",
323
+ description: "List the interface packs the world carries, their files and what is wrong with each. Each pack has a path: the folder its files go in, as the file tools take it.",
324
+ parameters: {},
325
+ output: jsonOutput$2,
326
+ isConcurrencySafe: () => true,
327
+ async execute(_args, exec) {
328
+ const { record } = await reader.read(exec);
329
+ return listWorldPacks(record.directory).map((entry) => ({
330
+ ...entry,
331
+ path: relativeTo(exec, join(record.directory, "ui", entry.id))
332
+ }));
333
+ }
334
+ }),
335
+ defineTool({
336
+ name: "check_world_pack",
337
+ description: "Check a pack of this world as session start will: the manifest, the theme, the skin, the surfaces and every file. An empty list of problems means it can be used.",
338
+ parameters: { pack: packParameter },
339
+ output: jsonOutput$2,
340
+ isConcurrencySafe: () => true,
341
+ async execute(args, exec) {
342
+ const { record } = await reader.read(exec);
343
+ return {
344
+ pack: args.pack,
345
+ problems: checkWorldPack(record.directory, args.pack)
346
+ };
347
+ }
348
+ }),
349
+ defineTool({
350
+ name: "delete_world_pack_file",
351
+ description: "Remove a file of a pack of this world; it is moved into the world's .trash directory. Requires user approval.",
352
+ parameters: {
353
+ pack: packParameter,
354
+ path: pathParameter
355
+ },
356
+ output: jsonOutput$2,
357
+ async execute(args, exec) {
358
+ const { record } = await reader.read(exec);
359
+ const { trashPath, problems } = await deleteWorldPackFile(record.directory, args.pack, args.path);
360
+ return {
361
+ action: "deleted",
362
+ pack: args.pack,
363
+ path: args.path,
364
+ trashPath,
365
+ problems
366
+ };
367
+ }
368
+ })
369
+ ];
370
+ }
371
+ //#endregion
209
372
  //#region src/host/authoring/prompt-tools.ts
210
373
  const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
211
374
  const output$2 = (value) => [{
@@ -327,7 +490,8 @@ const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
327
490
  "delete_world_element",
328
491
  "edit_world_relationship",
329
492
  "replace_world_plots",
330
- ...PROMPT_MUTATION_TOOLS
493
+ ...PROMPT_MUTATION_TOOLS,
494
+ ...PACK_MUTATION_TOOLS
331
495
  ]);
332
496
  function result(action, kind, key, state, extra = {}) {
333
497
  return {
@@ -469,12 +633,29 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
469
633
  if (!AUTHORING_MUTATION_TOOLS.has(exec.name) || exec.agent === void 0 || authoredWorldOf(exec.agent.session.id) === void 0) return await next();
470
634
  const args = exec.arguments;
471
635
  const prompt = PROMPT_MUTATION_TOOLS.includes(exec.name);
636
+ const pack = PACK_MUTATION_TOOLS.includes(exec.name);
472
637
  const importing = await reviewing(exec.agent.session.id);
638
+ if (importing && pack) return {
639
+ kind: "deny",
640
+ reason: "an import does not write interface packs; they are left to the person"
641
+ };
473
642
  if (importing && prompt && !PROSE_PROMPTS.includes(String(args["id"]))) return {
474
643
  kind: "deny",
475
644
  reason: `an import may change only the prose prompts (${PROSE_PROMPTS.join(", ")}); "${String(args["id"])}" holds rules of the game and is left to the person`
476
645
  };
477
646
  if (importing) return await next();
647
+ if (pack) {
648
+ const target = `file “${String(args["path"])}” of interface pack “${String(args["pack"])}”`;
649
+ const remove = exec.name.startsWith("delete");
650
+ return {
651
+ kind: "ask",
652
+ reason: `${remove ? "delete" : "write"} authored world ${target}`,
653
+ displayReason: {
654
+ en: `${remove ? "Delete" : "Write"} ${target} in the world files?`,
655
+ zh: `${remove ? "删除" : "写入"}世界文件中界面包“${String(args["pack"])}”的文件“${String(args["path"])}”?`
656
+ }
657
+ };
658
+ }
478
659
  if (prompt) {
479
660
  const target = `prompt “${String(args["language"])}/${String(args["id"])}”`;
480
661
  const remove = exec.name.startsWith("delete");
@@ -501,6 +682,97 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
501
682
  };
502
683
  }
503
684
  //#endregion
685
+ //#region src/host/authoring/pack-jail.ts
686
+ /** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
687
+ const PACK_FILE_TOOLS = [
688
+ "read",
689
+ "write",
690
+ "edit"
691
+ ];
692
+ const WRITING = ["write", "edit"];
693
+ /** The most text a call may carry. */
694
+ const MAX_PACK_TEXT = 204800;
695
+ function unsafePath(ui, path) {
696
+ const parts = relative(ui, path).split(sep);
697
+ let current = ui;
698
+ for (const part of ["", ...parts]) {
699
+ if (part !== "") current = join(current, part);
700
+ try {
701
+ if (lstatSync(current).isSymbolicLink()) return `the path passes through the symbolic link ${current}`;
702
+ } catch (error) {
703
+ if (error.code === "ENOENT") break;
704
+ if (error.code === "ENOTDIR") return `${current} cannot be traversed as a folder`;
705
+ throw error;
706
+ }
707
+ }
708
+ }
709
+ /**
710
+ * Why a call of a file tool is not one on an interface pack of the world, or nothing when it is: the file must be a text
711
+ * file of a pack folder `<world>/ui/<pack>/`, and a write must not carry more text than a pack file may hold.
712
+ * @param path - the absolute path asked for.
713
+ * @param world - the world's folder.
714
+ */
715
+ function packFileProblem(tool, path, world, texts = []) {
716
+ const ui = join(world, "ui");
717
+ const inside = relative(ui, path);
718
+ const segments = inside.split(sep);
719
+ const hint = `in this chat the file tools reach only the text files of the world's interface packs, ${join(ui, "<pack>", "<file>")}. Nothing, not another path and not sandbox_permissions, lifts that: do not try again for this file, tell the person that it cannot be changed from here`;
720
+ if (inside === "" || inside.startsWith("..") || isAbsolute(inside) || segments.length < 2) return `${path} is not a file of an interface pack: ${hint}`;
721
+ if (!isPackId(segments[0])) return `"${segments[0]}" is not a usable pack name (letters, digits, "-" and "_"): ${hint}`;
722
+ if (segments.some((segment) => segment.startsWith("."))) return `${path}: names may not start with a dot`;
723
+ if (!TEXT_EXTENSIONS.includes(extname(path).slice(1).toLowerCase())) return `${path} is not a text file of a pack (${TEXT_EXTENSIONS.join(", ")}); pictures and other files are added by hand`;
724
+ const unsafe = unsafePath(ui, path);
725
+ if (unsafe !== void 0) return `${path}: ${unsafe}; file tools do not follow symbolic links in interface packs`;
726
+ if (WRITING.includes(tool) && texts.some((text) => Buffer.byteLength(text) > 204800)) return `a call may carry at most ${MAX_PACK_TEXT / 1024} KB of text`;
727
+ }
728
+ const textOf = (value) => typeof value === "string" ? [value] : [];
729
+ /**
730
+ * Keeps DSH's `read`, `write` and `edit` on the interface packs of the world in an authoring chat, and asks the person before
731
+ * any change. It stands first in the chain, so that what it refuses cannot be let through by a listener after it; and what a
732
+ * later listener decides still stands: a plugin that denies or asks keeps doing so, and only a plain allow becomes an ask.
733
+ */
734
+ async function packJail(exec, next, deps) {
735
+ const chat = exec.agent?.session.id;
736
+ if (!PACK_FILE_TOOLS.includes(exec.name) || chat === void 0 || authoredWorldOf(chat) === void 0) return await next();
737
+ const world = await deps.worldDirectory(chat);
738
+ if (world === void 0) return {
739
+ kind: "deny",
740
+ reason: "the world of this chat no longer exists"
741
+ };
742
+ const args = exec.arguments;
743
+ const requested = args["file_path"];
744
+ if (typeof requested !== "string" || requested === "" || requested.startsWith("~")) return {
745
+ kind: "deny",
746
+ reason: "file_path must be a path of an interface pack of this world"
747
+ };
748
+ const path = resolve(exec.agent?.session.header.cwd ?? world, requested);
749
+ const problem = packFileProblem(exec.name, path, world, [...textOf(args["content"]), ...textOf(args["new_string"])]);
750
+ if (problem !== void 0) return {
751
+ kind: "deny",
752
+ reason: problem
753
+ };
754
+ const writing = WRITING.includes(exec.name);
755
+ if (writing && await deps.reviewing(chat)) return {
756
+ kind: "deny",
757
+ reason: "an import does not write interface packs; they are left to the person"
758
+ };
759
+ const decision = await next();
760
+ if (!writing || decision.kind !== "allow") return decision;
761
+ const target = `“${relative(join(world, "ui"), path)}”`;
762
+ return {
763
+ kind: "ask",
764
+ reason: `${exec.name} interface pack file ${target}`,
765
+ displayReason: {
766
+ en: `${exec.name === "write" ? "Write" : "Edit"} ${target} of an interface pack in the world files?`,
767
+ zh: `${exec.name === "write" ? "写入" : "编辑"}世界文件中界面包的文件${target}?`
768
+ }
769
+ };
770
+ }
771
+ /** Puts the jail first in the chain of `tools/pre-execute`: what it refuses cannot be let through by a listener after it. */
772
+ function registerPackJail(ctx, deps) {
773
+ ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
774
+ }
775
+ //#endregion
504
776
  //#region src/host/import/tools.ts
505
777
  const SURVEY_TOOL = "import_survey";
506
778
  const BUILD_TOOL = "import_build";
@@ -729,6 +1001,7 @@ function apply(ctx) {
729
1001
  for (const tool of authoredWorldReadTools(reader)) ctx.tools.register(tool);
730
1002
  for (const tool of authoredWorldWriteTools(reader)) ctx.tools.register(tool);
731
1003
  for (const tool of worldPromptTools(reader)) ctx.tools.register(tool);
1004
+ for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
732
1005
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
733
1006
  importHooks(ctx, ctx.roleplayWorlds, prompting);
734
1007
  const reviewing = async (chat) => {
@@ -736,6 +1009,14 @@ function apply(ctx) {
736
1009
  const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
737
1010
  return record !== void 0 && await isReviewing(record.directory);
738
1011
  };
1012
+ const worldDirectory = async (chat) => {
1013
+ const id = authoredWorldOf(chat);
1014
+ return id === void 0 ? void 0 : (await ctx.roleplayWorlds.find(id))?.directory;
1015
+ };
1016
+ registerPackJail(ctx, {
1017
+ worldDirectory,
1018
+ reviewing
1019
+ });
739
1020
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing));
740
1021
  for (const [name, order, id] of [[
741
1022
  "WORLD_AUTHORING_PERSONA",