-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclasses.ts
More file actions
2577 lines (2323 loc) · 95.6 KB
/
Copy pathclasses.ts
File metadata and controls
2577 lines (2323 loc) · 95.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import clone from "just-clone";
import { describeTag, parseTags, TagType, unfoldTags } from "../parsetags";
import { TemplateFalse, TemplateTrue, tmpl } from "../template";
import {
ChatType,
EntityId,
isPerson,
isPromptRequest,
isRoom,
isStoryActionAttempt,
isStoryDescription,
isStoryDialog,
MessageType,
PersonScheduledEventType,
PersonScheduleTemplateType,
ScheduleId,
StoryActionType,
StoryEventType,
StoryEventWithPositionsType,
type ActionRequestType,
type ChangesType,
type ChangeType,
} from "../types";
import { historyForEntity as computeHistoryForEntity } from "./history";
import { coerceBoolean, coerceNumber, fixupText } from "./coerce";
import type { Model } from "./model";
import { mysteryTriggers } from "./mysteries";
import { pathTo } from "./pathto";
import { pronounsForGender } from "./pronouns";
import {
intraActivityForTime,
scheduleForTime,
timeAsString,
} from "./scheduler";
import type { World } from "./world";
import { entitiesById, fieldsOf } from "./dynamic";
import { applyTag, type TagContext } from "./tags";
import { todoPrompt } from "./todos";
import { TagStreamParser } from "./tagstream";
export interface EntityInitType {
id: EntityId;
name?: string;
shortDescription?: string;
description?: string;
inside?: EntityId;
color?: string;
invisible?: boolean;
}
export interface ParametersType {
trigger?: string;
/**
* Set on a Person's reaction to a player event, and how much claim they
* have on one of the turn's limited response slots; see lib/game/crowd.ts.
* 3 = in the conversation (spoken to directly, or the player's current
* interlocutor) and guaranteed a turn, never capped. 2 = named in a
* description or action, 1 = overheard undirected speech, 0 = merely
* attentive; these compete for the remaining slots. Absent on scripted
* requests (triggers, ceremonies, wakeups), which are never capped.
*/
reactionPriority?: number;
}
export abstract class Entity<ParametersT extends ParametersType = object> {
name: string = "";
shortDescription: string = "";
description: string = "";
color: string = "text-white";
inside: EntityId | null = null;
invisible: boolean = false;
abstract type: string;
public readonly id: EntityId;
world!: World;
constructor({
id,
name,
shortDescription,
description,
color,
inside,
invisible,
}: EntityInitType) {
this.id = id;
if (name) {
this.name = name;
}
if (shortDescription) {
this.shortDescription = shortDescription;
}
if (description) {
this.description = description;
}
if (color) {
this.color = color;
}
if (inside) {
this.inside = inside;
}
if (invisible !== undefined) {
this.invisible = invisible;
}
}
clone(): this {
const newInstance = new (
this.constructor as new ({ id }: { id: string }) => this
)({
id: this.id,
});
Object.assign(newInstance, this);
return newInstance as this;
}
myRoom(): Room {
if (isRoom(this)) {
return this as Room;
}
const room = this.world.entityRoom(this.id);
if (!room) {
return this.world.getRoom("Void")!;
}
return room;
}
applyChange(changes: ChangeType) {
for (const [key, value] of Object.entries(changes.after)) {
if (
key === "inside" &&
!entitiesById(this.world.entities)[value as EntityId]
) {
console.warn(
`Updating ${this.id}.${key} be inside ${value} but entity does not exist`,
);
continue;
}
if (key === "exits") {
if (!isRoom(this)) {
throw new Error("Tried to update exits on a non-room");
}
const existing = (this as unknown as Room).exits;
let newExits = [...existing];
if (!Array.isArray(value)) {
throw new Error("Exits must be an array");
}
for (const exit of value) {
const existingExit = existing.find((x) => x.roomId === exit.roomId);
if (exit.deleted) {
if (!existingExit) {
console.warn("Tried to delete exit that does not exist", exit);
continue;
}
newExits = newExits.filter((x) => x.roomId !== exit.roomId);
} else {
if (existingExit) {
newExits = newExits.map((x) =>
x.roomId === exit.roomId ? exit : x,
);
} else {
newExits.push(exit);
}
}
fieldsOf(this).exits = newExits;
}
continue;
}
if (key === "attitudes") {
if (!isPerson(this)) {
throw new Error("Tried to update attitudes on a non-person");
}
// Copy-on-write: clone() copies the record by reference, so mutating
// it in place would write folded state into the pristine `original`
// entities that undo and reload re-fold from.
const merged = {
...(fieldsOf(this).attitudes as Record<string, unknown>),
};
for (const [id, attitude] of Object.entries(value)) {
if (attitude === null) {
delete merged[id];
} else {
merged[id] = attitude;
}
}
fieldsOf(this).attitudes = merged;
continue;
}
if (fieldsOf(this)[key] === undefined) {
console.warn(
`Updating ${this.id}.${key} to ${value} but attribute does not exist`,
);
}
fieldsOf(this)[key] = value;
}
}
onStoryEvent(
storyEvent: StoryEventType,
): ActionRequestType<ParametersT>[] | void {
return undefined;
}
makePromptRequest(parameters: ParametersT): ActionRequestType<ParametersT> {
return {
type: "promptRequest",
id: this.id,
parameters,
};
}
async processTag({
tag,
model,
parameters,
storyEvent,
llmResponse,
}: {
tag: TagType;
model: Model;
parameters: ParametersT;
storyEvent: StoryEventType;
llmResponse: string;
}): Promise<StoryEventType> {
// Name the tag rather than the object. The warning is what the evals count
// as a protocol failure, and `console.warn("...", tag)` stringified to
// "Got unexpected tag: [object Object]" — so the one record of what a model
// actually emitted said nothing, at exactly the moment it was being used to
// judge whether that model can run the game.
console.warn(`Got unexpected tag: ${describeTag(tag)}`);
return storyEvent;
}
afterPrompt(storyEvent: StoryEventType): StoryEventType {
return storyEvent;
}
assemblePrompt(parameters: ParametersT): ChatType {
throw new Error("Method not implemented.");
}
additionalPromptInstructions(parameters: ParametersT): string {
return "";
}
/**
* System-prompt content that is fixed for this character.
*
* Prompt caching matches a prefix, so the assembled prompt is ordered
* stable-first: anything that changes between turns belongs in
* volatileSystemInstructions instead, or the cache misses every turn.
*/
additionalSystemInstructions(parameters: ParametersT): string {
return "";
}
/** System-prompt content that changes as the game runs; goes after the fixed part. */
volatileSystemInstructions(parameters: ParametersT): string {
return "";
}
/** This entity's recent history, as chat messages for a prompt. */
historyForEntity({ limit }: { limit?: number } = {}): MessageType[] {
return computeHistoryForEntity(this, { limit });
}
currentLocationPrompt(parameters: ParametersT): string {
const room = this.world.entityRoom(this.id);
if (!room) {
return "Located in an indeterminate location.";
}
return tmpl`
${room.name} (id: ${JSON.stringify(room.id)}) "${room.shortDescription}"
`;
}
currentPeoplePrompt(parameters: ParametersT): string {
const room = this.world.entityRoom(this.id);
if (!room) {
return "There are no people here.";
}
const entities = this.world
.entitiesInRoom(room)
.filter((x) => isPerson(x))
.filter((x) => !x.invisible && x.id !== this.id);
const lines = [];
for (const entity of entities) {
lines.push(`${entity.name} (${entity.pronouns}) {`);
if (entity.id !== entity.name) {
lines.push(` id = ${JSON.stringify(entity.id)}`);
}
lines.push(
` ${entity.promptPersonDescription({ includeName: false, join: "\n ", fullDescription: true })}`,
);
lines.push("}");
}
if (this.id !== "Ama") {
lines.push(`Ama is always present {`);
lines.push(` ${this.world.entities.Ama.shortDescription}`);
lines.push("}");
}
return lines.join("\n");
}
exitsPrompt(parameters: ParametersT): string {
const room = this.world.entityRoom(this.id);
if (!room || !room.exits?.length) {
return "There are no exits.";
}
const lines = [];
for (const exit of room.exits) {
const target = this.world.getRoom(exit.roomId);
if (!target) {
console.warn("Exit target is not a room", exit.roomId);
continue;
}
lines.push(
tmpl`
Exit locationId "${exit.roomId}" {
name: ${target.name}
"${target.shortDescription}"
`,
);
if (exit.aliases) {
lines.push(` aliases: ${exit.aliases.join(", ")}`);
}
if (exit.restriction) {
lines.push(` exit is restricted by: "${exit.restriction}"`);
}
lines.push("}");
}
return lines.join("\n");
}
/**
* Run the prompt, streaming narrative text to `model.streaming` if a
* streaming backend is configured. Either way this resolves to the complete
* response, so the caller's parse is identical — streaming only adds the
* ability to show a turn while it is still arriving.
*/
private async streamOrChat(model: Model, prompt: ChatType): Promise<string> {
// Which character this prompt is for, for its usage record. Set here rather
// than in each assemblePrompt because every entity prompt passes through.
prompt.meta.entity ??= this.id;
if (!model.chatStream) {
return model.chat(prompt);
}
const parser = new TagStreamParser();
const show = (events: ReturnType<TagStreamParser["feed"]>) => {
for (const event of events) {
if (event.kind === "close") {
model.streaming.value = null;
} else {
model.streaming.value = { entityId: this.id, tag: event.tag };
}
}
};
try {
const text = await model.chatStream(prompt, (delta) =>
show(parser.feed(delta)),
);
show(parser.end());
return text;
} finally {
// Never leave provisional text on screen, even if the request failed.
model.streaming.value = null;
}
}
/**
* How many times to hand a broken response back and ask again.
*
* One. A model that misspells an attribute usually fixes it when told, and a
* model that doesn't fix it on the second go isn't going to on the third —
* meanwhile every retry is a whole prompt's worth of money and a second of
* the player waiting. Bounded at one because the failure being repaired is
* cosmetic to the player: the turn still happened, it just recorded less than
* it meant to.
*/
static readonly PROTOCOL_RETRIES = 1;
async executePrompt(model: Model, parameters: ParametersT) {
const prompt = this.assemblePrompt(parameters);
const roomId = this.world.entityRoom(this.id)?.id || "Void";
let resp = "";
let result: StoryEventType | null = null;
let complaints: string[] = [];
for (
let attempt = 0;
attempt <= (this.constructor as typeof Entity).PROTOCOL_RETRIES;
attempt++
) {
// On a retry the model is shown its own answer and what was wrong with
// it, which is the shape it can act on. Reassembling the prompt from
// scratch and hoping for better would be a reroll, not a correction.
const attemptPrompt =
attempt === 0
? prompt
: {
...prompt,
messages: [
...prompt.messages,
{ role: "assistant" as const, content: resp },
{
role: "user" as const,
content: `Some of that could not be applied:\n${complaints.join("\n")}\n\nReply again with the complete set of tags for this turn, fixing those. Use only attributes that already exist.`,
},
],
};
resp = fixupText(
await model.run(() => this.streamOrChat(model, attemptPrompt)),
);
complaints = [];
result = await this.applyResponse({
model,
parameters,
resp,
roomId,
title: prompt.meta.title,
complaints,
});
if (!complaints.length) {
break;
}
}
result = this.afterPrompt(result!);
await model.addStoryEvent(result);
}
/** Turn one response into a story event, collecting what wouldn't apply. */
private async applyResponse({
model,
parameters,
resp,
roomId,
title,
complaints,
}: {
model: Model;
parameters: ParametersT;
resp: string;
roomId: EntityId;
title: string;
complaints: string[];
}): Promise<StoryEventType> {
let tags = unfoldTags(parseTags(resp), {
// We don't want to unfold this, because it's for planning, not action:
ignoreContainers: ["context"],
// These sometimes are produced without content, but then they are meaningless:
trimEmpty: ["dialog", "description"],
});
if (tags.length === 1 && tags[0]!.type === "context") {
// This happens sometimes when it puts *everything* in a context tag. We don't always want to look inside context but if there's only context then we do...
tags = unfoldTags(parseTags(tags[0]!.content), {});
}
let result: StoryEventType = {
id: this.id,
totalTime: 0,
changes: {},
actions: [],
roomId,
llmTitle: title,
llmResponse: resp,
// Recorded for replay/undo; the concrete shape varies per entity type, so
// it is stored as a plain record.
llmParameters: parameters as Record<string, unknown>,
};
const tagContext: TagContext = {
world: this.world,
entityId: this.id,
roomId,
// FIXME: kind of a hack that should be done in a subclass:
subject: (parameters as { examine?: string }).examine || undefined,
complaints,
};
for (const tag of tags) {
if (applyTag(tag, result, tagContext)) {
continue;
}
// Not part of the base protocol - let the entity's own hook handle it.
result = await this.processTag({
tag,
model,
parameters,
storyEvent: result,
llmResponse: resp,
});
}
return result;
}
changes(values: Partial<this>): Record<string, ChangeType> {
const c: ChangeType = {
before: {},
after: {},
};
for (const [key, value] of Object.entries(values)) {
c.before[key] = fieldsOf(this)[key];
c.after[key] = value;
}
return {
[this.id]: c,
};
}
mergeChanges(event: StoryEventType, values: Partial<this>): StoryEventType {
const changes = this.changes(values);
const mine = changes[this.id]!;
const existing = event.changes[this.id];
if (existing) {
for (const [key, value] of Object.entries(mine.after)) {
existing.after[key] = value;
}
} else {
event.changes[this.id] = mine;
}
return event;
}
/**
* The character's current feelings about people, for their own prompt only.
*
* Empty string when there are none, which is the usual case — the [[...]]
* template wrapper then drops the section entirely, so a character with no
* particular feelings carries no text about feelings at all.
*/
attitudesPrompt(): string {
if (!isPerson(this)) {
return "";
}
const entries = Object.entries(this.attitudes);
if (!entries.length) {
return "";
}
const lines = entries.map(([id, feeling]) => {
const who = this.world.getEntity(id);
return `- ${who?.name ?? id} (${id}): ${feeling}`;
});
return tmpl`
${this.name}'s current private feelings, which only ${this.name} knows and which color how ${this.name} behaves:
${lines.join("\n")}
`;
}
myMysteryHints(): string {
const results: string[] = [];
for (const mystery of this.world.unveiledMysteries()) {
let hints: Record<EntityId, string> = {};
if (mystery.state === "revealed") {
hints = mystery.revealedHints;
} else if (mystery.state === "available") {
hints = mystery.availableHints;
} else if (mystery.state === "solved") {
hints = mystery.solvedHints;
}
// Collected per mystery, so the "*" and meter lines attach to the
// mystery they belong to. (This also fixes a leak: the old cross-mystery
// `results.length` check could hand a room one mystery's "*" hint
// because a *different* mystery had briefed that room.)
const mine: string[] = [];
const selfHint = hints[this.id];
if (selfHint) {
mine.push(selfHint);
}
const roomHint = hints[this.myRoom().id];
if (this.myRoom().id !== this.id && roomHint) {
mine.push(roomHint);
}
if ((mine.length || isPerson(this)) && hints["*"]) {
mine.unshift(hints["*"]);
}
if (mine.length && mystery.meters.length) {
mine.push(this.meterReadout(mystery.meters));
}
results.push(...mine);
}
return results.join("\n");
}
/**
* The current values of a mystery's meters, as one line of prompt text.
*
* Hints are static strings, so an instruction like "her behavior is keyed to
* PLAYER.civicPoints" had no way to see the number: a model only knew a
* counter's value while its own `<set>` events were still inside the sliding
* history window. The Archivist's angst registers shipped with that bug.
* Any character a mystery briefs gets the mystery's declared meters appended
* to the hint block.
*/
meterReadout(meters: string[]): string {
const parts = meters.map((meter) => {
const [entityId, attr] = meter.split(".");
const entity = entityId ? this.world.getEntity(entityId) : undefined;
const value = entity && attr ? fieldsOf(entity)[attr] : undefined;
return `${meter} = ${JSON.stringify(value)}`;
});
return `Current values: ${parts.join(", ")}`;
}
}
export interface SoundTrackType {
url: string;
sunoUrl: string;
}
export class Room extends Entity {
type = "room";
exits: Exit[] = [];
userInputInstructions = "";
visits: number = 0;
excludeFromMap = false;
/**
* Whether Ama will name this room or route to it for `/nav`.
*
* Bedrooms are off it: somewhere private is somewhere she does not send
* people, and anyone in a room that is off it is not findable either. That is
* the seam for anything later that should hide a person — being unfindable is
* a property of where you are rather than a special case in the lookup.
*
* Separate from `excludeFromMap`, which is about drawing: a room can be
* absent from the map and still be somewhere you can be directed to.
*/
onNav = true;
soundtrack?: SoundTrackType;
actionPrompt = "";
constructor({
exits,
userInputInstructions,
visits,
excludeFromMap,
onNav,
soundtrack,
actionPrompt,
promptForPerson,
...props
}: EntityInitType & {
exits?: Exit[];
userInputInstructions?: string;
visits?: number;
excludeFromMap?: boolean;
onNav?: boolean;
soundtrack?: SoundTrackType;
actionPrompt?: string;
promptForPerson?: (this: Room, person: Person) => string;
}) {
super(props);
if (exits) {
this.exits = exits;
}
if (userInputInstructions !== undefined) {
this.userInputInstructions = userInputInstructions;
}
if (visits !== undefined) {
this.visits = visits;
}
if (excludeFromMap !== undefined) {
this.excludeFromMap = excludeFromMap;
}
if (onNav !== undefined) {
this.onNav = onNav;
}
if (soundtrack) {
this.soundtrack = soundtrack;
}
if (actionPrompt) {
this.actionPrompt = actionPrompt;
}
if (promptForPerson) {
this.promptForPerson = promptForPerson.bind(this);
}
}
override clone(): this {
const newInstance = super.clone() as this;
newInstance.exits = this.exits.map((exit) => ({ ...exit }));
return newInstance as this;
}
promptForPerson(person: Person): string {
return "";
}
}
// The Archivist console room. Its distinctive terminal-style rendering lives in
// the view (app/renderstoryaction.tsx); this class only marks the room type.
export class ArchivistRoom extends Room {}
export interface Exit {
name?: string;
roomId: EntityId;
aliases?: string[];
/**
* Prose conditions on passing, adjudicated by a model when the player tries
* (`assembleMovePrompt`). Right for doors a character can decide to allow —
* the quarters doors, which their owners walk through nightly.
*/
restriction?: string;
/**
* A hard lock the engine enforces: `<goto>` is refused without asking a
* model, `pathTo` will not route through it (so schedules and the cuff
* don't), and the action adjudicator is told no attempt on it succeeds.
* For doors that must hold against anything the player can type; only an
* engine-made event (the Star Citizen ceremony) opens one. A `restriction`
* alongside it is display text, explaining the door the model never gets
* to adjudicate.
*/
sealed?: boolean;
}
export type RelationshipRatingType = "positive" | "negative" | "neutral";
export interface RelationshipType {
background?: string;
polite?: RelationshipRatingType;
fun?: RelationshipRatingType;
respectable?: RelationshipRatingType;
trustworthy?: RelationshipRatingType;
}
/**
* One emotional meter, declared on the character it belongs to.
*
* The value is a plain numeric field on the person (so `<set>` increments,
* complaints validation, `Mystery.meters` and `attrSet`/`reaches` triggers all
* work on it unchanged); this spec is everything else — the range, what moves
* it, and what each level means. The model only ever judges the moment ("did
* this turn annoy him? +1"); the level is engine arithmetic and the register
* text tells the model how to play the number it is at. Counted rather than
* judged, for the same reason as Archivist.angst: "sufficiently annoyed" is a
* threshold a model fires on turn one or never.
*
* Keep it to one, two, at most three meters per character, in small ranges:
* the player has to be able to comprehend the dial from behavior alone.
*/
export interface StatSpecType {
/** Initial value. Defaults to 0. */
start?: number;
/** Defaults to 0. Negative minimums are fine (a like/dislike axis). */
min?: number;
/** Defaults to 10, but declare it; small ranges read better. */
max?: number;
/** What raises it, one flat line, shown to the model as the +1 criteria. */
up?: string;
/** What lowers it, the -1 criteria. */
down?: string;
/**
* What the number means, keyed by the value each register starts at: the
* character plays the highest register at or below the current value.
*/
levels?: Record<number, string>;
}
export class Person<
ParametersT extends ParametersType = ParametersType,
> extends Entity<ParametersT> {
type = "person";
pronouns: string = "they/them";
roleplayInstructions: string = "";
declare inside: EntityId;
/**
* How this character currently feels about specific people, keyed by entity
* id, written and updated by the character itself via `<attitude toward=...>`.
* Sparse on purpose: no key means no particular feeling, and that absence is
* the default state — there is no "neutral" entry. The fold merges these
* per key (see applyChanges), so one feeling changing doesn't clobber the
* rest, and a `null` in a change deletes a feeling that has faded.
*/
attitudes: Record<EntityId, string> = {};
/**
* The character's declared emotional meters; see StatSpecType. The values
* live as plain numeric fields on the instance, named by these keys.
*/
statSpecs: Record<string, StatSpecType> = {};
scheduleTemplate: PersonScheduleTemplateType[] = [];
todaysSchedule: PersonScheduledEventType[] = [];
runningScheduleId: ScheduleId | null = null;
constructor({
pronouns,
roleplayInstructions,
attitudes,
stats,
scheduleTemplate,
...props
}: EntityInitType & {
pronouns?: string;
roleplayInstructions?: string;
attitudes?: Record<EntityId, string>;
stats?: Record<string, StatSpecType>;
scheduleTemplate?: PersonScheduleTemplateType[];
}) {
super(props);
if (stats) {
for (const [name, spec] of Object.entries(stats)) {
if (name in this) {
throw new Error(
`Stat "${name}" on ${this.id} collides with an existing field`,
);
}
fieldsOf(this)[name] = spec.start ?? 0;
}
this.statSpecs = stats;
}
if (pronouns) {
this.pronouns = pronouns;
}
if (roleplayInstructions) {
this.roleplayInstructions = roleplayInstructions;
}
if (!fieldsOf(this).inside) {
this.inside = "Void";
}
if (attitudes) {
this.attitudes = attitudes;
}
if (scheduleTemplate) {
this.scheduleTemplate = scheduleTemplate;
}
}
/**
* The character's declared meters, rendered for their own prompt only:
* current value, range, the +1/-1 criteria, and the register text for each
* level. Empty string for the (usual) character with no meters, so the
* [[...]] wrapper drops the section and no prompt grows for them.
*/
metersPrompt(): string {
const entries = Object.entries(this.statSpecs);
if (!entries.length) {
return "";
}
const parts = entries.map(([name, spec]) => {
const lines = [
`${name} = ${fieldsOf(this)[name]} (range ${spec.min ?? 0} to ${spec.max ?? 10})`,
];
if (spec.up) {
lines.push(`Raise it (+1) when: ${spec.up}`);
}
if (spec.down) {
lines.push(`Lower it (-1) when: ${spec.down}`);
}
const levels = Object.entries(spec.levels ?? {}).sort(
(a, b) => Number(a[0]) - Number(b[0]),
);
if (levels.length) {
lines.push(
`What the number means; play the highest register at or below the current value:`,
);
for (const [at, means] of levels) {
lines.push(`${at}: ${means}`);
}
}
return lines.join("\n");
});
return tmpl`
${this.name}'s meters, private to ${this.name}. The number sets the register ${this.name} plays in:
${parts.join("\n\n")}
When this turn genuinely moves a meter, adjust it one step:
<set attr="${this.id}.${entries[0]![0]}">+1</set>
Use -1 for a step down. At most one step per meter per turn; most turns move nothing. When a meter moves, show the shift in ${this.name}'s behavior in the same response, so the player can feel the change without seeing the number.
`;
}
override assemblePrompt(parameters: ParametersT): ChatType {
const lastTo = this.lastSpokeTo()?.id || "";
let hasInteracted = false;
for (let i = this.world.model.liveUpdates.value.length - 1; i >= 0; i--) {
const update = this.world.model.liveUpdates.value[i]!;
if (update.id === this.id) {
for (const action of update.actions) {
if (isStoryDialog(action) && action.toId === "PLAYER") {
hasInteracted = true;
break;
}
}
}
}
const schedule = scheduleForTime(this, this.world.timestampMinutes);
const willLeave = schedule && !schedule.inside.includes(this.inside);
const promptForPerson = this.world
.entityRoom(this.id)
?.promptForPerson(this);
const mysteryHints = this.myMysteryHints();
// The <taskList> block below is length-sensitive, in both directions, and
// was tuned against the evals rather than guessed at. Cutting it to two
// sentences stopped tasks being created at all (task-list 3/5); the first,
// wordier version got tasks created but made both model tiers sloppier
// elsewhere — movement dropped a hallucinated `<set>` on a scenario that
// had been clean. Re-run `pnpm evals --scenario task-list --scenario
// movement` after editing it.
return {
meta: {
title: `prompt ${this.id}`,
},
messages: [
{
role: "system",
content: tmpl`
You are a computer running a text adventure game. You will respond with tags to represent game action.
In this step you will be playing the part of a character named "${this.name}" (${this.pronouns}).
The human plays the character PLAYER — that is an id, used as-is in tags (as in <set attr="PLAYER.name">). PLAYER is currently known as "${this.world.entities.PLAYER.name}" (${this.world.entities.PLAYER.pronouns}); that may change as ${this.name} learns who they are.
<characterDescription>
${this.description}
</characterDescription>
<roleplayInstructions>
In general, the goal for the game to be FUN and SURPRISING. Move the conversation forward, and don't be afraid to overreact! ENGAGE with PLAYER and pay attention to what PLAYER says.
${this.roleplayInstructions}
</roleplayInstructions>
<taskList>
PLAYER keeps a list of what they have agreed to do, shown to them in their interface.
When ${this.name} asks PLAYER to do something, or PLAYER agrees to do something, add the response:
<todo>a short instruction, as PLAYER would write it to themselves</todo>
When that thing is genuinely finished, repeat the same wording as <todoDone>...</todoDone>. Nothing else belongs on the list.
</taskList>
${this.additionalSystemInstructions(parameters)}
[Everything above is fixed for this character. Everything below changes as the game is played.]
The time is ${timeAsString(this.world.timestampMinutes)}
${this.name} is currently in the room "${this.myRoom().name}": ${this.myRoom().shortDescription}
[[${IF(!hasInteracted)}This is the first time ${this.name} has spoken to PLAYER. There aren't many new people in Intra, so this might be a big deal.]]
[[${promptForPerson}]]
${this.intraActivityDescription()}
${this.activityDescription(parameters)}
The other people in the room ${this.myRoom().name} are:
${this.currentPeoplePrompt(parameters)}
[[${this.attitudesPrompt()}]]
[[${this.metersPrompt()}]]
[[This character has some knowledge of some mysteries; follow these additional instructions:
"""
${mysteryHints}
"""
Inventing around a mystery: invented detail is welcome, and invented side paths are welcome, but a side path must lead toward something real that the instructions above mention — a person, a place, a record. Do not invent evidence that names a culprit, answers a mystery's question, or points suspicion at anyone these instructions do not implicate. An invented lead the player follows should connect them back to the real trail.]]
[[${todoPrompt(this.world.todos)}]]
${this.volatileSystemInstructions(parameters)}
`,
},
...this.historyForEntity({ limit: 10 }),
{
role: "user",
content: tmpl`
Given the above play state, respond as the character "${this.name}"
[[This character has been triggered to act specifically by: "${parameters.trigger}"]]
Begin by assembling the essential context given the above history, writing 4-5 words for each item:
<context>
1. Are there any special questions for this character that need to be answered? If so answer them here.
2. Are there any facts that have to be constructed to continue the scene or response? If so then invent those facts and record them.
3. ${this.name}'s goals, including listing out any specific goals previously noted in the prompt
4. Relevant facts from the history
5. How can this response be fun or surprising?
6. ${this.name}'s reaction to any recent speech or events
7. ${this.name}'s intention in this response
8. Did this turn change how ${this.name} feels about a specific person? Name the person and the change, or write "no"
</context>
<responseFormat>
Begin your response with <context>...</context>
To generate speech add this response:
<dialog character="${this.name}">1-3 sentences of dialog written as ${this.name}</dialog>
To speak directly TO someone:
<dialog character="${this.name}" to="${lastTo || "Jim"}">Dialog written as ${this.name} to ${lastTo || "Jim"}</dialog>
[[${this.name} last spoke directly to ${lastTo}, so it's very likely ${this.heshe} is still speaking to them.]]
If the character ${this.name} is performing an action, add this response (optionally with a rough estimate of the time it will take in minutes):
<description minutes="5">Describe the action</description>