@dsh-agentic-roleplay/core 0.7.2 → 0.8.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 (54) hide show
  1. package/README.md +1 -1
  2. package/lib/authoring-tools-DNnx0Nts.js +3574 -0
  3. package/lib/authoring.js +295 -333
  4. package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
  5. package/lib/client.js +931 -415
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +2 -2
  8. package/lib/doctor.js +2 -2
  9. package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
  10. package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +1326 -1638
  15. package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
  16. package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
  19. package/lib/orchestration.js +95 -18
  20. package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
  21. package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
  22. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
  23. package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
  24. package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/presets-MwOSMMyu.js +3998 -0
  27. package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
  28. package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
  29. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
  30. package/package.json +2 -2
  31. package/prompts/en/import/casting.md +14 -0
  32. package/prompts/en/import/classifier.md +9 -0
  33. package/prompts/en/import/finish-draft.md +1 -0
  34. package/prompts/en/import/generator.md +8 -0
  35. package/prompts/en/import/notice-repair.md +4 -0
  36. package/prompts/en/import/repair-again.md +3 -0
  37. package/prompts/en/import/roster.md +1 -0
  38. package/prompts/en/import/variables.md +1 -0
  39. package/prompts/en/roleplay/game-master.md +3 -0
  40. package/prompts/en/roleplay/standing.md +1 -0
  41. package/prompts/en/world/author.md +1 -1
  42. package/prompts/zh/import/casting.md +14 -0
  43. package/prompts/zh/import/classifier.md +9 -0
  44. package/prompts/zh/import/finish-draft.md +1 -0
  45. package/prompts/zh/import/generator.md +8 -0
  46. package/prompts/zh/import/notice-repair.md +4 -0
  47. package/prompts/zh/import/repair-again.md +3 -0
  48. package/prompts/zh/import/roster.md +1 -0
  49. package/prompts/zh/import/variables.md +1 -0
  50. package/prompts/zh/roleplay/game-master.md +3 -0
  51. package/prompts/zh/roleplay/standing.md +1 -0
  52. package/prompts/zh/world/author.md +1 -1
  53. package/lib/authoring-tools-q34iq3hW.js +0 -6140
  54. package/lib/route-DRTJ_vcA.js +0 -518
@@ -155,6 +155,7 @@ function sharedSamplingOf(settings) {
155
155
  const SUBMIT_TOOL = "submit_result";
156
156
  /** Said to every child once, after its persona, so it is the same for all of them and the start of every request stays the same. */
157
157
  const SUBMIT_RULE = `When you are done, call ${SUBMIT_TOOL} with your result. It is the only way to finish: text you write instead is lost.`;
158
+ const STRUCTURED_RULE = "Your whole reply is the result, as one JSON object of the shape you were given: write nothing before or after it.";
158
159
  /** Calls a child may make before it is given up; a child that keeps going is not converging. */
159
160
  const DEFAULT_MAX_CALLS = 40;
160
161
  /** A child that stops without a result is told to submit this many times before it is given up. */
@@ -170,6 +171,11 @@ const REPEATS_TOLD = 1;
170
171
  const REPEATS_STOPPED = 4;
171
172
  /** A result that is refused this many times is not going to be fixed by asking again: the child is stopped and the caller decides what to do without it. */
172
173
  const MAX_REFUSALS = 5;
174
+ /**
175
+ * How long a child that was stopped has to wind down. Found live twice: a stopped child's activation never settled and the caller waited for ever (an import stood still for
176
+ * minutes, a game master's turn never ended), so what the stop decided is not waited on past this.
177
+ */
178
+ const STOP_GRACE_MS = 15e3;
173
179
  /** A child ran out of the time it was given; asking again would only spend it again. */
174
180
  var ChildTimeoutError = class extends Error {
175
181
  constructor(minutes) {
@@ -320,6 +326,57 @@ async function supportedEffort(task) {
320
326
  return level;
321
327
  }
322
328
  }
329
+ /**
330
+ * A JSON text that was cut off, closed after the last whole entry it holds: what a reply that ran into its limit in the middle of a long list still says. Nothing when no such cut makes it JSON.
331
+ */
332
+ function repairedJson(text) {
333
+ const cuts = [];
334
+ for (const marks of ["}]", ","]) for (let at = text.length - 1, found = 0; at >= 0 && found < 300; at -= 1) if (marks.includes(text[at])) {
335
+ cuts.push(at);
336
+ found += 1;
337
+ }
338
+ for (const at of cuts) {
339
+ const head = text.slice(0, text[at] === "," ? at : at + 1);
340
+ const stack = [];
341
+ let inString = false;
342
+ for (let index = 0; index < head.length; index += 1) {
343
+ const char = head[index];
344
+ if (inString) {
345
+ if (char === "\\") index += 1;
346
+ else if (char === "\"") inString = false;
347
+ continue;
348
+ }
349
+ if (char === "\"") inString = true;
350
+ else if (char === "{") stack.push("}");
351
+ else if (char === "[") stack.push("]");
352
+ else if (char === "}" || char === "]") stack.pop();
353
+ }
354
+ if (inString) continue;
355
+ const closed = head + stack.reverse().join("");
356
+ try {
357
+ JSON.parse(closed);
358
+ return closed;
359
+ } catch {
360
+ continue;
361
+ }
362
+ }
363
+ }
364
+ /** The result in the last reply of a structured child: its JSON, which must fit the schema; else what is wrong with it. */
365
+ function structuredReply(child, schema, cut = false) {
366
+ const message = child.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
367
+ const text = (message?.type === "assistant/message" ? message.data.message.content : []).flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
368
+ if (text === "") return { problem: "the reply is empty" };
369
+ let value;
370
+ try {
371
+ value = JSON.parse(text);
372
+ } catch (error) {
373
+ const mended = cut ? repairedJson(text) : void 0;
374
+ if (mended === void 0) return { problem: `the reply is not valid JSON (${error instanceof Error ? error.message : String(error)})` };
375
+ value = JSON.parse(mended);
376
+ }
377
+ const violations = validateJsonSchemaValue(schema, value);
378
+ return violations.length > 0 ? { problem: violations.map((violation) => String(violation)).join("; ") } : { value };
379
+ }
323
380
  const cut = (value, limit = MAX_RUN_TEXT) => {
324
381
  const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
325
382
  return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
@@ -330,6 +387,10 @@ async function execute(task, stats) {
330
387
  let submitted;
331
388
  let reminders = 0;
332
389
  let stopped;
390
+ let giveUp;
391
+ const gaveUp = new Promise((resolve) => {
392
+ giveUp = resolve;
393
+ });
333
394
  let retire;
334
395
  let stepsAfterRetire = -1;
335
396
  let overran = false;
@@ -447,11 +508,14 @@ async function execute(task, stats) {
447
508
  };
448
509
  const childId = SessionId(randomUUID());
449
510
  const entry = {
450
- persona: `${task.persona}\n\n${SUBMIT_RULE}`,
511
+ persona: `${task.persona}\n\n${task.structured === true ? STRUCTURED_RULE : SUBMIT_RULE}`,
451
512
  setup(child) {
452
513
  entry.agent = child;
453
514
  stopped = () => {
454
515
  child.cancel({ kind: "parent" });
516
+ setTimeout(() => {
517
+ giveUp?.();
518
+ }, STOP_GRACE_MS);
455
519
  };
456
520
  const childCtx = child.ctx;
457
521
  childCtx.tools.restrict({ allow: [...task.external ?? []] });
@@ -476,9 +540,51 @@ async function execute(task, stats) {
476
540
  }
477
541
  return decision;
478
542
  });
479
- childCtx.tools.register(submit);
543
+ if (task.structured !== true) childCtx.tools.register(submit);
480
544
  childCtx.on("agent/turn-stopping", () => {
481
545
  if (submitted !== void 0) return;
546
+ if (task.structured === true) {
547
+ const reply = structuredReply(child, enforcedSchema(task), cutOff(child));
548
+ if (cutOff(child) && !("value" in reply)) {
549
+ rambled = true;
550
+ overran = true;
551
+ stopped?.();
552
+ return;
553
+ }
554
+ const refusal = "value" in reply ? task.beforeSubmit?.(reply.value) : reply.problem;
555
+ if ("value" in reply && refusal === void 0) {
556
+ submitted = { value: reply.value };
557
+ stats.result = cut(reply.value, MAX_RUN_PROMPT);
558
+ if (stats.record.length < 60) stats.record.push({
559
+ tool: "reply",
560
+ args: "",
561
+ outcome: cut(reply.value),
562
+ failed: false
563
+ });
564
+ return;
565
+ }
566
+ refusals += 1;
567
+ lastRefusal = refusal ?? "";
568
+ if (stats.record.length < 60) stats.record.push({
569
+ tool: "reply",
570
+ args: "",
571
+ outcome: cut(lastRefusal),
572
+ failed: true
573
+ });
574
+ if (refusals >= MAX_REFUSALS) {
575
+ overran = true;
576
+ stopped?.();
577
+ return;
578
+ }
579
+ child.steer(createUserMessage({
580
+ content: [{
581
+ type: "text",
582
+ text: `That reply cannot be used: ${lastRefusal}\nReply again with the whole result as one JSON object.`
583
+ }],
584
+ source: { kind: "roleplay" }
585
+ }));
586
+ return;
587
+ }
482
588
  if (cutOff(child)) {
483
589
  rambled = true;
484
590
  overran = true;
@@ -499,7 +605,23 @@ async function execute(task, stats) {
499
605
  }
500
606
  };
501
607
  helpers.set(childId, entry);
502
- if (task.sampling !== void 0) samplings.set(childId, task.sampling);
608
+ if (task.structured === true) {
609
+ const { toolChoice: _unused, ...rest } = task.sampling ?? {};
610
+ samplings.set(childId, {
611
+ ...rest,
612
+ body: {
613
+ ...rest.body,
614
+ response_format: {
615
+ type: "json_schema",
616
+ json_schema: {
617
+ name: "result",
618
+ strict: true,
619
+ schema: task.result
620
+ }
621
+ }
622
+ }
623
+ });
624
+ } else if (task.sampling !== void 0) samplings.set(childId, task.sampling);
503
625
  try {
504
626
  const subagents = parent.ctx.get("subagents");
505
627
  if (subagents === void 0) throw new Error("the sub-agent service is not loaded");
@@ -527,12 +649,14 @@ async function execute(task, stats) {
527
649
  }
528
650
  });
529
651
  try {
530
- await activation.result;
652
+ await Promise.race([activation.result, gaveUp]);
531
653
  } catch (error) {
532
654
  if (submitted === void 0 && !overran && !signal.aborted) throw error;
533
655
  } finally {
534
656
  if (entry.agent !== void 0) stats.tokens = tokensOf(entry.agent.session.snapshotEvents());
535
- await activation.dispose();
657
+ await (overran ? Promise.race([activation.dispose(), new Promise((resolve) => {
658
+ setTimeout(resolve, STOP_GRACE_MS);
659
+ })]) : activation.dispose());
536
660
  }
537
661
  } finally {
538
662
  helpers.delete(childId);
@@ -552,4 +676,4 @@ async function execute(task, stats) {
552
676
  //#endregion
553
677
  export { finishOf as _, childTrace as a, runChild as c, sharedSamplingOf as d, tokensOf as f, cutOff as g, currentTurn as h, childSamplingOf as i, SAMPLING_RANGES as l, addTokens as m, childModel as n, helpers as o, NO_TOKENS as p, childSampling as r, namedModel as s, ChildTimeoutError as t, parseSampling as u, estimateAnswer as v, tokensOf$1 as y };
554
678
 
555
- //# sourceMappingURL=child-CyCViUKa.js.map
679
+ //# sourceMappingURL=child-D6mpkkCE.js.map