@alexkroman1/aai-cli 16.1.0 → 17.0.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.
Files changed (183) hide show
  1. package/README.md +2 -1
  2. package/dist/{_build-target-ClEEuUuW.mjs → _build-target-C08aM-Es.mjs} +504 -43
  3. package/dist/_build-target.d.ts +98 -19
  4. package/dist/_deno-target.d.ts +15 -14
  5. package/dist/_dev-env.d.ts +19 -13
  6. package/dist/{_dev-server-D1wKiA0_.mjs → _dev-server-CLU9xjH5.mjs} +25 -17
  7. package/dist/_dev-server.d.ts +4 -3
  8. package/dist/_init.d.ts +39 -0
  9. package/dist/_modal-target.d.ts +11 -6
  10. package/dist/_preflight-CnW9QiE7.mjs +116 -0
  11. package/dist/_preflight.d.ts +110 -5
  12. package/dist/_target-bundle.d.ts +112 -0
  13. package/dist/_target-entry.d.ts +81 -0
  14. package/dist/{_templates-CuP74F8D.mjs → _templates-IMeKMVIj.mjs} +1 -1
  15. package/dist/{_vitest-runner-BiAMIir1.mjs → _vitest-runner-CZNGj0ZC.mjs} +21 -16
  16. package/dist/_vitest-runner.d.ts +35 -23
  17. package/dist/{build-O6BT51x_.mjs → build-DrQTSc2R.mjs} +128 -293
  18. package/dist/build.d.ts +34 -4
  19. package/dist/cli.mjs +20 -16
  20. package/dist/{deploy-lldQyJVj.mjs → deploy-B68-x7xM.mjs} +12 -4
  21. package/dist/deploy.d.ts +9 -0
  22. package/dist/{dev-Du8pCWFq.mjs → dev-ChsrNHpK.mjs} +1 -1
  23. package/dist/dev.d.ts +1 -1
  24. package/dist/{eval-Ducmkt1n.mjs → eval-DB07kTxO.mjs} +1 -1
  25. package/dist/init-W-4k-lCF.mjs +559 -0
  26. package/dist/init.d.ts +43 -3
  27. package/dist/scaffold/CLAUDE.md +51 -64
  28. package/dist/scaffold/package.json +6 -6
  29. package/dist/scaffold/vite.config.ts +29 -1
  30. package/dist/{studio-It7SRfUN.mjs → studio-DEAJGBXa.mjs} +19 -9
  31. package/dist/templates/applicant-screening-agent/agent.eval.test.ts +20 -6
  32. package/dist/templates/applicant-screening-agent/agent.ts +28 -0
  33. package/dist/templates/applicant-screening-agent/shared.ts +11 -11
  34. package/dist/templates/call-audit-workflow/agent.ts +2 -0
  35. package/dist/templates/code-interpreter-agent/agent.eval.test.ts +3 -2
  36. package/dist/templates/code-interpreter-agent/agent.ts +1 -0
  37. package/dist/templates/coding-agent/agent.eval.test.ts +136 -0
  38. package/dist/templates/coding-agent/agent.test.ts +109 -0
  39. package/dist/templates/coding-agent/agent.ts +45 -0
  40. package/dist/templates/coding-agent/chat.ts +63 -0
  41. package/dist/templates/coding-agent/shared.ts +46 -0
  42. package/dist/templates/coding-agent/system-prompt.md +32 -0
  43. package/dist/templates/coding-agent/tools/bash.ts +6 -0
  44. package/dist/templates/coding-agent/tools/delete_file.ts +6 -0
  45. package/dist/templates/coding-agent/tools/edit_file.ts +6 -0
  46. package/dist/templates/coding-agent/tools/glob.ts +6 -0
  47. package/dist/templates/coding-agent/tools/grep.ts +6 -0
  48. package/dist/templates/coding-agent/tools/list_files.ts +6 -0
  49. package/dist/templates/coding-agent/tools/read_file.ts +6 -0
  50. package/dist/templates/coding-agent/tools/todo_write.ts +6 -0
  51. package/dist/templates/coding-agent/tools/write_file.ts +6 -0
  52. package/dist/templates/custom-pipeline-agent/agent.ts +1 -0
  53. package/dist/templates/document-redline-workflow/agent.ts +2 -0
  54. package/dist/templates/emergency-dispatch-agent/agent.test.ts +103 -0
  55. package/dist/templates/emergency-dispatch-agent/agent.ts +15 -0
  56. package/dist/templates/emergency-dispatch-agent/guardrails.ts +105 -0
  57. package/dist/templates/emergency-dispatch-agent/system-prompt.md +1 -0
  58. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +8 -1
  59. package/dist/templates/entertainment-picks-agent/agent.ts +1 -0
  60. package/dist/templates/entertainment-picks-agent/system-prompt.md +6 -0
  61. package/dist/templates/entertainment-picks-agent/tools/revisit.ts +7 -0
  62. package/dist/templates/executive-inbox-agent/agent.eval.test.ts +84 -23
  63. package/dist/templates/executive-inbox-agent/agent.ts +1 -0
  64. package/dist/templates/executive-inbox-agent/meeting.ts +1 -1
  65. package/dist/templates/executive-inbox-agent/prompts.ts +3 -1
  66. package/dist/templates/executive-inbox-agent/system-prompt.md +3 -3
  67. package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +3 -3
  68. package/dist/templates/executive-inbox-agent/tools/open_email.ts +8 -16
  69. package/dist/templates/hotel-reception-agent/agent.eval.test.ts +85 -21
  70. package/dist/templates/hotel-reception-agent/agent.test.ts +2 -1
  71. package/dist/templates/hotel-reception-agent/agent.ts +6 -3
  72. package/dist/templates/hotel-reception-agent/client.tsx +14 -2
  73. package/dist/templates/hotel-reception-agent/concierge.ts +2 -1
  74. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +2 -1
  75. package/dist/templates/hotel-reception-agent/disputes.ts +9 -11
  76. package/dist/templates/hotel-reception-agent/events.ts +2 -1
  77. package/dist/templates/hotel-reception-agent/session.ts +56 -0
  78. package/dist/templates/hotel-reception-agent/shared.ts +20 -21
  79. package/dist/templates/hotel-reception-agent/system-prompt.md +1 -1
  80. package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +2 -1
  81. package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +2 -1
  82. package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +2 -1
  83. package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +2 -1
  84. package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +2 -1
  85. package/dist/templates/hotel-reception-agent/tools/check_restaurant_availability.ts +1 -1
  86. package/dist/templates/hotel-reception-agent/tools/check_room_availability.ts +1 -1
  87. package/dist/templates/hotel-reception-agent/tools/choose_room.ts +1 -1
  88. package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +2 -1
  89. package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +2 -1
  90. package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +2 -1
  91. package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +2 -1
  92. package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +2 -1
  93. package/dist/templates/hotel-reception-agent/tools/lookup_guest_history.ts +1 -1
  94. package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +2 -1
  95. package/dist/templates/hotel-reception-agent/tools/lookup_restaurant_reservation.ts +1 -1
  96. package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +1 -1
  97. package/dist/templates/hotel-reception-agent/tools/record_card.ts +1 -1
  98. package/dist/templates/hotel-reception-agent/tools/record_followup.ts +2 -1
  99. package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +2 -1
  100. package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +1 -1
  101. package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +1 -1
  102. package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +2 -1
  103. package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +2 -1
  104. package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +1 -1
  105. package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +2 -1
  106. package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +2 -1
  107. package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +2 -1
  108. package/dist/templates/hotel-reception-agent/tools/set_extras.ts +1 -1
  109. package/dist/templates/hotel-reception-agent/tools/set_stay.ts +2 -1
  110. package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +2 -1
  111. package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +2 -1
  112. package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +2 -1
  113. package/dist/templates/hotel-reception-agent/tools/transfer_call.ts +2 -1
  114. package/dist/templates/hotel-reception-agent/tools/update_card.ts +2 -1
  115. package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +2 -1
  116. package/dist/templates/link-digest-workflow/agent.eval.test.ts +16 -1
  117. package/dist/templates/link-digest-workflow/agent.ts +5 -0
  118. package/dist/templates/medication-safety-agent/agent.test.ts +54 -0
  119. package/dist/templates/medication-safety-agent/agent.ts +48 -1
  120. package/dist/templates/meeting-recap-agent/agent.test.ts +2 -2
  121. package/dist/templates/meeting-recap-agent/agent.ts +4 -0
  122. package/dist/templates/pizza-ordering-agent/agent.ts +3 -0
  123. package/dist/templates/podcast-digest-workflow/agent.ts +4 -0
  124. package/dist/templates/quickstart-agent/agent.eval.test.ts +39 -3
  125. package/dist/templates/quickstart-agent/agent.test.ts +22 -0
  126. package/dist/templates/quickstart-agent/agent.ts +18 -2
  127. package/dist/templates/quickstart-agent/system-prompt.md +8 -0
  128. package/dist/templates/quickstart-agent/tools/get_weather.ts +59 -0
  129. package/dist/templates/research-handoff-agent/agent.ts +4 -0
  130. package/dist/templates/research-planner-agent/agent.eval.test.ts +24 -2
  131. package/dist/templates/research-planner-agent/agent.ts +3 -0
  132. package/dist/templates/research-planner-agent/system-prompt.md +1 -1
  133. package/dist/templates/retail-orders-agent/agent.ts +32 -3
  134. package/dist/templates/retail-orders-agent/keyterms.ts +154 -0
  135. package/dist/templates/retail-orders-agent/resolve.ts +18 -3
  136. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +37 -5
  137. package/dist/templates/roadside-assistance-agent/agent.test.ts +38 -6
  138. package/dist/templates/roadside-assistance-agent/agent.ts +4 -0
  139. package/dist/templates/roadside-assistance-agent/shared.ts +12 -0
  140. package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +14 -0
  141. package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +11 -0
  142. package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +17 -11
  143. package/dist/templates/roadside-assistance-agent/yard.test.ts +4 -0
  144. package/dist/templates/spoken-summary-workflow/agent.ts +4 -0
  145. package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +6 -0
  146. package/dist/templates/tabletop-rpg-agent/agent.test.ts +125 -1
  147. package/dist/templates/tabletop-rpg-agent/agent.ts +30 -1
  148. package/dist/templates/tabletop-rpg-agent/shared.ts +81 -0
  149. package/dist/templates/tabletop-rpg-agent/system-prompt.md +1 -1
  150. package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +16 -7
  151. package/dist/templates/technical-support-agent/agent.test.ts +3 -3
  152. package/dist/templates/technical-support-agent/agent.ts +5 -1
  153. package/dist/templates/technical-support-agent/knowledge.ts +165 -0
  154. package/dist/templates/technical-support-agent/nodes.ts +3 -2
  155. package/dist/templates/technical-support-agent/procedure.ts +4 -3
  156. package/dist/templates/technical-support-agent/shared.ts +10 -146
  157. package/dist/templates/technical-support-agent/tools/list_topics.ts +2 -1
  158. package/dist/templates/text-adventure-agent/agent.eval.test.ts +39 -6
  159. package/dist/templates/text-adventure-agent/agent.test.ts +79 -1
  160. package/dist/templates/text-adventure-agent/agent.ts +30 -1
  161. package/dist/templates/text-adventure-agent/shared.ts +37 -0
  162. package/dist/templates/text-adventure-agent/system-prompt.md +9 -2
  163. package/dist/templates/topic-briefing-agent/agent.eval.test.ts +18 -4
  164. package/dist/templates/topic-briefing-agent/agent.test.ts +23 -11
  165. package/dist/templates/topic-briefing-agent/agent.ts +4 -1
  166. package/dist/templates/topic-briefing-agent/shared.ts +10 -10
  167. package/dist/templates/topic-briefing-agent/system-prompt.md +13 -8
  168. package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +43 -5
  169. package/dist/templates/transcription-workflow/agent.ts +3 -0
  170. package/dist/templates/travel-concierge-agent/agent.ts +4 -0
  171. package/dist/templates/web-research-agent/agent.eval.test.ts +31 -5
  172. package/dist/templates/web-research-agent/agent.test.ts +16 -0
  173. package/dist/templates/web-research-agent/agent.ts +30 -0
  174. package/dist/templates/web-research-agent/system-prompt.md +8 -2
  175. package/dist/templates/word-game-agent/agent.eval.test.ts +79 -18
  176. package/dist/templates/word-game-agent/agent.ts +20 -0
  177. package/dist/test-CjKPQ9_B.mjs +102 -0
  178. package/dist/test.d.ts +37 -12
  179. package/package.json +5 -5
  180. package/dist/_init-Bp1CjRrU.mjs +0 -199
  181. package/dist/_preflight-CcAR577V.mjs +0 -46
  182. package/dist/init-CY4NAXAA.mjs +0 -183
  183. package/dist/test-PHHv0Vj6.mjs +0 -83
@@ -1,14 +1,43 @@
1
1
  import { agent } from "@alexkroman1/aai";
2
- import { gameProjection, storyFlow } from "./shared.ts";
2
+ import { gameProjection, gameSlot, liveSheet, storyFlow } from "./shared.ts";
3
+ // The rules of the game. The build discovers `system-prompt.md` on its own —
4
+ // importing it is what lets the resolver below compose against it, and
5
+ // `withSystemPrompt` leaves a resolver exactly as written.
6
+ import prompt from "./system-prompt.md?raw";
3
7
 
4
8
  export default agent({
5
9
  name: "Solo RPG",
10
+ // The listing line, for a reader picking an agent out of a list. It says what
11
+ // the borrowed systems DO rather than naming them — the attribution belongs
12
+ // in `shared.ts`, not in a picker row.
13
+ description: "Narrates a solo tabletop campaign and keeps its dice, tracks and clocks",
6
14
  greeting:
7
15
  "Welcome. Tell me your name, or describe the kind of story you want, and we will begin. You can say something like, dark fantasy warrior named Kael, or just give me a name and I will build a world around you.",
8
16
  sttPrompt:
9
17
  "Solo RPG terms: strong hit, weak hit, miss, momentum, chaos factor, clock, disposition, bond, edge, heart, iron, shadow, wits, face danger, compel, gather information, secure advantage, clash, strike, endure harm, endure stress, make connection, test bond, resupply, world shaping",
10
18
  maxSteps: 8,
11
19
 
20
+ /**
21
+ * The rules, plus the campaign sheet as it stands RIGHT NOW.
22
+ *
23
+ * A `systemPrompt` resolver is called once per model request, so the tracks,
24
+ * the momentum, the chaos factor, the clocks and the cast are in front of the
25
+ * narrator before it says anything. The prompt's FLOW section used to open
26
+ * with "call check_state as your FIRST tool call every turn … NEVER remember
27
+ * or guess stats from prior turns" — a full model round trip per turn of a
28
+ * live voice game, and only advice, so the turns it was skipped on are the
29
+ * turns the sheet drifted.
30
+ *
31
+ * `ctx` is an `AgentSessionContext`: the session id, the env and the slots.
32
+ * Enough for `gameSlot.get`, and deliberately nothing that could speak — a
33
+ * resolver returns instructions, it does not take a turn.
34
+ *
35
+ * The dialog's own `instruction` is NOT rendered here. `storyFlow` is declared
36
+ * below, and the runtime already appends the active state's instruction to the
37
+ * same prompt; saying it twice is how two copies of one rule drift apart.
38
+ */
39
+ systemPrompt: (ctx) => `${prompt}\n\n${liveSheet(gameSlot.get(ctx))}`,
40
+
12
41
  // One declaration replaces a `ctx.send("game_state", state)` in every
13
42
  // state-mutating tool — six of them, and adding a seventh meant
14
43
  // remembering to push or watching the UI quietly fall out of sync.
@@ -669,6 +669,87 @@ export function stateSummary(state: FrozenGameState) {
669
669
  };
670
670
  }
671
671
 
672
+ /**
673
+ * The campaign sheet as the NARRATOR is given it, before every reply.
674
+ *
675
+ * `agent.ts` appends this to the system prompt through a `systemPrompt`
676
+ * resolver, so every number the narrator must not invent — the tracks, the
677
+ * momentum, the chaos factor, the clocks, who is in the scene — is in front of
678
+ * the model on each request.
679
+ *
680
+ * **This is what retired the FLOW rule that opened every turn with a tool
681
+ * call.** `system-prompt.md` used to say "Call check_state as your FIRST tool
682
+ * call every turn, before narrating or rolling … NEVER remember or guess stats
683
+ * from prior turns": an instruction that bought a full model round trip on every
684
+ * turn of a live voice game when it was obeyed, and a desynced sheet when it was
685
+ * not. A number the model may not guess belongs in the prompt, not behind a rule
686
+ * telling it to go and fetch one.
687
+ *
688
+ * `check_state` is NOT retired. It answers with the chronicle, the whole NPC
689
+ * records and the story blueprint as well, and it is the tool for a turn where
690
+ * the narrator wants the full board or the position restated. What went is the
691
+ * compulsory read-back.
692
+ *
693
+ * Prose rather than {@link stateSummary}'s JSON, because this is read as
694
+ * instructions rather than as a tool result — and deliberately SHORTER than that
695
+ * summary: it lands on every request, where a tool result lands once. The
696
+ * position (`state`/`instruction`) is not here either, since `storyFlow` is
697
+ * declared in `agent({ dialogs })` and the runtime already puts the active
698
+ * state's `instruction` in the same prompt.
699
+ */
700
+ export function liveSheet(game: FrozenGameState): string {
701
+ if (!game.initialized) {
702
+ return [
703
+ "LIVE CAMPAIGN SHEET: no character yet, and no campaign. setup_character is",
704
+ "the only way in and it fills every field itself — take whatever the player",
705
+ "gave you, invent the rest, and call it this turn.",
706
+ ].join("\n");
707
+ }
708
+
709
+ const clocks = game.clocks.map((c) => `${c.name} ${c.filled}/${c.segments} (${c.clockType})`);
710
+ const cast = game.npcs
711
+ .filter((n) => n.status !== "deceased")
712
+ .map((n) => `${n.name} (${n.disposition}, bond ${n.bond})`);
713
+
714
+ const lines = [
715
+ "LIVE CAMPAIGN SHEET (the engine's own record, refreshed before every reply —",
716
+ "these are ground truth, they are never a turn behind, and you neither guess",
717
+ "them nor change them by narrating):",
718
+ `- ${game.playerName || "The player"}, ${game.settingArchetype} — ${game.settingGenre}, ${game.settingTone}`,
719
+ `- Stats: edge ${game.edge}, heart ${game.heart}, iron ${game.iron}, shadow ${game.shadow}, wits ${game.wits}`,
720
+ `- Health ${game.health}/${MAX_RESOURCE}, spirit ${game.spirit}/${MAX_RESOURCE}, supply ${game.supply}/${MAX_RESOURCE}`,
721
+ `- Momentum ${game.momentum} (max ${game.maxMomentum}), chaos factor ${game.chaosFactor}`,
722
+ `- Scene ${game.sceneCount}, ${game.currentLocation || "location unset"}, ${game.timeOfDay || "time unset"}`,
723
+ `- Clocks: ${clocks.length > 0 ? clocks.join("; ") : "none"}`,
724
+ `- NPCs: ${cast.length > 0 ? cast.join("; ") : "none"}`,
725
+ ];
726
+
727
+ if (game.storyBlueprint) {
728
+ const { currentAct, acts, storyComplete } = game.storyBlueprint;
729
+ const phase = acts[currentAct - 1]?.phase ?? "unknown";
730
+ lines.push(
731
+ `- Act ${currentAct} of ${acts.length} (${phase})${storyComplete ? ", story complete" : ""}`,
732
+ );
733
+ }
734
+
735
+ // DERIVED, for the reason `stateSummary` derives them: `after` restores the
736
+ // stored flags only once a mutating body has returned, so a sheet rendered
737
+ // from the fields would report a just-emptied track as survivable.
738
+ if (isGameOver(game)) {
739
+ lines.push("- GAME OVER: nothing can be rolled or updated. Narrate the ending.");
740
+ } else if (inCrisis(game)) {
741
+ lines.push("- CRISIS: a track is empty. Every miss now is more dangerous.");
742
+ }
743
+ if (game.kidMode) lines.push("- Kid mode is on.");
744
+ if (game.lastRoll) {
745
+ lines.push(
746
+ `- A ${game.lastRoll.result} on ${game.lastRoll.move} is standing — burn_momentum can still upgrade it.`,
747
+ );
748
+ }
749
+
750
+ return lines.join("\n");
751
+ }
752
+
672
753
  // ── Dice System ──────────────────────────────────────────────────────────────
673
754
  export type RollOutcome = "STRONG_HIT" | "WEAK_HIT" | "MISS";
674
755
 
@@ -98,7 +98,7 @@ CORRECTION SYSTEM:
98
98
  If the player starts a message with ##, treat it as a correction to the previous turn. Acknowledge the correction and rewrite the scene.
99
99
 
100
100
  FLOW:
101
- 1. Call check_state as your FIRST tool call every turn, before narrating or rolling. Read the returned values as ground truth. NEVER remember or guess stats from prior turns. Its `state` and `instruction` say where the story is and what that expects — every other tool answers with the same pair, and a tool that is not available yet refuses and tells you what has to happen first. You do not have to remember any of this between turns.
101
+ 1. The LIVE CAMPAIGN SHEET at the end of these instructions is refreshed before every reply: the tracks, momentum, chaos factor, clocks, cast, and which act you are in. It is the engine's own record and it is never a turn behind, so read it rather than remembering, and never state a number that contradicts it. You do not have to open a turn with a tool call to find out where you are. `check_state` is still there for the full board — the chronicle, the whole NPC records, the story blueprint — and for the position (`state` and `instruction`) restated on demand; every other tool answers with that same pair, and a tool that is not available yet refuses and tells you what has to happen first.
102
102
  2. Present situations with tension and choice. Two to three options, but accept anything.
103
103
  3. For ANY risky action, you MUST call action_roll. NEVER narrate success or failure without rolling. NEVER reduce health, spirit, supply, or momentum yourself — action_roll does this through code. If you narrate damage without calling action_roll, the sidebar will be wrong and the game will break.
104
104
  4. After location changes, new NPCs, or other world changes, call update_state. But NEVER manually set health, spirit, supply, or momentum in update_state unless the player is resting or trading — action_roll handles combat and risk.
@@ -6,16 +6,25 @@ import { gameSlot, stateSummary, storyFlow } from "../shared.ts";
6
6
  * is handed is deep-frozen, which is what makes "this tool only reads" a
7
7
  * property of the declaration rather than a claim in a comment.
8
8
  *
9
- * **Legal in every state, which is why it is not a `storyFlow.tool`** — the
10
- * prompt says to call it FIRST every turn, and that includes the turn before a
11
- * character exists. It is also the one tool that reports the POSITION, the way
12
- * `research-planner-agent`'s `plan_status` does: the position comes from the machine
13
- * rather than from a second reading of the campaign's fields, so "there is no
14
- * character yet" is the same fact here as the refusal `action_roll` would give.
9
+ * **Legal in every state, which is why it is not a `storyFlow.tool`** — it is
10
+ * answerable before a character exists, and "there is no campaign yet" is a
11
+ * thing the narrator may need said back. It is also the one tool that reports
12
+ * the POSITION, the way `research-planner-agent`'s `plan_status` does: the
13
+ * position comes from the machine rather than from a second reading of the
14
+ * campaign's fields, so "there is no character yet" is the same fact here as the
15
+ * refusal `action_roll` would give.
16
+ *
17
+ * **It is no longer called every turn, and that is the point of `liveSheet`.**
18
+ * The prompt used to open every turn with this call — a full model round trip
19
+ * before a word of narration, on a live voice game — because the tracks and the
20
+ * clocks reached the model no other way. They ride in the system prompt now
21
+ * (`agent.ts`'s `systemPrompt` resolver), so what is left here is the half a
22
+ * sheet cannot carry on every request: the chronicle, the whole NPC records,
23
+ * the story blueprint, and the position on demand.
15
24
  */
16
25
  export default gameSlot.tool({
17
26
  description:
18
- "Returns the full current game state, and where the story is. Call this at the start of every turn, before narrating or rolling, and treat the returned values as ground truth — never guess or remember stats from previous turns.",
27
+ "Returns the FULL current game state — including the chronicle, the whole NPC records and the story blueprint — and where the story is. The tracks, momentum, clocks and cast are already in your instructions and refreshed every turn, so reach for this when you want the rest of the board or the position restated, not as a matter of routine.",
19
28
  execute: (_args, game, ctx) => ({
20
29
  // The position SPREAD rather than renamed. `at`/`next`/`storyOver` said the
21
30
  // same three things a gated tool's result already carries as `state`,
@@ -15,7 +15,7 @@ import {
15
15
  } from "@alexkroman1/aai/testing";
16
16
  import { isToolFailure, type ToolFailure } from "@alexkroman1/aai/utils";
17
17
  import { describe, expect, test } from "vitest";
18
-
18
+ import { retrieve } from "./knowledge.ts";
19
19
  import { MAX_ATTEMPTS, runCorrectiveRag } from "./procedure.ts";
20
20
  import {
21
21
  ANSWER_SYSTEM,
@@ -24,7 +24,7 @@ import {
24
24
  GROUNDED_SYSTEM,
25
25
  REWRITE_SYSTEM,
26
26
  } from "./prompts.ts";
27
- import { ASKED_CAP, retrieve, supportProjection, supportSlot, supportView } from "./shared.ts";
27
+ import { ASKED_CAP, supportProjection, supportSlot, supportView } from "./shared.ts";
28
28
  /** TYPE-only, so nothing here re-registers a tool module: the defs under test
29
29
  * still come from `agentDef`, which is what a deploy resolves. */
30
30
  import type AnswerQuestion from "./tools/answer_question.ts";
@@ -169,7 +169,7 @@ function phases(calls: string[]): string[] {
169
169
 
170
170
  // ─── 1. The retriever ────────────────────────────────────────────────────────
171
171
 
172
- describe("retrieval (shared.ts)", () => {
172
+ describe("retrieval (knowledge.ts)", () => {
173
173
  test("ranks the document a caller's words actually point at", () => {
174
174
  expect(retrieve("my broadband light is red")[0]?.doc.id).toBe("D1");
175
175
  expect(retrieve("nobody was home for the engineer")[0]?.doc.id).toBe("D6");
@@ -4,7 +4,7 @@ import { PRODUCT, supportProjection } from "./shared.ts";
4
4
  /**
5
5
  * A support line that grades its own retrieval before it speaks — the
6
6
  * self-RAG / CRAG graph, ported to voice. `procedure.ts` holds the loop, `prompts.ts`
7
- * the attribution and the graders, `shared.ts` the knowledge base and why its
7
+ * the attribution and the graders, `knowledge.ts` the knowledge base and why its
8
8
  * retriever is lexical.
9
9
  *
10
10
  * **Why this shape is worth the model calls on a phone line.** A naive RAG voice
@@ -18,6 +18,10 @@ import { PRODUCT, supportProjection } from "./shared.ts";
18
18
  */
19
19
  export default agent({
20
20
  name: `${PRODUCT} Support`,
21
+ // For a reader of a LIST of agents, not for the model. It says what the line
22
+ // does with a question it cannot answer, because that is the half a caller
23
+ // reading a directory wants to know.
24
+ description: `Answers ${PRODUCT} support questions from a graded knowledge base, and logs a ticket when it cannot`,
21
25
  // The trace exists before the first tool call, so a resumed connection has
22
26
  // something to project.
23
27
  // The projection is also the privacy boundary: a logged ticket carries the
@@ -0,0 +1,165 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * The knowledge base and the retriever over it.
4
+ *
5
+ * **Split from `shared.ts` to keep `knowledge.json` out of the browser
6
+ * bundle.** The index below is built at MODULE SCOPE — `for (const doc of
7
+ * DOCS)` runs on import — so every document was reachable from any module that
8
+ * touched this file, and `client.tsx` touches `shared.ts` for its view. Measured
9
+ * before this split: the full text of every article was present in the built
10
+ * client bundle.
11
+ *
12
+ * `shared.ts` keeps `PRODUCT` alone, as a named import off the same JSON, so the
13
+ * browser still derives the tab title from the knowledge base without taking
14
+ * the articles with it. Everything that reads `docs` lives here, and the browser
15
+ * never imports this module.
16
+ *
17
+ * **The retriever is lexical, and that is a deliberate difference from the
18
+ * notebooks this template ports.** Their self-RAG and CRAG graphs retrieve from
19
+ * a Chroma vectorstore over OpenAI embeddings; this SDK has no vector store
20
+ * (`ctx.vector` was removed — see the root guide), and a template that needed
21
+ * one would be a template nobody can run. So retrieval here is term overlap
22
+ * with an inverse-document-frequency weight, which is genuinely worse at
23
+ * meaning and genuinely fine at words.
24
+ *
25
+ * That makes the corrective loop MORE valuable rather than less, which is the
26
+ * point worth taking away: CRAG exists because retrieval is imperfect, and a
27
+ * weaker retriever is exactly the case its grader and its query rewriter were
28
+ * designed for. A caller saying "my internet keeps dying at night" retrieves
29
+ * nothing useful by words alone — the rewrite step is what turns it into
30
+ * "evening slowdown congestion peak time" and finds D10.
31
+ */
32
+ import { docs } from "./knowledge.json" with { type: "json" };
33
+
34
+ export interface Doc {
35
+ id: string;
36
+ title: string;
37
+ topic: string;
38
+ text: string;
39
+ }
40
+
41
+ export const DOCS: Doc[] = docs;
42
+
43
+ export const TOPICS: string[] = [...new Set(DOCS.map((doc) => doc.topic))].sort();
44
+
45
+ // ─── Retrieval ───────────────────────────────────────────────────────────────
46
+
47
+ /** Words that match everything and therefore rank nothing. */
48
+ const STOPWORDS = new Set([
49
+ "the",
50
+ "and",
51
+ "for",
52
+ "you",
53
+ "your",
54
+ "are",
55
+ "was",
56
+ "with",
57
+ "that",
58
+ "this",
59
+ "have",
60
+ "has",
61
+ "can",
62
+ "not",
63
+ "but",
64
+ "how",
65
+ "why",
66
+ "what",
67
+ "when",
68
+ "will",
69
+ "from",
70
+ "into",
71
+ "out",
72
+ "get",
73
+ "does",
74
+ "did",
75
+ "any",
76
+ "all",
77
+ "our",
78
+ "their",
79
+ "there",
80
+ "then",
81
+ "than",
82
+ "about",
83
+ "just",
84
+ "been",
85
+ "were",
86
+ "they",
87
+ "them",
88
+ "his",
89
+ "her",
90
+ "its",
91
+ "one",
92
+ "two",
93
+ "who",
94
+ "whom",
95
+ "some",
96
+ ]);
97
+
98
+ function tokenize(text: string): string[] {
99
+ return text
100
+ .toLowerCase()
101
+ .split(/[^a-z0-9]+/)
102
+ .filter((word) => word.length > 2 && !STOPWORDS.has(word));
103
+ }
104
+
105
+ /**
106
+ * Term → how many documents contain it, and per document, term → how often it
107
+ * occurs. Both computed once at module load, in the one pass that has to visit
108
+ * every token anyway.
109
+ *
110
+ * The per-document COUNTS are what scoring needs. Keeping the raw token list
111
+ * instead made `retrieve` walk it end to end once per query term, allocating a
112
+ * filtered array each time, to recover a number this loop already had.
113
+ */
114
+ const DOC_FREQUENCY = new Map<string, number>();
115
+ const DOC_TERM_COUNTS = new Map<string, Map<string, number>>();
116
+ for (const doc of DOCS) {
117
+ const counts = new Map<string, number>();
118
+ for (const token of tokenize(`${doc.title} ${doc.topic} ${doc.text}`)) {
119
+ counts.set(token, (counts.get(token) ?? 0) + 1);
120
+ }
121
+ DOC_TERM_COUNTS.set(doc.id, counts);
122
+ for (const term of counts.keys()) {
123
+ DOC_FREQUENCY.set(term, (DOC_FREQUENCY.get(term) ?? 0) + 1);
124
+ }
125
+ }
126
+
127
+ /** How many documents one retrieval returns before grading. */
128
+ export const RETRIEVE_K = 4;
129
+
130
+ export interface Retrieved {
131
+ doc: Doc;
132
+ score: number;
133
+ }
134
+
135
+ /**
136
+ * The `retrieve` node: top-k by idf-weighted term overlap.
137
+ *
138
+ * A term in one document is worth much more than a term in eight — without the
139
+ * weight, "fibre" and "hub" (in nearly every document) drown the one word that
140
+ * actually distinguishes the caller's question.
141
+ */
142
+ export function retrieve(query: string, k: number = RETRIEVE_K): Retrieved[] {
143
+ const terms = new Set(tokenize(query));
144
+ if (terms.size === 0) return [];
145
+ const scored: Retrieved[] = [];
146
+ for (const doc of DOCS) {
147
+ const counts = DOC_TERM_COUNTS.get(doc.id);
148
+ let score = 0;
149
+ for (const term of terms) {
150
+ const hits = counts?.get(term) ?? 0;
151
+ if (hits === 0) continue;
152
+ const frequency = DOC_FREQUENCY.get(term) ?? 1;
153
+ // Diminishing returns per repeat, so one long document cannot win on
154
+ // repetition alone.
155
+ score += Math.log(1 + hits) * Math.log(DOCS.length / frequency + 1);
156
+ }
157
+ if (score > 0) scored.push({ doc, score });
158
+ }
159
+ return scored.sort((a, b) => b.score - a.score).slice(0, k);
160
+ }
161
+
162
+ /** One document as the answer prompt sees it. */
163
+ export function formatDoc(doc: Doc): string {
164
+ return `[${doc.id}] ${doc.title}\n${doc.text}`;
165
+ }
@@ -22,6 +22,8 @@ import type {
22
22
  GenerateResult,
23
23
  GuardrailVerdict,
24
24
  } from "@alexkroman1/aai";
25
+ import type { Doc } from "./knowledge.ts";
26
+ import { formatDoc } from "./knowledge.ts";
25
27
  import {
26
28
  ANSWER_SYSTEM,
27
29
  ANSWERS_SYSTEM,
@@ -31,8 +33,7 @@ import {
31
33
  GROUNDED_SYSTEM,
32
34
  REWRITE_SYSTEM,
33
35
  } from "./prompts.ts";
34
- import type { Doc, GradedDoc } from "./shared.ts";
35
- import { formatDoc } from "./shared.ts";
36
+ import type { GradedDoc } from "./shared.ts";
36
37
 
37
38
  /**
38
39
  * One closed question, asked with the schema that constrains it.
@@ -62,6 +62,8 @@ import {
62
62
  procedure,
63
63
  } from "@alexkroman1/aai";
64
64
  import { assign, fromPromise, setup } from "xstate";
65
+ import type { Doc } from "./knowledge.ts";
66
+ import { retrieve } from "./knowledge.ts";
65
67
  import {
66
68
  generateAnswer,
67
69
  gradeDocuments,
@@ -69,8 +71,7 @@ import {
69
71
  gradeUseful,
70
72
  transformQuery,
71
73
  } from "./nodes.ts";
72
- import type { AnswerTrace, Doc, GradedDoc, TraceStep } from "./shared.ts";
73
- import { retrieve } from "./shared.ts";
74
+ import type { AnswerTrace, GradedDoc, TraceStep } from "./shared.ts";
74
75
 
75
76
  /** Retrieve-and-answer attempts, i.e. one query rewrite. */
76
77
  export const MAX_ATTEMPTS = 2;
@@ -217,7 +218,7 @@ const machine = setup({
217
218
  }),
218
219
  states: {
219
220
  /**
220
- * Retrieval is LEXICAL and synchronous (`shared.ts`), so it is an entry
221
+ * Retrieval is LEXICAL and synchronous (`knowledge.ts`), so it is an entry
221
222
  * action rather than an invoked actor — there is nothing to await.
222
223
  */
223
224
  retrieve: {
@@ -1,20 +1,9 @@
1
1
  /**
2
- * The knowledge base, the retriever, and what the browser is shown.
2
+ * The session's state, the slot, and what the browser is shown.
3
3
  *
4
- * **The retriever is lexical, and that is a deliberate difference from the
5
- * notebooks this template ports.** Their self-RAG and CRAG graphs retrieve from
6
- * a Chroma vectorstore over OpenAI embeddings; this SDK has no vector store
7
- * (`ctx.vector` was removed — see the root guide), and a template that needed
8
- * one would be a template nobody can run. So retrieval here is term overlap
9
- * with an inverse-document-frequency weight, which is genuinely worse at
10
- * meaning and genuinely fine at words.
11
- *
12
- * That makes the corrective loop MORE valuable rather than less, which is the
13
- * point worth taking away: CRAG exists because retrieval is imperfect, and a
14
- * weaker retriever is exactly the case its grader and its query rewriter were
15
- * designed for. A caller saying "my internet keeps dying at night" retrieves
16
- * nothing useful by words alone — the rewrite step is what turns it into
17
- * "evening slowdown congestion peak time" and finds D10.
4
+ * The knowledge base and its retriever moved to `knowledge.ts` so that
5
+ * `client.tsx`, which imports this module for its view, does not take the
6
+ * articles with it.
18
7
  */
19
8
 
20
9
  import {
@@ -23,141 +12,16 @@ import {
23
12
  type StateProjection,
24
13
  sessionSlot,
25
14
  } from "@alexkroman1/aai";
26
- import knowledge from "./knowledge.json" with { type: "json" };
27
-
28
- export interface Doc {
29
- id: string;
30
- title: string;
31
- topic: string;
32
- text: string;
33
- }
34
-
35
- export const PRODUCT: string = knowledge.product;
36
- export const DOCS: Doc[] = knowledge.docs;
37
-
38
- export const TOPICS: string[] = [...new Set(DOCS.map((doc) => doc.topic))].sort();
39
-
40
- // ─── Retrieval ───────────────────────────────────────────────────────────────
41
-
42
- /** Words that match everything and therefore rank nothing. */
43
- const STOPWORDS = new Set([
44
- "the",
45
- "and",
46
- "for",
47
- "you",
48
- "your",
49
- "are",
50
- "was",
51
- "with",
52
- "that",
53
- "this",
54
- "have",
55
- "has",
56
- "can",
57
- "not",
58
- "but",
59
- "how",
60
- "why",
61
- "what",
62
- "when",
63
- "will",
64
- "from",
65
- "into",
66
- "out",
67
- "get",
68
- "does",
69
- "did",
70
- "any",
71
- "all",
72
- "our",
73
- "their",
74
- "there",
75
- "then",
76
- "than",
77
- "about",
78
- "just",
79
- "been",
80
- "were",
81
- "they",
82
- "them",
83
- "his",
84
- "her",
85
- "its",
86
- "one",
87
- "two",
88
- "who",
89
- "whom",
90
- "some",
91
- ]);
92
-
93
- function tokenize(text: string): string[] {
94
- return text
95
- .toLowerCase()
96
- .split(/[^a-z0-9]+/)
97
- .filter((word) => word.length > 2 && !STOPWORDS.has(word));
98
- }
15
+ import { product } from "./knowledge.json" with { type: "json" };
99
16
 
100
17
  /**
101
- * Term → how many documents contain it, and per document, term → how often it
102
- * occurs. Both computed once at module load, in the one pass that has to visit
103
- * every token anyway.
18
+ * The product this desk supports.
104
19
  *
105
- * The per-document COUNTS are what scoring needs. Keeping the raw token list
106
- * instead made `retrieve` walk it end to end once per query term, allocating a
107
- * filtered array each time, to recover a number this loop already had.
20
+ * A NAMED import off `knowledge.json`, not a property of the whole object: the
21
+ * browser imports this module and must not take `docs` with it. `knowledge.ts`
22
+ * holds the articles.
108
23
  */
109
- const DOC_FREQUENCY = new Map<string, number>();
110
- const DOC_TERM_COUNTS = new Map<string, Map<string, number>>();
111
- for (const doc of DOCS) {
112
- const counts = new Map<string, number>();
113
- for (const token of tokenize(`${doc.title} ${doc.topic} ${doc.text}`)) {
114
- counts.set(token, (counts.get(token) ?? 0) + 1);
115
- }
116
- DOC_TERM_COUNTS.set(doc.id, counts);
117
- for (const term of counts.keys()) {
118
- DOC_FREQUENCY.set(term, (DOC_FREQUENCY.get(term) ?? 0) + 1);
119
- }
120
- }
121
-
122
- /** How many documents one retrieval returns before grading. */
123
- export const RETRIEVE_K = 4;
124
-
125
- export interface Retrieved {
126
- doc: Doc;
127
- score: number;
128
- }
129
-
130
- /**
131
- * The `retrieve` node: top-k by idf-weighted term overlap.
132
- *
133
- * A term in one document is worth much more than a term in eight — without the
134
- * weight, "fibre" and "hub" (in nearly every document) drown the one word that
135
- * actually distinguishes the caller's question.
136
- */
137
- export function retrieve(query: string, k: number = RETRIEVE_K): Retrieved[] {
138
- const terms = new Set(tokenize(query));
139
- if (terms.size === 0) return [];
140
- const scored: Retrieved[] = [];
141
- for (const doc of DOCS) {
142
- const counts = DOC_TERM_COUNTS.get(doc.id);
143
- let score = 0;
144
- for (const term of terms) {
145
- const hits = counts?.get(term) ?? 0;
146
- if (hits === 0) continue;
147
- const frequency = DOC_FREQUENCY.get(term) ?? 1;
148
- // Diminishing returns per repeat, so one long document cannot win on
149
- // repetition alone.
150
- score += Math.log(1 + hits) * Math.log(DOCS.length / frequency + 1);
151
- }
152
- if (score > 0) scored.push({ doc, score });
153
- }
154
- return scored.sort((a, b) => b.score - a.score).slice(0, k);
155
- }
156
-
157
- /** One document as the answer prompt sees it. */
158
- export function formatDoc(doc: Doc): string {
159
- return `[${doc.id}] ${doc.title}\n${doc.text}`;
160
- }
24
+ export const PRODUCT: string = product;
161
25
 
162
26
  // ─── The trace ───────────────────────────────────────────────────────────────
163
27
  // Their graph is watched by streaming node names to a notebook. A caller hears
@@ -1,5 +1,6 @@
1
1
  import { tool } from "@alexkroman1/aai";
2
- import { DOCS, PRODUCT, TOPICS } from "../shared.ts";
2
+ import { DOCS, TOPICS } from "../knowledge.ts";
3
+ import { PRODUCT } from "../shared.ts";
3
4
 
4
5
  /**
5
6
  * What the knowledge base covers.