@alexkroman1/aai-cli 16.1.0 → 18.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.
- package/README.md +2 -1
- package/dist/{_build-target-ClEEuUuW.mjs → _build-target-C08aM-Es.mjs} +504 -43
- package/dist/_build-target.d.ts +98 -19
- package/dist/_console-audio.d.ts +17 -0
- package/dist/_console-session.d.ts +70 -0
- package/dist/_deno-target.d.ts +15 -14
- package/dist/_dev-env.d.ts +19 -13
- package/dist/{_dev-server-D1wKiA0_.mjs → _dev-server-Dtp4aAlo.mjs} +26 -18
- package/dist/_dev-server.d.ts +5 -3
- package/dist/_init.d.ts +39 -0
- package/dist/_modal-target.d.ts +11 -6
- package/dist/_preflight-CnW9QiE7.mjs +116 -0
- package/dist/_preflight.d.ts +110 -5
- package/dist/_target-bundle.d.ts +112 -0
- package/dist/_target-entry.d.ts +81 -0
- package/dist/_templates-DXadVNsL.mjs +135 -0
- package/dist/_templates.d.ts +11 -34
- package/dist/{_vitest-runner-BiAMIir1.mjs → _vitest-runner-CZNGj0ZC.mjs} +21 -16
- package/dist/_vitest-runner.d.ts +35 -23
- package/dist/{build-O6BT51x_.mjs → build-DrQTSc2R.mjs} +128 -293
- package/dist/build.d.ts +34 -4
- package/dist/cli.mjs +40 -16
- package/dist/console-BsyE3DyB.mjs +422 -0
- package/dist/console.d.ts +37 -0
- package/dist/{deploy-lldQyJVj.mjs → deploy-B68-x7xM.mjs} +12 -4
- package/dist/deploy.d.ts +9 -0
- package/dist/{dev-Du8pCWFq.mjs → dev-BGWU2zPP.mjs} +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/{eval-Ducmkt1n.mjs → eval-DB07kTxO.mjs} +1 -1
- package/dist/init-CbOhyNYe.mjs +559 -0
- package/dist/init.d.ts +43 -3
- package/dist/scaffold/CLAUDE.md +161 -166
- package/dist/scaffold/package.json +6 -6
- package/dist/scaffold/vite.config.ts +29 -1
- package/dist/start.d.ts +3 -3
- package/dist/{studio-It7SRfUN.mjs → studio-BRJsw7lr.mjs} +19 -9
- package/dist/templates/applicant-screening-agent/agent.eval.test.ts +20 -6
- package/dist/templates/applicant-screening-agent/agent.test.ts +17 -13
- package/dist/templates/applicant-screening-agent/agent.ts +28 -0
- package/dist/templates/applicant-screening-agent/crews.ts +4 -4
- package/dist/templates/applicant-screening-agent/shared.ts +11 -11
- package/dist/templates/call-audit-workflow/agent.ts +2 -0
- package/dist/templates/code-interpreter-agent/agent.eval.test.ts +3 -2
- package/dist/templates/code-interpreter-agent/agent.test.ts +2 -2
- package/dist/templates/code-interpreter-agent/agent.ts +1 -0
- package/dist/templates/coding-agent/agent.eval.test.ts +136 -0
- package/dist/templates/coding-agent/agent.test.ts +109 -0
- package/dist/templates/coding-agent/agent.ts +45 -0
- package/dist/templates/coding-agent/chat.ts +63 -0
- package/dist/templates/coding-agent/shared.ts +46 -0
- package/dist/templates/coding-agent/system-prompt.md +32 -0
- package/dist/templates/coding-agent/tools/bash.ts +6 -0
- package/dist/templates/coding-agent/tools/delete_file.ts +6 -0
- package/dist/templates/coding-agent/tools/edit_file.ts +6 -0
- package/dist/templates/coding-agent/tools/glob.ts +6 -0
- package/dist/templates/coding-agent/tools/grep.ts +6 -0
- package/dist/templates/coding-agent/tools/list_files.ts +6 -0
- package/dist/templates/coding-agent/tools/read_file.ts +6 -0
- package/dist/templates/coding-agent/tools/todo_write.ts +6 -0
- package/dist/templates/coding-agent/tools/write_file.ts +6 -0
- package/dist/templates/custom-pipeline-agent/agent.ts +3 -2
- package/dist/templates/custom-pipeline-agent/modes.test.ts +4 -4
- package/dist/templates/custom-pipeline-agent/stages.test.ts +75 -83
- package/dist/templates/document-redline-workflow/agent.ts +2 -0
- package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +1 -1
- package/dist/templates/emergency-dispatch-agent/agent.test.ts +103 -0
- package/dist/templates/emergency-dispatch-agent/agent.ts +15 -0
- package/dist/templates/emergency-dispatch-agent/guardrails.ts +105 -0
- package/dist/templates/emergency-dispatch-agent/system-prompt.md +1 -0
- package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +9 -2
- package/dist/templates/entertainment-picks-agent/agent.ts +1 -0
- package/dist/templates/entertainment-picks-agent/system-prompt.md +6 -0
- package/dist/templates/entertainment-picks-agent/tools/revisit.ts +7 -0
- package/dist/templates/executive-inbox-agent/agent.eval.test.ts +84 -23
- package/dist/templates/executive-inbox-agent/agent.test.ts +35 -25
- package/dist/templates/executive-inbox-agent/agent.ts +1 -0
- package/dist/templates/executive-inbox-agent/calendar.test.ts +13 -7
- package/dist/templates/executive-inbox-agent/meeting.ts +3 -3
- package/dist/templates/executive-inbox-agent/prompts.ts +3 -1
- package/dist/templates/executive-inbox-agent/system-prompt.md +3 -3
- package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +3 -3
- package/dist/templates/executive-inbox-agent/tools/open_email.ts +8 -16
- package/dist/templates/front-desk-agent/agent.eval.test.ts +174 -0
- package/dist/templates/front-desk-agent/agent.test.ts +150 -0
- package/dist/templates/front-desk-agent/agent.ts +22 -0
- package/dist/templates/front-desk-agent/shared.ts +234 -0
- package/dist/templates/front-desk-agent/system-prompt.md +13 -0
- package/dist/templates/front-desk-agent/tools/verify_account.ts +41 -0
- package/dist/templates/hotel-reception-agent/agent.eval.test.ts +85 -21
- package/dist/templates/hotel-reception-agent/agent.test.ts +3 -3
- package/dist/templates/hotel-reception-agent/agent.ts +6 -3
- package/dist/templates/hotel-reception-agent/client.tsx +14 -2
- package/dist/templates/hotel-reception-agent/concierge.ts +2 -1
- package/dist/templates/hotel-reception-agent/desk-seams.test.ts +3 -3
- package/dist/templates/hotel-reception-agent/disputes.ts +9 -11
- package/dist/templates/hotel-reception-agent/events.ts +2 -1
- package/dist/templates/hotel-reception-agent/session.ts +56 -0
- package/dist/templates/hotel-reception-agent/shared.ts +20 -21
- package/dist/templates/hotel-reception-agent/system-prompt.md +1 -1
- package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/check_restaurant_availability.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/check_room_availability.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/choose_room.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/lookup_guest_history.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/lookup_restaurant_reservation.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/record_card.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/record_followup.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/set_extras.ts +1 -1
- package/dist/templates/hotel-reception-agent/tools/set_stay.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/transfer_call.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/update_card.ts +2 -1
- package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +2 -1
- package/dist/templates/link-digest-workflow/agent.eval.test.ts +16 -1
- package/dist/templates/link-digest-workflow/agent.ts +5 -0
- package/dist/templates/medication-safety-agent/agent.test.ts +57 -4
- package/dist/templates/medication-safety-agent/agent.ts +48 -1
- package/dist/templates/meeting-recap-agent/agent.test.ts +2 -2
- package/dist/templates/meeting-recap-agent/agent.ts +4 -0
- package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +68 -2
- package/dist/templates/pizza-ordering-agent/agent.ts +3 -0
- package/dist/templates/podcast-digest-workflow/agent.ts +4 -0
- package/dist/templates/push-to-talk-agent/agent.eval.test.ts +74 -0
- package/dist/templates/push-to-talk-agent/agent.test.ts +61 -0
- package/dist/templates/push-to-talk-agent/agent.ts +22 -0
- package/dist/templates/push-to-talk-agent/client.tsx +124 -0
- package/dist/templates/push-to-talk-agent/shared.ts +34 -0
- package/dist/templates/push-to-talk-agent/system-prompt.md +11 -0
- package/dist/templates/push-to-talk-agent/tools/list_notes.ts +15 -0
- package/dist/templates/push-to-talk-agent/tools/save_note.ts +26 -0
- package/dist/templates/quickstart-agent/agent.eval.test.ts +91 -3
- package/dist/templates/quickstart-agent/agent.test.ts +22 -0
- package/dist/templates/quickstart-agent/agent.ts +18 -2
- package/dist/templates/quickstart-agent/system-prompt.md +8 -0
- package/dist/templates/quickstart-agent/tools/get_weather.ts +59 -0
- package/dist/templates/research-handoff-agent/agent.eval.test.ts +1 -1
- package/dist/templates/research-handoff-agent/agent.test.ts +34 -26
- package/dist/templates/research-handoff-agent/agent.ts +4 -0
- package/dist/templates/research-planner-agent/agent.eval.test.ts +24 -2
- package/dist/templates/research-planner-agent/agent.test.ts +26 -16
- package/dist/templates/research-planner-agent/agent.ts +3 -0
- package/dist/templates/research-planner-agent/system-prompt.md +1 -1
- package/dist/templates/retail-orders-agent/agent.eval.test.ts +1 -1
- package/dist/templates/retail-orders-agent/agent.ts +32 -3
- package/dist/templates/retail-orders-agent/keyterms.ts +154 -0
- package/dist/templates/retail-orders-agent/resolve.ts +18 -3
- package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +124 -5
- package/dist/templates/roadside-assistance-agent/agent.test.ts +39 -7
- package/dist/templates/roadside-assistance-agent/agent.ts +4 -0
- package/dist/templates/roadside-assistance-agent/shared.ts +12 -0
- package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +14 -0
- package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +11 -0
- package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +17 -11
- package/dist/templates/roadside-assistance-agent/yard.test.ts +4 -0
- package/dist/templates/spoken-summary-workflow/agent.ts +4 -0
- package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +6 -0
- package/dist/templates/tabletop-rpg-agent/agent.test.ts +125 -1
- package/dist/templates/tabletop-rpg-agent/agent.ts +30 -1
- package/dist/templates/tabletop-rpg-agent/shared.ts +81 -0
- package/dist/templates/tabletop-rpg-agent/system-prompt.md +1 -1
- package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +16 -7
- package/dist/templates/technical-support-agent/agent.test.ts +29 -23
- package/dist/templates/technical-support-agent/agent.ts +5 -1
- package/dist/templates/technical-support-agent/knowledge.ts +165 -0
- package/dist/templates/technical-support-agent/nodes.ts +3 -2
- package/dist/templates/technical-support-agent/procedure.ts +7 -6
- package/dist/templates/technical-support-agent/shared.ts +10 -146
- package/dist/templates/technical-support-agent/tools/list_topics.ts +2 -1
- package/dist/templates/text-adventure-agent/agent.eval.test.ts +39 -6
- package/dist/templates/text-adventure-agent/agent.test.ts +79 -1
- package/dist/templates/text-adventure-agent/agent.ts +30 -1
- package/dist/templates/text-adventure-agent/shared.ts +37 -0
- package/dist/templates/text-adventure-agent/system-prompt.md +9 -2
- package/dist/templates/topic-briefing-agent/agent.eval.test.ts +18 -4
- package/dist/templates/topic-briefing-agent/agent.test.ts +61 -36
- package/dist/templates/topic-briefing-agent/agent.ts +4 -1
- package/dist/templates/topic-briefing-agent/shared.ts +19 -18
- package/dist/templates/topic-briefing-agent/system-prompt.md +13 -8
- package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +43 -5
- package/dist/templates/transcription-workflow/agent.ts +3 -0
- package/dist/templates/travel-concierge-agent/agent.eval.test.ts +9 -7
- package/dist/templates/travel-concierge-agent/agent.test.ts +1 -2
- package/dist/templates/travel-concierge-agent/agent.ts +4 -0
- package/dist/templates/web-research-agent/agent.eval.test.ts +31 -5
- package/dist/templates/web-research-agent/agent.test.ts +16 -0
- package/dist/templates/web-research-agent/agent.ts +30 -0
- package/dist/templates/web-research-agent/system-prompt.md +8 -2
- package/dist/templates/word-game-agent/agent.eval.test.ts +79 -18
- package/dist/templates/word-game-agent/agent.test.ts +3 -1
- package/dist/templates/word-game-agent/agent.ts +20 -0
- package/dist/test-CjKPQ9_B.mjs +102 -0
- package/dist/test.d.ts +37 -12
- package/package.json +5 -5
- package/dist/_init-Bp1CjRrU.mjs +0 -199
- package/dist/_preflight-CcAR577V.mjs +0 -46
- package/dist/_templates-CuP74F8D.mjs +0 -291
- package/dist/init-CY4NAXAA.mjs +0 -183
- package/dist/test-PHHv0Vj6.mjs +0 -83
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
/** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
|
|
2
2
|
import agentDef from "virtual:aai/agent";
|
|
3
|
-
import type {
|
|
3
|
+
import type {
|
|
4
|
+
AgentSessionContext,
|
|
5
|
+
InferToolInput,
|
|
6
|
+
RandomSource,
|
|
7
|
+
SlotHolder,
|
|
8
|
+
} from "@alexkroman1/aai";
|
|
4
9
|
import { createSeededRandom, isToolFailure } from "@alexkroman1/aai";
|
|
5
10
|
import {
|
|
6
11
|
createToolContext,
|
|
@@ -20,6 +25,7 @@ import {
|
|
|
20
25
|
gameView,
|
|
21
26
|
inCrisis,
|
|
22
27
|
isGameOver,
|
|
28
|
+
liveSheet,
|
|
23
29
|
MAX_LOG_ENTRIES,
|
|
24
30
|
MAX_NPCS,
|
|
25
31
|
MIN_MOMENTUM,
|
|
@@ -894,3 +900,121 @@ describe("the story flow", () => {
|
|
|
894
900
|
// restored rather than recomputed) has no path left to exercise it: a session
|
|
895
901
|
// is the whole life of a game now.
|
|
896
902
|
});
|
|
903
|
+
|
|
904
|
+
// ── The prompt carries the sheet ─────────────────────────────────────────────
|
|
905
|
+
//
|
|
906
|
+
// `systemPrompt` is a RESOLVER here: `system-prompt.md` supplies the rules and
|
|
907
|
+
// `liveSheet` appends the campaign as it stands before every model request.
|
|
908
|
+
// What that replaced was FLOW rule 1 — "call check_state as your FIRST tool
|
|
909
|
+
// call every turn" — a model round trip in front of every turn of a live voice
|
|
910
|
+
// game, enforced by nothing.
|
|
911
|
+
|
|
912
|
+
describe("the campaign sheet the narrator is given", () => {
|
|
913
|
+
/** The def's resolver, which is what a request assembles the instructions from. */
|
|
914
|
+
const resolve = (ctx: AgentSessionContext): string => {
|
|
915
|
+
const prompt = agentDef.systemPrompt;
|
|
916
|
+
if (typeof prompt !== "function") throw new Error("systemPrompt is not a resolver");
|
|
917
|
+
return prompt(ctx);
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
test("it is a resolver, and the rules file survives into it", () => {
|
|
921
|
+
// The build discovers `system-prompt.md` and hands it to `withSystemPrompt`,
|
|
922
|
+
// which leaves a resolver alone — so the file reaches the model through the
|
|
923
|
+
// resolver's own import, and this is what proves it does.
|
|
924
|
+
expect(typeof agentDef.systemPrompt).toBe("function");
|
|
925
|
+
expect(resolve(createToolContext())).toContain("CORE MECHANIC - ACTION ROLL");
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
test("before setup it says so, rather than printing an empty sheet", () => {
|
|
929
|
+
const ctx = createToolContext();
|
|
930
|
+
const sheet = liveSheet(gameSlot.get(ctx));
|
|
931
|
+
expect(sheet).toContain("no character yet");
|
|
932
|
+
expect(sheet).toContain("setup_character");
|
|
933
|
+
// The tracks of a campaign that does not exist would read as a live sheet.
|
|
934
|
+
// (Asserted on the sheet, not the whole prompt: the rules file has its own
|
|
935
|
+
// MOMENTUM section and always will.)
|
|
936
|
+
expect(sheet).not.toContain("Momentum");
|
|
937
|
+
expect(resolve(ctx).endsWith(sheet)).toBe(true);
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
test("a roll's consequences are in the NEXT request's prompt, with no tool call in between", async () => {
|
|
941
|
+
const ctx = createToolContext();
|
|
942
|
+
seedPlaying(ctx);
|
|
943
|
+
// A MISS: the tracks and the momentum move, and the chaos factor with them.
|
|
944
|
+
const before = resolve(ctx);
|
|
945
|
+
expect(before).toContain(`Momentum ${DEFAULT_STATE.momentum}`);
|
|
946
|
+
|
|
947
|
+
expectToolOk(
|
|
948
|
+
await run(
|
|
949
|
+
"action_roll",
|
|
950
|
+
{ move: "face_danger", stat: "iron", position: "desperate", effect: "standard" },
|
|
951
|
+
createToolContext({ ...ctx, random: dice(1, 1, 10, 10) }),
|
|
952
|
+
),
|
|
953
|
+
);
|
|
954
|
+
|
|
955
|
+
const after = resolve(ctx);
|
|
956
|
+
const game = gameSlot.get(ctx);
|
|
957
|
+
expect(after).toContain(`Momentum ${game.momentum}`);
|
|
958
|
+
expect(after).toContain(`chaos factor ${game.chaosFactor}`);
|
|
959
|
+
expect(after).toContain(`Health ${game.health}/`);
|
|
960
|
+
// And the burn window, which is the one thing the narrator most often lost
|
|
961
|
+
// track of between turns.
|
|
962
|
+
expect(after).toContain("burn_momentum can still upgrade it");
|
|
963
|
+
});
|
|
964
|
+
|
|
965
|
+
test("the cast, the clocks and the act are all on it", () => {
|
|
966
|
+
const ctx = createToolContext();
|
|
967
|
+
const state = playingState();
|
|
968
|
+
state.playerName = "Kael";
|
|
969
|
+
state.currentLocation = "Ashfall Keep";
|
|
970
|
+
state.clocks[0]!.filled = 2;
|
|
971
|
+
state.storyBlueprint = {
|
|
972
|
+
structureType: "3act",
|
|
973
|
+
centralConflict: "c",
|
|
974
|
+
antagonistForce: "a",
|
|
975
|
+
thematicThread: "t",
|
|
976
|
+
currentAct: 2,
|
|
977
|
+
storyComplete: false,
|
|
978
|
+
acts: [
|
|
979
|
+
{ phase: "setup", title: "One", goal: "g1", mood: "m1", transitionTrigger: "t1" },
|
|
980
|
+
{ phase: "turn", title: "Two", goal: "g2", mood: "m2", transitionTrigger: "t2" },
|
|
981
|
+
],
|
|
982
|
+
};
|
|
983
|
+
seedPlaying(ctx, state);
|
|
984
|
+
|
|
985
|
+
const sheet = resolve(ctx);
|
|
986
|
+
expect(sheet).toContain("Kael");
|
|
987
|
+
expect(sheet).toContain("Doom 2/4 (threat)");
|
|
988
|
+
expect(sheet).toContain("Mira (neutral, bond 0)");
|
|
989
|
+
expect(sheet).toContain("Act 2 of 2 (turn)");
|
|
990
|
+
});
|
|
991
|
+
|
|
992
|
+
test("crisis and game over are DERIVED, so an emptied track cannot read as survivable", () => {
|
|
993
|
+
const ctx = createToolContext();
|
|
994
|
+
const hurt = playingState();
|
|
995
|
+
hurt.spirit = 0;
|
|
996
|
+
seedPlaying(ctx, hurt);
|
|
997
|
+
expect(liveSheet(gameSlot.get(ctx))).toContain("CRISIS");
|
|
998
|
+
expect(inCrisis(gameSlot.get(ctx))).toBe(true);
|
|
999
|
+
|
|
1000
|
+
const dead = playingState();
|
|
1001
|
+
dead.health = 0;
|
|
1002
|
+
dead.spirit = 0;
|
|
1003
|
+
seedPlaying(ctx, dead);
|
|
1004
|
+
expect(liveSheet(gameSlot.get(ctx))).toContain("GAME OVER");
|
|
1005
|
+
expect(isGameOver(gameSlot.get(ctx))).toBe(true);
|
|
1006
|
+
});
|
|
1007
|
+
|
|
1008
|
+
test("each session is told its OWN campaign", () => {
|
|
1009
|
+
// The resolver reads through `ctx.slots`, so it is per session for the same
|
|
1010
|
+
// reason every tool is.
|
|
1011
|
+
const one = createToolContext();
|
|
1012
|
+
const two = createToolContext();
|
|
1013
|
+
const named = playingState();
|
|
1014
|
+
named.playerName = "Kael";
|
|
1015
|
+
seedPlaying(one, named);
|
|
1016
|
+
|
|
1017
|
+
expect(resolve(one)).toContain("Kael");
|
|
1018
|
+
expect(resolve(two)).toContain("no character yet");
|
|
1019
|
+
});
|
|
1020
|
+
});
|
|
@@ -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.
|
|
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`** —
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* `research-planner-agent`'s `plan_status` does: the
|
|
13
|
-
* rather than from a second reading of the
|
|
14
|
-
* character yet" is the same fact here as the
|
|
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
|
|
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,
|
|
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";
|
|
@@ -80,27 +80,33 @@ function scriptedModel(script: Script = {}) {
|
|
|
80
80
|
};
|
|
81
81
|
|
|
82
82
|
const { generate } = stubGenerate({
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
83
|
+
routes: {
|
|
84
|
+
[DOC_GRADER_SYSTEM]: (call) => {
|
|
85
|
+
const id = /\[(D\d+)\]/.exec(call.prompt)?.[1] ?? "?";
|
|
86
|
+
calls.push(`grade_documents:${id}`);
|
|
87
|
+
const pass = script.relevant ? script.relevant(id, attempt) : true;
|
|
88
|
+
return { object: { score: pass ? "yes" : "no", reason: `graded ${id}` } };
|
|
89
|
+
},
|
|
90
|
+
[REWRITE_SYSTEM]: () => {
|
|
91
|
+
calls.push("transform_query");
|
|
92
|
+
attempt++;
|
|
93
|
+
return script.rewrite ?? "rewritten query";
|
|
94
|
+
},
|
|
95
|
+
[ANSWER_SYSTEM]: () => {
|
|
96
|
+
calls.push("generate");
|
|
97
|
+
return answers.shift() ?? "The documented answer.";
|
|
98
|
+
},
|
|
99
|
+
[GROUNDED_SYSTEM]: verdictRoute(
|
|
100
|
+
"grade_generation_v_documents",
|
|
101
|
+
grounded,
|
|
102
|
+
"not in the documents",
|
|
103
|
+
),
|
|
104
|
+
[ANSWERS_SYSTEM]: verdictRoute(
|
|
105
|
+
"grade_generation_v_question",
|
|
106
|
+
useful,
|
|
107
|
+
"answers something else",
|
|
108
|
+
),
|
|
93
109
|
},
|
|
94
|
-
[ANSWER_SYSTEM]: () => {
|
|
95
|
-
calls.push("generate");
|
|
96
|
-
return answers.shift() ?? "The documented answer.";
|
|
97
|
-
},
|
|
98
|
-
[GROUNDED_SYSTEM]: verdictRoute(
|
|
99
|
-
"grade_generation_v_documents",
|
|
100
|
-
grounded,
|
|
101
|
-
"not in the documents",
|
|
102
|
-
),
|
|
103
|
-
[ANSWERS_SYSTEM]: verdictRoute("grade_generation_v_question", useful, "answers something else"),
|
|
104
110
|
});
|
|
105
111
|
|
|
106
112
|
return { generate, calls };
|
|
@@ -169,7 +175,7 @@ function phases(calls: string[]): string[] {
|
|
|
169
175
|
|
|
170
176
|
// ─── 1. The retriever ────────────────────────────────────────────────────────
|
|
171
177
|
|
|
172
|
-
describe("retrieval (
|
|
178
|
+
describe("retrieval (knowledge.ts)", () => {
|
|
173
179
|
test("ranks the document a caller's words actually point at", () => {
|
|
174
180
|
expect(retrieve("my broadband light is red")[0]?.doc.id).toBe("D1");
|
|
175
181
|
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, `
|
|
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 {
|
|
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.
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
*/
|
|
54
54
|
|
|
55
55
|
import {
|
|
56
|
-
|
|
56
|
+
DEFAULT_GUARDRAIL_MAX_REVISIONS,
|
|
57
57
|
type GenerateFn,
|
|
58
58
|
type GuardrailVerdict,
|
|
59
59
|
omitUndefined,
|
|
@@ -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,21 +71,20 @@ import {
|
|
|
69
71
|
gradeUseful,
|
|
70
72
|
transformQuery,
|
|
71
73
|
} from "./nodes.ts";
|
|
72
|
-
import type { AnswerTrace,
|
|
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;
|
|
77
78
|
/**
|
|
78
79
|
* Regenerations after a "not grounded" verdict, within one attempt.
|
|
79
80
|
*
|
|
80
|
-
* The SDK's own number, not a coincidence: `
|
|
81
|
+
* The SDK's own number, not a coincidence: `DEFAULT_GUARDRAIL_MAX_REVISIONS` is
|
|
81
82
|
* how many times `subagent({ guardrail })` re-asks after a verdict rejects an
|
|
82
83
|
* answer, and that is exactly what this counter bounds — the same judge, the
|
|
83
84
|
* same retry, one layer down. Taking it from the SDK is how the two stay one
|
|
84
85
|
* decision instead of two constants that drift.
|
|
85
86
|
*/
|
|
86
|
-
export const MAX_REGENERATIONS =
|
|
87
|
+
export const MAX_REGENERATIONS = DEFAULT_GUARDRAIL_MAX_REVISIONS;
|
|
87
88
|
|
|
88
89
|
/**
|
|
89
90
|
* What the machine carries: the trace it is building, plus the two counters the
|
|
@@ -217,7 +218,7 @@ const machine = setup({
|
|
|
217
218
|
}),
|
|
218
219
|
states: {
|
|
219
220
|
/**
|
|
220
|
-
* Retrieval is LEXICAL and synchronous (`
|
|
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: {
|