@pretty-chitty/core 1.2.17 → 2.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/dist/components/ClientTrustMatchViewer.d.ts +14 -1
- package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
- package/dist/components/ClientTrustMatchViewer.js +25 -2
- package/dist/components/ClientTrustMatchViewer.js.map +1 -1
- package/dist/components/DemoWrapper.d.ts.map +1 -1
- package/dist/components/DemoWrapper.js +4 -11
- package/dist/components/DemoWrapper.js.map +1 -1
- package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
- package/dist/components/Gallery/BuiltItem.js +3 -0
- package/dist/components/Gallery/BuiltItem.js.map +1 -1
- package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
- package/dist/components/Gallery/GalleryController.js +3 -1
- package/dist/components/Gallery/GalleryController.js.map +1 -1
- package/dist/components/PanelSpark.js +1 -1
- package/dist/components/PlayerImage.d.ts.map +1 -1
- package/dist/components/PlayerImage.js +21 -1
- package/dist/components/PlayerImage.js.map +1 -1
- package/dist/components/Playground.d.ts.map +1 -1
- package/dist/components/Playground.js +37 -11
- package/dist/components/Playground.js.map +1 -1
- package/dist/components/TokenizedMessage.d.ts +2 -6
- package/dist/components/TokenizedMessage.d.ts.map +1 -1
- package/dist/components/TokenizedMessage.js +1 -35
- package/dist/components/TokenizedMessage.js.map +1 -1
- package/dist/components/TopBarPlayers.d.ts.map +1 -1
- package/dist/components/TopBarPlayers.js +1 -1
- package/dist/components/TopBarPlayers.js.map +1 -1
- package/dist/game/Chit.js +2 -2
- package/dist/game/Chit.js.map +1 -1
- package/dist/game/ConnectionTransport.d.ts +3 -0
- package/dist/game/ConnectionTransport.d.ts.map +1 -1
- package/dist/game/ConnectionTransport.js +13 -4
- package/dist/game/ConnectionTransport.js.map +1 -1
- package/dist/game/Game.d.ts +8 -1
- package/dist/game/Game.d.ts.map +1 -1
- package/dist/game/Match.d.ts +66 -0
- package/dist/game/Match.d.ts.map +1 -1
- package/dist/game/Match.js +151 -3
- package/dist/game/Match.js.map +1 -1
- package/dist/game/MatchStorage.d.ts +8 -1
- package/dist/game/MatchStorage.d.ts.map +1 -1
- package/dist/game/MatchStorage.js +11 -3
- package/dist/game/MatchStorage.js.map +1 -1
- package/dist/game/Pick.d.ts +14 -0
- package/dist/game/Pick.d.ts.map +1 -1
- package/dist/game/Pick.js +15 -0
- package/dist/game/Pick.js.map +1 -1
- package/dist/game/PlayerChit.d.ts +4 -0
- package/dist/game/PlayerChit.d.ts.map +1 -1
- package/dist/game/PlayerChit.js +8 -2
- package/dist/game/PlayerChit.js.map +1 -1
- package/dist/game/PlayerInfo.d.ts +8 -0
- package/dist/game/PlayerInfo.d.ts.map +1 -1
- package/dist/game/PlayerInfo.js +6 -3
- package/dist/game/PlayerInfo.js.map +1 -1
- package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
- package/dist/game/PlayerPromptStatusChit.js +3 -1
- package/dist/game/PlayerPromptStatusChit.js.map +1 -1
- package/dist/game/Turn.d.ts +11 -2
- package/dist/game/Turn.d.ts.map +1 -1
- package/dist/game/Turn.js +118 -68
- package/dist/game/Turn.js.map +1 -1
- package/dist/game/TurnState.d.ts +8 -0
- package/dist/game/TurnState.d.ts.map +1 -1
- package/dist/game/TurnState.js +7 -0
- package/dist/game/TurnState.js.map +1 -1
- package/dist/game/ai/AiClientPrompts.d.ts +160 -0
- package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
- package/dist/game/ai/AiClientPrompts.js +525 -0
- package/dist/game/ai/AiClientPrompts.js.map +1 -0
- package/dist/game/ai/AiLiveView.d.ts +2 -0
- package/dist/game/ai/AiLiveView.d.ts.map +1 -0
- package/dist/game/ai/AiLiveView.js +48 -0
- package/dist/game/ai/AiLiveView.js.map +1 -0
- package/dist/game/ai/AiPlayerView.d.ts +2 -0
- package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
- package/dist/game/ai/AiPlayerView.js +89 -0
- package/dist/game/ai/AiPlayerView.js.map +1 -0
- package/dist/game/ai/connectAiPlayer.d.ts +43 -0
- package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
- package/dist/game/ai/connectAiPlayer.js +58 -0
- package/dist/game/ai/connectAiPlayer.js.map +1 -0
- package/dist/game/ai/defineAi.d.ts +119 -0
- package/dist/game/ai/defineAi.d.ts.map +1 -0
- package/dist/game/ai/defineAi.js +122 -0
- package/dist/game/ai/defineAi.js.map +1 -0
- package/dist/game/ai/simulateMatches.d.ts +62 -0
- package/dist/game/ai/simulateMatches.d.ts.map +1 -0
- package/dist/game/ai/simulateMatches.js +108 -0
- package/dist/game/ai/simulateMatches.js.map +1 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
- package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
- package/dist/hooks/useTokenMap.d.ts +2 -4
- package/dist/hooks/useTokenMap.d.ts.map +1 -1
- package/dist/hooks/useTokenMap.js +2 -5
- package/dist/hooks/useTokenMap.js.map +1 -1
- package/dist/hooks/useWebGlRenderer.d.ts +1 -0
- package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
- package/dist/hooks/useWebGlRenderer.js +33 -21
- package/dist/hooks/useWebGlRenderer.js.map +1 -1
- package/dist/index.d.ts +21 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
- package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
- package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.d.ts +18 -1
- package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.js +119 -6
- package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
- package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
- package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
- package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
- package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
- package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
- package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
- package/dist/utilities/ParameterizedCanvas.js +4 -1
- package/dist/utilities/ParameterizedCanvas.js.map +1 -1
- package/dist/utilities/TokenizedText.d.ts +49 -0
- package/dist/utilities/TokenizedText.d.ts.map +1 -0
- package/dist/utilities/TokenizedText.js +47 -0
- package/dist/utilities/TokenizedText.js.map +1 -0
- package/package.json +1 -1
- package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
- package/src/library/components/DemoWrapper.tsx +4 -12
- package/src/library/components/Gallery/BuiltItem.ts +4 -0
- package/src/library/components/Gallery/GalleryController.ts +3 -1
- package/src/library/components/PanelSpark.tsx +1 -1
- package/src/library/components/PlayerImage.tsx +26 -2
- package/src/library/components/Playground.tsx +77 -12
- package/src/library/components/TokenizedMessage.tsx +2 -63
- package/src/library/components/TopBarPlayers.tsx +6 -1
- package/src/library/game/Chit.ts +2 -2
- package/src/library/game/ConnectionTransport.ts +12 -3
- package/src/library/game/Game.ts +9 -1
- package/src/library/game/Match.ts +162 -3
- package/src/library/game/MatchStorage.ts +14 -4
- package/src/library/game/Pick.ts +20 -0
- package/src/library/game/PlayerChit.ts +10 -3
- package/src/library/game/PlayerInfo.ts +13 -3
- package/src/library/game/PlayerPromptStatusChit.ts +3 -1
- package/src/library/game/Turn.ts +131 -76
- package/src/library/game/TurnState.ts +8 -0
- package/src/library/game/ai/AI_GUIDE.md +434 -0
- package/src/library/game/ai/AiClientPrompts.ts +681 -0
- package/src/library/game/ai/AiLiveView.ts +63 -0
- package/src/library/game/ai/AiPlayerView.ts +112 -0
- package/src/library/game/ai/ai.test.ts +475 -0
- package/src/library/game/ai/connectAiPlayer.ts +88 -0
- package/src/library/game/ai/defineAi.ts +230 -0
- package/src/library/game/ai/simulateMatches.ts +172 -0
- package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
- package/src/library/hooks/useTokenMap.ts +2 -6
- package/src/library/hooks/useWebGlRenderer.tsx +44 -24
- package/src/library/index.ts +34 -2
- package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
- package/src/library/utilities/CanvasStack/CanvasStack.ts +119 -5
- package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
- package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
- package/src/library/utilities/ParameterizedCanvas.ts +5 -1
- package/src/library/utilities/TokenizedText.test.ts +32 -0
- package/src/library/utilities/TokenizedText.ts +97 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { ConnectionObject } from "../ConnectionObject";
|
|
2
|
+
import { PlayerChit } from "../PlayerChit";
|
|
3
|
+
import { RootChit } from "../RootChit";
|
|
4
|
+
import { AiContext, AiOption } from "./defineAi";
|
|
5
|
+
/**
|
|
6
|
+
* Where a bot keeps its plan memory between prompts. `connectAiPlayer` defaults to a store inside the
|
|
7
|
+
* match's saved state, so memory survives a reload or a re-seat in another process. Pass your own to
|
|
8
|
+
* keep it elsewhere, or `false` for in-process only.
|
|
9
|
+
*/
|
|
10
|
+
export type AiMemoryStore<M = any> = {
|
|
11
|
+
read(): M | undefined;
|
|
12
|
+
write(memory: M): void;
|
|
13
|
+
};
|
|
14
|
+
export type AiPlayerOptions = {
|
|
15
|
+
/** 0–1. Lower values add more noise to scores so the bot plays less predictably. Default 0.85 */
|
|
16
|
+
difficulty?: number;
|
|
17
|
+
/** Pause before answering, in ms: a fixed value or a [min, max] range. Default 0 */
|
|
18
|
+
thinkMs?: number | [number, number];
|
|
19
|
+
/** Seed for the bot's random number generator */
|
|
20
|
+
seed?: number;
|
|
21
|
+
/** Log untagged prompts and warnings to the console. Default true */
|
|
22
|
+
log?: boolean;
|
|
23
|
+
/** Warn if the server hasn't answered within this many ms after the bot responds. Default 10000 */
|
|
24
|
+
stallWarningMs?: number;
|
|
25
|
+
/** Anything the game's rules should read as `ctx.params`: per-seat weights, a personality, … */
|
|
26
|
+
params?: unknown;
|
|
27
|
+
/**
|
|
28
|
+
* Choose by softmax over scores at this temperature, in score units (1 = an option worth one
|
|
29
|
+
* point less is chosen e≈2.7× less often). Replaces the `difficulty` noise, which scales with
|
|
30
|
+
* the spread of each prompt's scores. Unset: use `difficulty`.
|
|
31
|
+
*/
|
|
32
|
+
temperature?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Override the choice: return the index into `scored` to take, or undefined for the normal
|
|
35
|
+
* choice. For harnesses (forced moves in playouts, scripted openings), not for game rules.
|
|
36
|
+
*/
|
|
37
|
+
choose?: (scored: {
|
|
38
|
+
option: AiOption;
|
|
39
|
+
score: number;
|
|
40
|
+
}[], ctx: AiContext<any, any, any>) => number | undefined;
|
|
41
|
+
/** Called after every decision with each option's score and the chosen index (for logging and audits). */
|
|
42
|
+
onDecision?: (decision: AiDecision) => void;
|
|
43
|
+
/**
|
|
44
|
+
* Where plan memory is kept (see `AiMemoryStore`). `connectAiPlayer` defaults this to the match's
|
|
45
|
+
* saved state; `false` keeps memory in-process only, so it resets whenever the bot is re-seated.
|
|
46
|
+
*/
|
|
47
|
+
memoryStore?: AiMemoryStore | false;
|
|
48
|
+
/** Start paused (see `setEnabled`). Default false */
|
|
49
|
+
disabled?: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** One decision, as reported to `AiPlayerOptions.onDecision`. */
|
|
52
|
+
export type AiDecision = {
|
|
53
|
+
playerId: string;
|
|
54
|
+
prompt: {
|
|
55
|
+
message?: string;
|
|
56
|
+
help?: string;
|
|
57
|
+
};
|
|
58
|
+
scored: {
|
|
59
|
+
option: AiOption;
|
|
60
|
+
score: number;
|
|
61
|
+
}[];
|
|
62
|
+
chosen: number;
|
|
63
|
+
/** The context the rules saw (its `view` is live in the default view mode: read it now, don't keep it) */
|
|
64
|
+
ctx: AiContext<any, any, any>;
|
|
65
|
+
};
|
|
66
|
+
export type AiPlayerStats = {
|
|
67
|
+
promptsAnswered: number;
|
|
68
|
+
stepBacks: number;
|
|
69
|
+
rejections: number;
|
|
70
|
+
stalls: number;
|
|
71
|
+
ruleErrors: number;
|
|
72
|
+
/** Prompts the bot could not get out of (no valid moves and nothing left to undo) */
|
|
73
|
+
stuck: number;
|
|
74
|
+
/** How often each untagged pick (keyed by its message) was scored without a rule */
|
|
75
|
+
untagged: {
|
|
76
|
+
[message: string]: number;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* An AI player, registered as "ClientPrompts" on its own connection (see `connectAiPlayer`).
|
|
81
|
+
*
|
|
82
|
+
* It only has the Game (for its rules and chit library) and its view of the board: by default the
|
|
83
|
+
* match's live objects (AiLiveView), or, when the game asks for it, exactly what the server sends
|
|
84
|
+
* its seat (AiPlayerView). Create one with `connectAiPlayer`.
|
|
85
|
+
*
|
|
86
|
+
* @group AI
|
|
87
|
+
*/
|
|
88
|
+
export declare class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = any> extends ConnectionObject {
|
|
89
|
+
private playerId;
|
|
90
|
+
private game;
|
|
91
|
+
private view;
|
|
92
|
+
private options;
|
|
93
|
+
private serverPrompts;
|
|
94
|
+
private latest?;
|
|
95
|
+
private seq;
|
|
96
|
+
private handledSeq;
|
|
97
|
+
private running;
|
|
98
|
+
private disposed;
|
|
99
|
+
private _stalled;
|
|
100
|
+
private _enabled;
|
|
101
|
+
private memoryStore?;
|
|
102
|
+
private memory;
|
|
103
|
+
private history;
|
|
104
|
+
private dead;
|
|
105
|
+
private exhaustedVisits;
|
|
106
|
+
private blindStepBacks;
|
|
107
|
+
private warned;
|
|
108
|
+
private random;
|
|
109
|
+
stats: AiPlayerStats;
|
|
110
|
+
dispose(): void;
|
|
111
|
+
/** The bot's current (frozen) memory, for debugging and tests */
|
|
112
|
+
get memorySnapshot(): Readonly<M>;
|
|
113
|
+
/** True when the bot is not working on anything */
|
|
114
|
+
get idle(): boolean;
|
|
115
|
+
/** False while paused: prompts are kept but not answered (see `setEnabled`) */
|
|
116
|
+
get enabled(): boolean;
|
|
117
|
+
/**
|
|
118
|
+
* Pause or resume the bot without losing its memory. While paused it still receives prompts and
|
|
119
|
+
* answers the latest one when resumed. Hosts use this to make sure only one copy of a match drives
|
|
120
|
+
* its bots when several copies exist (every browser tab in client-trust mode, or two bundle
|
|
121
|
+
* versions of one match on a server). On resume the memory is re-read from the store, since
|
|
122
|
+
* another copy may have moved the plan on.
|
|
123
|
+
*/
|
|
124
|
+
setEnabled(enabled: boolean): void;
|
|
125
|
+
private loadMemory;
|
|
126
|
+
/** Commits new memory and mirrors it to the store so it survives a reload. */
|
|
127
|
+
private setMemory;
|
|
128
|
+
/** True while an answer has been sent but the server has not reacted within `stallWarningMs` */
|
|
129
|
+
get stalled(): boolean;
|
|
130
|
+
private pump;
|
|
131
|
+
private isCurrent;
|
|
132
|
+
private handle;
|
|
133
|
+
/** Lists every legal answer to the prompt, with chits taken from this player's view. */
|
|
134
|
+
private enumerate;
|
|
135
|
+
private makeButton;
|
|
136
|
+
private choose;
|
|
137
|
+
/**
|
|
138
|
+
* The old demo behaviour, which games tune with `Game.demoPickWeight`: choose a pick weighted by
|
|
139
|
+
* (number of choices × demoPickWeight), then an option within it uniformly. For a DragPick the
|
|
140
|
+
* DragTarget group is chosen uniformly first, so splitting targets into groups steers drops.
|
|
141
|
+
*/
|
|
142
|
+
private chooseLegacy;
|
|
143
|
+
/** Last resort when no options could be mapped to chits in the view. */
|
|
144
|
+
private answerBlindly;
|
|
145
|
+
/** Undo the bot's last answer, remembering it as a dead end for that exact situation. */
|
|
146
|
+
private backtrack;
|
|
147
|
+
private fingerprint;
|
|
148
|
+
private pruneDeadEndsExcept;
|
|
149
|
+
private noteUntagged;
|
|
150
|
+
private think;
|
|
151
|
+
/**
|
|
152
|
+
* Awaits the server's reaction to an answer. If it takes longer than `stallWarningMs`, warns and
|
|
153
|
+
* counts a stall, then keeps waiting: the answer is in flight, so the bot cannot know whether it
|
|
154
|
+
* was accepted until the server says so.
|
|
155
|
+
*/
|
|
156
|
+
private withStallWarning;
|
|
157
|
+
private log;
|
|
158
|
+
private warnOnce;
|
|
159
|
+
}
|
|
160
|
+
//# sourceMappingURL=AiClientPrompts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AiClientPrompts.d.ts","sourceRoot":"","sources":["../../../src/library/game/ai/AiClientPrompts.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
import { ConnectionObject } from "../ConnectionObject";
|
|
2
|
+
import { Confirm, GameButton } from "../GameButton";
|
|
3
|
+
import { applyPlan, chooseIndex, chooseSoftmax, chooseWeighted, createRandom, hashString, normalizeScore, } from "./defineAi";
|
|
4
|
+
const MAX_BLIND_STEP_BACKS = 3;
|
|
5
|
+
const MAX_EXHAUSTED_VISITS = 3;
|
|
6
|
+
/**
|
|
7
|
+
* An AI player, registered as "ClientPrompts" on its own connection (see `connectAiPlayer`).
|
|
8
|
+
*
|
|
9
|
+
* It only has the Game (for its rules and chit library) and its view of the board: by default the
|
|
10
|
+
* match's live objects (AiLiveView), or, when the game asks for it, exactly what the server sends
|
|
11
|
+
* its seat (AiPlayerView). Create one with `connectAiPlayer`.
|
|
12
|
+
*
|
|
13
|
+
* @group AI
|
|
14
|
+
*/
|
|
15
|
+
export class AiClientPrompts extends ConnectionObject {
|
|
16
|
+
/** @internal */
|
|
17
|
+
constructor(playerId, connection, game, view, options = {}) {
|
|
18
|
+
super();
|
|
19
|
+
this.playerId = playerId;
|
|
20
|
+
this.game = game;
|
|
21
|
+
this.view = view;
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.serverPrompts = undefined;
|
|
24
|
+
this.latest = undefined;
|
|
25
|
+
this.seq = 0;
|
|
26
|
+
this.handledSeq = -1;
|
|
27
|
+
this.running = false;
|
|
28
|
+
this.disposed = false;
|
|
29
|
+
this._stalled = false;
|
|
30
|
+
this._enabled = true;
|
|
31
|
+
this.memoryStore = undefined;
|
|
32
|
+
this.memory = undefined;
|
|
33
|
+
this.history = [];
|
|
34
|
+
this.dead = new Map();
|
|
35
|
+
this.exhaustedVisits = new Map();
|
|
36
|
+
this.blindStepBacks = 0;
|
|
37
|
+
this.warned = new Set();
|
|
38
|
+
this.random = undefined;
|
|
39
|
+
this.stats = {
|
|
40
|
+
promptsAnswered: 0,
|
|
41
|
+
stepBacks: 0,
|
|
42
|
+
rejections: 0,
|
|
43
|
+
stalls: 0,
|
|
44
|
+
ruleErrors: 0,
|
|
45
|
+
stuck: 0,
|
|
46
|
+
untagged: {},
|
|
47
|
+
};
|
|
48
|
+
this.serverPrompts = connection.get("ServerPrompts");
|
|
49
|
+
this.random = createRandom(options.seed);
|
|
50
|
+
this.memoryStore = options.memoryStore || undefined;
|
|
51
|
+
this._enabled = !options.disabled;
|
|
52
|
+
this.memory = deepFreeze(this.loadMemory());
|
|
53
|
+
}
|
|
54
|
+
dispose() {
|
|
55
|
+
this.disposed = true;
|
|
56
|
+
super.dispose();
|
|
57
|
+
}
|
|
58
|
+
/** The bot's current (frozen) memory, for debugging and tests */
|
|
59
|
+
get memorySnapshot() {
|
|
60
|
+
return this.memory;
|
|
61
|
+
}
|
|
62
|
+
/** True when the bot is not working on anything */
|
|
63
|
+
get idle() {
|
|
64
|
+
return !this.running;
|
|
65
|
+
}
|
|
66
|
+
/** False while paused: prompts are kept but not answered (see `setEnabled`) */
|
|
67
|
+
get enabled() {
|
|
68
|
+
return this._enabled;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Pause or resume the bot without losing its memory. While paused it still receives prompts and
|
|
72
|
+
* answers the latest one when resumed. Hosts use this to make sure only one copy of a match drives
|
|
73
|
+
* its bots when several copies exist (every browser tab in client-trust mode, or two bundle
|
|
74
|
+
* versions of one match on a server). On resume the memory is re-read from the store, since
|
|
75
|
+
* another copy may have moved the plan on.
|
|
76
|
+
*/
|
|
77
|
+
setEnabled(enabled) {
|
|
78
|
+
if (this._enabled === enabled) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
this._enabled = enabled;
|
|
82
|
+
if (enabled) {
|
|
83
|
+
this.memory = deepFreeze(this.loadMemory());
|
|
84
|
+
this.history = [];
|
|
85
|
+
this.handledSeq = -1;
|
|
86
|
+
void this.pump();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
loadMemory() {
|
|
90
|
+
const stored = this.memoryStore?.read();
|
|
91
|
+
if (stored !== undefined) {
|
|
92
|
+
return stored;
|
|
93
|
+
}
|
|
94
|
+
return (this.game.ai?.initialMemory?.() ?? {});
|
|
95
|
+
}
|
|
96
|
+
/** Commits new memory and mirrors it to the store so it survives a reload. */
|
|
97
|
+
setMemory(memory) {
|
|
98
|
+
this.memory = deepFreeze(memory);
|
|
99
|
+
try {
|
|
100
|
+
this.memoryStore?.write(this.memory);
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
this.warnOnce("memoryStore", "could not persist memory", e);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** True while an answer has been sent but the server has not reacted within `stallWarningMs` */
|
|
107
|
+
get stalled() {
|
|
108
|
+
return this._stalled;
|
|
109
|
+
}
|
|
110
|
+
/** @internal Called by ServerPrompts for every player's prompt changes */
|
|
111
|
+
async setPromptForPlayer(playerId, prompt, clockDetails) {
|
|
112
|
+
if (playerId !== this.playerId || this.disposed) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
this.seq++;
|
|
116
|
+
this.latest = prompt ? { prompt, clockDetails, seq: this.seq } : undefined;
|
|
117
|
+
void this.pump();
|
|
118
|
+
}
|
|
119
|
+
async pump() {
|
|
120
|
+
if (this.running) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
this.running = true;
|
|
124
|
+
try {
|
|
125
|
+
while (this.latest && this.latest.seq !== this.handledSeq && !this.disposed && this._enabled) {
|
|
126
|
+
const current = this.latest;
|
|
127
|
+
this.handledSeq = current.seq;
|
|
128
|
+
try {
|
|
129
|
+
await this.handle(current);
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
if (!this.disposed) {
|
|
133
|
+
console.error(`[AI ${this.playerId}] failed to handle prompt "${current.prompt.id}"`, e);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!this._enabled && this.latest?.seq === current.seq) {
|
|
137
|
+
// Paused mid-prompt: leave it unanswered, and answer it when resumed
|
|
138
|
+
this.handledSeq = -1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
this.running = false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
isCurrent(entry) {
|
|
147
|
+
return !this.disposed && this._enabled && this.latest?.seq === entry.seq;
|
|
148
|
+
}
|
|
149
|
+
async handle(entry) {
|
|
150
|
+
const { prompt } = entry;
|
|
151
|
+
if (!prompt.canReset) {
|
|
152
|
+
// Nothing before this prompt can be undone (rng, player switch, start of game)
|
|
153
|
+
this.history = [];
|
|
154
|
+
}
|
|
155
|
+
await this.view.sync(entry.clockDetails?.clock);
|
|
156
|
+
if (!this.isCurrent(entry)) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (prompt.type === "NoValidMovesPrompt") {
|
|
160
|
+
await this.backtrack(prompt, "no valid moves");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (prompt.type !== "PickPrompt") {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const fingerprint = this.fingerprint(prompt, this.view.signature);
|
|
167
|
+
if (!prompt.canReset) {
|
|
168
|
+
this.pruneDeadEndsExcept(fingerprint);
|
|
169
|
+
}
|
|
170
|
+
const options = this.enumerate(prompt);
|
|
171
|
+
if (options.length === 0) {
|
|
172
|
+
this.warnOnce(`empty:${prompt.id}`, `could not map any options for "${promptMessage(prompt)}"; answering blindly`);
|
|
173
|
+
await this.answerBlindly(prompt);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const dead = this.dead.get(fingerprint);
|
|
177
|
+
let live = dead ? options.filter((o) => !dead.has(choiceKey(o))) : options;
|
|
178
|
+
if (live.length === 0) {
|
|
179
|
+
const visits = (this.exhaustedVisits.get(fingerprint) ?? 0) + 1;
|
|
180
|
+
this.exhaustedVisits.set(fingerprint, visits);
|
|
181
|
+
if (prompt.canReset && this.history.length > 0) {
|
|
182
|
+
await this.backtrack(prompt, "every option leads to a dead end");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (visits > MAX_EXHAUSTED_VISITS) {
|
|
186
|
+
this.stats.stuck++;
|
|
187
|
+
console.error(`[AI ${this.playerId}] stuck at "${promptMessage(prompt)}": every option leads to no valid moves and it cannot undo further. Giving up on this prompt.`);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.warnOnce(`exhausted:${fingerprint}`, `every option at "${promptMessage(prompt)}" failed; retrying anyway`);
|
|
191
|
+
this.dead.delete(fingerprint);
|
|
192
|
+
live = options;
|
|
193
|
+
}
|
|
194
|
+
await this.think();
|
|
195
|
+
if (!this.isCurrent(entry)) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const rejected = new Set();
|
|
199
|
+
for (;;) {
|
|
200
|
+
const candidates = live.filter((o) => !rejected.has(choiceKey(o)));
|
|
201
|
+
if (candidates.length === 0) {
|
|
202
|
+
this.stats.stuck++;
|
|
203
|
+
console.error(`[AI ${this.playerId}] the server rejected every option for "${promptMessage(prompt)}"`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const chosen = this.choose(prompt, candidates);
|
|
207
|
+
const memoryBefore = this.memory;
|
|
208
|
+
// Written before the answer is sent, so the save that follows the answer carries it
|
|
209
|
+
this.setMemory(applyPlan(memoryBefore, chosen.plan));
|
|
210
|
+
const result = await this.withStallWarning(this.serverPrompts.resolvePrompt(prompt.id, chosen.option.response), prompt);
|
|
211
|
+
if (result && result.id === prompt.id) {
|
|
212
|
+
// ServerPrompts rejected the answer and sent the same prompt back
|
|
213
|
+
this.setMemory(memoryBefore);
|
|
214
|
+
this.stats.rejections++;
|
|
215
|
+
rejected.add(choiceKey(chosen.option));
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
this.history.push({ fingerprint, choice: choiceKey(chosen.option), memoryBefore });
|
|
219
|
+
this.stats.promptsAnswered++;
|
|
220
|
+
this.blindStepBacks = 0;
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Lists every legal answer to the prompt, with chits taken from this player's view. */
|
|
225
|
+
enumerate(prompt) {
|
|
226
|
+
const picks = prompt.details?.picks ?? [];
|
|
227
|
+
const find = this.view.findChit;
|
|
228
|
+
const options = [];
|
|
229
|
+
picks.forEach((sp, idx) => {
|
|
230
|
+
const pick = {
|
|
231
|
+
index: idx,
|
|
232
|
+
type: sp.type,
|
|
233
|
+
message: sp.message,
|
|
234
|
+
help: sp.help,
|
|
235
|
+
context: sp.context ? find(sp.context) : undefined,
|
|
236
|
+
};
|
|
237
|
+
const base = { key: sp.ai?.k, data: sp.ai?.d, pick };
|
|
238
|
+
switch (sp.type) {
|
|
239
|
+
case "ChitPick": {
|
|
240
|
+
sp.details.c.forEach((id) => {
|
|
241
|
+
const chit = find(id);
|
|
242
|
+
if (chit) {
|
|
243
|
+
options.push({ ...base, kind: "chit", chit, response: response(idx, "ChitPick", id) });
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
case "DragPick": {
|
|
249
|
+
const seen = new Set();
|
|
250
|
+
const targets = sp.details.d.flat();
|
|
251
|
+
sp.details.c.forEach((chitId) => {
|
|
252
|
+
const chit = find(chitId);
|
|
253
|
+
targets.forEach((targetChitId) => {
|
|
254
|
+
const target = find(targetChitId);
|
|
255
|
+
const k = `${chitId}->${targetChitId}`;
|
|
256
|
+
if (chit && target && !seen.has(k)) {
|
|
257
|
+
seen.add(k);
|
|
258
|
+
options.push({
|
|
259
|
+
...base,
|
|
260
|
+
kind: "drag",
|
|
261
|
+
chit,
|
|
262
|
+
target,
|
|
263
|
+
response: response(idx, "DragPick", { chitId, targetChitId }),
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
case "ButtonPick": {
|
|
271
|
+
const buttonType = sp.details?.__buttonType;
|
|
272
|
+
pick.buttonType = buttonType;
|
|
273
|
+
options.push({
|
|
274
|
+
...base,
|
|
275
|
+
kind: "button",
|
|
276
|
+
button: this.makeButton(buttonType, sp.details),
|
|
277
|
+
response: response(idx, "ButtonPick", null),
|
|
278
|
+
});
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
return options;
|
|
284
|
+
}
|
|
285
|
+
makeButton(buttonType, details) {
|
|
286
|
+
const ButtonType = (buttonType && this.game.buttonLibrary?.[buttonType]) || (buttonType === "Confirm" ? Confirm : undefined);
|
|
287
|
+
const button = ButtonType ? new ButtonType() : new GameButton();
|
|
288
|
+
try {
|
|
289
|
+
button.deserialize(details, (id) => this.view.findChit(id));
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// the button is informational only; a failed deserialize shouldn't stop the bot
|
|
293
|
+
}
|
|
294
|
+
return button;
|
|
295
|
+
}
|
|
296
|
+
choose(prompt, candidates) {
|
|
297
|
+
const ai = this.game.ai;
|
|
298
|
+
const rules = ai?.rules ?? {};
|
|
299
|
+
const defaultRule = ai?.default;
|
|
300
|
+
const ruleFor = (o) => (o.key ? rules[o.key] : undefined) ?? defaultRule;
|
|
301
|
+
if (!candidates.some((o) => ruleFor(o))) {
|
|
302
|
+
candidates.forEach((o) => this.noteUntagged(o));
|
|
303
|
+
return { option: this.chooseLegacy(prompt, candidates), score: 0 };
|
|
304
|
+
}
|
|
305
|
+
const root = this.view.root;
|
|
306
|
+
const ctx = {
|
|
307
|
+
view: root,
|
|
308
|
+
me: root?.players.find((p) => p.id === this.playerId),
|
|
309
|
+
options: candidates,
|
|
310
|
+
prompt: { message: promptMessage(prompt), help: prompt.details?.help },
|
|
311
|
+
random: this.random,
|
|
312
|
+
memory: this.memory,
|
|
313
|
+
find: this.view.findChit,
|
|
314
|
+
params: this.options.params,
|
|
315
|
+
};
|
|
316
|
+
const scored = candidates.map((option) => {
|
|
317
|
+
const rule = ruleFor(option);
|
|
318
|
+
if (!rule) {
|
|
319
|
+
this.noteUntagged(option);
|
|
320
|
+
return { option, score: 0 };
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
return { option, ...normalizeScore(rule(option, ctx)) };
|
|
324
|
+
}
|
|
325
|
+
catch (e) {
|
|
326
|
+
this.stats.ruleErrors++;
|
|
327
|
+
this.warnOnce(`rule:${option.key ?? "default"}`, `rule "${option.key ?? "default"}" threw; scoring 0`, e);
|
|
328
|
+
return { option, score: 0 };
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
const scores = scored.map((s) => s.score);
|
|
332
|
+
let index = this.options.choose?.(scored, ctx);
|
|
333
|
+
if (index === undefined || index < 0 || index >= scored.length) {
|
|
334
|
+
const temperature = this.options.temperature ?? this.game.ai?.temperature;
|
|
335
|
+
index =
|
|
336
|
+
temperature !== undefined
|
|
337
|
+
? chooseSoftmax(scores, temperature, this.random)
|
|
338
|
+
: chooseIndex(scores, 1 - clamp(this.options.difficulty ?? 0.85, 0, 1), this.random);
|
|
339
|
+
}
|
|
340
|
+
this.options.onDecision?.({ playerId: this.playerId, prompt: ctx.prompt, scored, chosen: index, ctx });
|
|
341
|
+
return scored[index];
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The old demo behaviour, which games tune with `Game.demoPickWeight`: choose a pick weighted by
|
|
345
|
+
* (number of choices × demoPickWeight), then an option within it uniformly. For a DragPick the
|
|
346
|
+
* DragTarget group is chosen uniformly first, so splitting targets into groups steers drops.
|
|
347
|
+
*/
|
|
348
|
+
chooseLegacy(prompt, candidates) {
|
|
349
|
+
const picks = prompt.details?.picks ?? [];
|
|
350
|
+
const pickIndexes = [...new Set(candidates.map((o) => o.pick.index))];
|
|
351
|
+
const weights = pickIndexes.map((i) => {
|
|
352
|
+
const multiplier = this.game.demoPickWeight ? this.game.demoPickWeight(picks, picks[i]) : 1;
|
|
353
|
+
return pickWeight(picks[i]) * multiplier;
|
|
354
|
+
});
|
|
355
|
+
const chosen = pickIndexes[chooseWeighted(weights, this.random)];
|
|
356
|
+
const inPick = candidates.filter((o) => o.pick.index === chosen);
|
|
357
|
+
const pickRandom = (items) => items[Math.floor(this.random() * items.length)];
|
|
358
|
+
const sp = picks[chosen];
|
|
359
|
+
if (sp?.type === "DragPick") {
|
|
360
|
+
const groups = sp.details.d.filter((g) => g.length > 0);
|
|
361
|
+
if (groups.length > 0) {
|
|
362
|
+
const targetId = pickRandom(pickRandom(groups));
|
|
363
|
+
const matching = inPick.filter((o) => o.kind === "drag" && o.target.id === targetId);
|
|
364
|
+
if (matching.length > 0) {
|
|
365
|
+
return pickRandom(matching);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return pickRandom(inPick);
|
|
370
|
+
}
|
|
371
|
+
/** Last resort when no options could be mapped to chits in the view. */
|
|
372
|
+
async answerBlindly(prompt) {
|
|
373
|
+
const picks = prompt.details?.picks ?? [];
|
|
374
|
+
if (picks.length === 0) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const idx = Math.floor(this.random() * picks.length);
|
|
378
|
+
const sp = picks[idx];
|
|
379
|
+
const pickRandom = (items) => items[Math.floor(this.random() * items.length)];
|
|
380
|
+
let value = null;
|
|
381
|
+
if (sp.type === "ChitPick") {
|
|
382
|
+
value = pickRandom(sp.details.c);
|
|
383
|
+
}
|
|
384
|
+
else if (sp.type === "DragPick") {
|
|
385
|
+
value = { chitId: pickRandom(sp.details.c), targetChitId: pickRandom(sp.details.d.flat()) };
|
|
386
|
+
}
|
|
387
|
+
await this.withStallWarning(this.serverPrompts.resolvePrompt(prompt.id, response(idx, sp.type, value)), prompt);
|
|
388
|
+
this.stats.promptsAnswered++;
|
|
389
|
+
}
|
|
390
|
+
/** Undo the bot's last answer, remembering it as a dead end for that exact situation. */
|
|
391
|
+
async backtrack(prompt, reason) {
|
|
392
|
+
if (!prompt.canReset) {
|
|
393
|
+
this.stats.stuck++;
|
|
394
|
+
console.error(`[AI ${this.playerId}] ${reason} at "${promptMessage(prompt)}" and nothing can be undone`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const last = this.history.pop();
|
|
398
|
+
if (last) {
|
|
399
|
+
const dead = this.dead.get(last.fingerprint) ?? new Set();
|
|
400
|
+
dead.add(last.choice);
|
|
401
|
+
this.dead.set(last.fingerprint, dead);
|
|
402
|
+
this.setMemory(last.memoryBefore);
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
// We don't know what we're undoing (e.g. the bot was reconnected), so cap blind undos
|
|
406
|
+
if (++this.blindStepBacks > MAX_BLIND_STEP_BACKS) {
|
|
407
|
+
this.stats.stuck++;
|
|
408
|
+
console.error(`[AI ${this.playerId}] ${reason}; giving up after ${MAX_BLIND_STEP_BACKS} blind undos`);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
this.stats.stepBacks++;
|
|
413
|
+
await this.serverPrompts.stepBackPrompt(false);
|
|
414
|
+
}
|
|
415
|
+
fingerprint(prompt, viewSignature) {
|
|
416
|
+
return hashString(`${JSON.stringify(prompt)}|${viewSignature}`);
|
|
417
|
+
}
|
|
418
|
+
pruneDeadEndsExcept(fingerprint) {
|
|
419
|
+
const keep = this.dead.get(fingerprint);
|
|
420
|
+
this.dead.clear();
|
|
421
|
+
if (keep) {
|
|
422
|
+
this.dead.set(fingerprint, keep);
|
|
423
|
+
}
|
|
424
|
+
const visits = this.exhaustedVisits.get(fingerprint);
|
|
425
|
+
this.exhaustedVisits.clear();
|
|
426
|
+
if (visits) {
|
|
427
|
+
this.exhaustedVisits.set(fingerprint, visits);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
noteUntagged(option) {
|
|
431
|
+
if (option.kind === "button" && option.pick.buttonType === "Confirm") {
|
|
432
|
+
return; // engine-inserted confirms don't need rules
|
|
433
|
+
}
|
|
434
|
+
const message = option.pick.message || `(untagged ${option.pick.type})`;
|
|
435
|
+
const isNew = this.stats.untagged[message] === undefined;
|
|
436
|
+
this.stats.untagged[message] = (this.stats.untagged[message] ?? 0) + 1;
|
|
437
|
+
if (isNew && this.game.ai) {
|
|
438
|
+
this.log(`no rule for "${message}"${option.key ? ` (key "${option.key}")` : ""}; scoring it 0`);
|
|
439
|
+
}
|
|
440
|
+
else if (isNew && !this.warned.has("noai")) {
|
|
441
|
+
this.warned.add("noai");
|
|
442
|
+
this.log("this game has no `ai`; playing at random. Tag picks with .ai(key) and define rules with defineAi()");
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
async think() {
|
|
446
|
+
const t = this.options.thinkMs;
|
|
447
|
+
const ms = Array.isArray(t) ? t[0] + this.random() * Math.max(0, t[1] - t[0]) : (t ?? 0);
|
|
448
|
+
if (ms > 0) {
|
|
449
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Awaits the server's reaction to an answer. If it takes longer than `stallWarningMs`, warns and
|
|
454
|
+
* counts a stall, then keeps waiting: the answer is in flight, so the bot cannot know whether it
|
|
455
|
+
* was accepted until the server says so.
|
|
456
|
+
*/
|
|
457
|
+
async withStallWarning(p, prompt) {
|
|
458
|
+
const ms = this.options.stallWarningMs ?? 10000;
|
|
459
|
+
const timer = setTimeout(() => {
|
|
460
|
+
this._stalled = true;
|
|
461
|
+
this.stats.stalls++;
|
|
462
|
+
console.warn(`[AI ${this.playerId}] answered "${promptMessage(prompt)}" but the game hasn't changed after ${ms}ms. ` +
|
|
463
|
+
"If that pick's callback can leave state untouched, the match waits forever.");
|
|
464
|
+
}, ms);
|
|
465
|
+
try {
|
|
466
|
+
return await p;
|
|
467
|
+
}
|
|
468
|
+
finally {
|
|
469
|
+
clearTimeout(timer);
|
|
470
|
+
this._stalled = false;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
log(message) {
|
|
474
|
+
if (this.options.log !== false) {
|
|
475
|
+
console.info(`[AI ${this.playerId}] ${message}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
warnOnce(key, message, error) {
|
|
479
|
+
if (this.warned.has(key)) {
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
this.warned.add(key);
|
|
483
|
+
if (this.options.log !== false) {
|
|
484
|
+
console.warn(`[AI ${this.playerId}] ${message}`, ...(error ? [error] : []));
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
function response(idx, pickType, value) {
|
|
489
|
+
return { idx, pickType, value };
|
|
490
|
+
}
|
|
491
|
+
function choiceKey(option) {
|
|
492
|
+
return JSON.stringify(option.response);
|
|
493
|
+
}
|
|
494
|
+
function pickWeight(sp) {
|
|
495
|
+
switch (sp?.type) {
|
|
496
|
+
case "ChitPick":
|
|
497
|
+
return sp.details.c.length;
|
|
498
|
+
case "DragPick":
|
|
499
|
+
return sp.details.d.reduce((sum, targets) => sum + targets.length, 0);
|
|
500
|
+
default:
|
|
501
|
+
return 1;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function promptMessage(prompt) {
|
|
505
|
+
if (prompt.details?.message) {
|
|
506
|
+
return prompt.details.message;
|
|
507
|
+
}
|
|
508
|
+
const picks = prompt.details?.picks ?? [];
|
|
509
|
+
return picks
|
|
510
|
+
.map((p) => p.message)
|
|
511
|
+
.filter((m) => m)
|
|
512
|
+
.join(" or ");
|
|
513
|
+
}
|
|
514
|
+
function clamp(n, min, max) {
|
|
515
|
+
return Math.min(max, Math.max(min, n));
|
|
516
|
+
}
|
|
517
|
+
function deepFreeze(value) {
|
|
518
|
+
const isPlain = Array.isArray(value) || (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype);
|
|
519
|
+
if (isPlain && !Object.isFrozen(value)) {
|
|
520
|
+
Object.freeze(value);
|
|
521
|
+
Object.values(value).forEach((v) => deepFreeze(v));
|
|
522
|
+
}
|
|
523
|
+
return value;
|
|
524
|
+
}
|
|
525
|
+
//# sourceMappingURL=AiClientPrompts.js.map
|