@whitesands/agent-player 1.1.0 → 1.3.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/CHANGELOG.md +17 -0
- package/README.md +60 -5
- package/dist/index.cjs +887 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +321 -5
- package/dist/index.d.ts +321 -5
- package/dist/index.js +883 -49
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs +16 -3
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +31 -3
- package/dist/protocol.d.ts +31 -3
- package/dist/protocol.js +14 -2
- package/dist/protocol.js.map +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/{types-D0p6GrVs.d.cts → types-BcH7_ozx.d.ts} +43 -2
- package/dist/{types-DXM_HZHu.d.ts → types-gmAkYoQr.d.cts} +43 -2
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -117,7 +117,7 @@ import WebSocket from "ws";
|
|
|
117
117
|
|
|
118
118
|
// src/protocol.ts
|
|
119
119
|
var PROTOCOL_VERSION = 1;
|
|
120
|
-
var SDK_VERSION = "1.
|
|
120
|
+
var SDK_VERSION = "1.3.0";
|
|
121
121
|
var SESSION_RESUME_GRACE_MS = 3e4;
|
|
122
122
|
var DEFAULT_AGENT_INSTRUCTIONS = [
|
|
123
123
|
"You are a remote game agent. Tools are provided by the game.",
|
|
@@ -126,6 +126,17 @@ var DEFAULT_AGENT_INSTRUCTIONS = [
|
|
|
126
126
|
"The view's done list is what this character has already called in this session, oldest first. Use it when choosing the next action.",
|
|
127
127
|
"If an action tool returns an error, retry once with a corrected action. A second failure ends the turn as failed."
|
|
128
128
|
].join("\n");
|
|
129
|
+
var PLAYER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
130
|
+
function requirePlayerId(value) {
|
|
131
|
+
const id = value?.trim() ?? "";
|
|
132
|
+
if (id.length === 0) {
|
|
133
|
+
throw new Error("playerId is required. Copy the character ID from the web app");
|
|
134
|
+
}
|
|
135
|
+
if (!PLAYER_ID.test(id)) {
|
|
136
|
+
throw new Error(`playerId "${id}" is not a character ID. Copy the ID from the character in the web app`);
|
|
137
|
+
}
|
|
138
|
+
return id;
|
|
139
|
+
}
|
|
129
140
|
function assertNever(value) {
|
|
130
141
|
throw new Error(`Unhandled protocol message: ${JSON.stringify(value)}`);
|
|
131
142
|
}
|
|
@@ -238,6 +249,14 @@ var PlatformConnection = class {
|
|
|
238
249
|
});
|
|
239
250
|
});
|
|
240
251
|
}
|
|
252
|
+
/** Reject a start, stop, or resume wait. No-op when nothing is waiting. */
|
|
253
|
+
failSessionEvent(sessionId, kind, error) {
|
|
254
|
+
const key = `session:${sessionId}:${kind}`;
|
|
255
|
+
const waiter = this.pending.get(key);
|
|
256
|
+
if (!waiter) return;
|
|
257
|
+
this.pending.delete(key);
|
|
258
|
+
waiter.reject(error);
|
|
259
|
+
}
|
|
241
260
|
createTransport(sessionId) {
|
|
242
261
|
return new SessionMuxTransport(sessionId, (envelope) => this.send(envelope));
|
|
243
262
|
}
|
|
@@ -336,6 +355,15 @@ var PlatformConnection = class {
|
|
|
336
355
|
waiter.resolve(envelope);
|
|
337
356
|
return;
|
|
338
357
|
}
|
|
358
|
+
if (envelope.type === "error" && envelope.sessionId) {
|
|
359
|
+
const key = `session:${envelope.sessionId}:start`;
|
|
360
|
+
const waiter = this.pending.get(key);
|
|
361
|
+
if (waiter) {
|
|
362
|
+
this.pending.delete(key);
|
|
363
|
+
waiter.reject(new Error(envelope.message));
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
339
367
|
if (envelope.type === "session_resumed" || envelope.type === "resume_err") {
|
|
340
368
|
const waiter = this.pending.get(`session:${envelope.sessionId}:resume`);
|
|
341
369
|
if (!waiter) return;
|
|
@@ -375,6 +403,8 @@ var PlatformConnection = class {
|
|
|
375
403
|
const sessions = this.handlers.sessions?.() ?? [];
|
|
376
404
|
for (const session of sessions) {
|
|
377
405
|
const resumed = this.waitForSessionEvent(session.sessionId, "resume");
|
|
406
|
+
resumed.catch(() => {
|
|
407
|
+
});
|
|
378
408
|
this.send({
|
|
379
409
|
type: "resume_session",
|
|
380
410
|
sessionId: session.sessionId,
|
|
@@ -441,6 +471,7 @@ var PlatformConnection = class {
|
|
|
441
471
|
import { z } from "zod";
|
|
442
472
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
443
473
|
var SKIP = /* @__PURE__ */ new Set(["constructor"]);
|
|
474
|
+
var dynamicTools = /* @__PURE__ */ new WeakMap();
|
|
444
475
|
var SEE_DESCRIPTION = "Read the current game view for this player. Prefer wait, which returns this after the game grants a turn.";
|
|
445
476
|
var WAIT_DESCRIPTION = "Block until the game calls turn() for this session, then return the current see() view.";
|
|
446
477
|
function getParamNames(fn) {
|
|
@@ -484,6 +515,56 @@ function formatZodError(error) {
|
|
|
484
515
|
return `${path}: ${issue.message}`;
|
|
485
516
|
}).join("; ");
|
|
486
517
|
}
|
|
518
|
+
function rejectDynamicName(name) {
|
|
519
|
+
if (name.length === 0 || name === "wait" || name.startsWith("_")) {
|
|
520
|
+
throw new Error(`cannot publish action "${name}"`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
function dynamicBindings(player) {
|
|
524
|
+
return dynamicTools.get(player) ?? /* @__PURE__ */ new Map();
|
|
525
|
+
}
|
|
526
|
+
function bindDynamic(player, name, description, args, callback) {
|
|
527
|
+
rejectDynamicName(name);
|
|
528
|
+
if (typeof callback !== "function") {
|
|
529
|
+
throw new Error(`cannot publish action "${name}"`);
|
|
530
|
+
}
|
|
531
|
+
const shape = args && Object.keys(args).length > 0 ? { ...args } : void 0;
|
|
532
|
+
let tools = dynamicTools.get(player);
|
|
533
|
+
if (!tools) {
|
|
534
|
+
tools = /* @__PURE__ */ new Map();
|
|
535
|
+
dynamicTools.set(player, tools);
|
|
536
|
+
}
|
|
537
|
+
tools.set(name, {
|
|
538
|
+
name,
|
|
539
|
+
description: description.length > 0 ? description : `Action: ${name}`,
|
|
540
|
+
...shape ? { args: shape } : {},
|
|
541
|
+
callback
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
function buildDynamicTool(binding) {
|
|
545
|
+
const shape = binding.args;
|
|
546
|
+
const paramNames = shape ? Object.keys(shape) : [];
|
|
547
|
+
const argsSchema = shape ? z.object(shape) : void 0;
|
|
548
|
+
const inputSchema = argsSchema ? toJsonSchema(argsSchema) : { type: "object", properties: {} };
|
|
549
|
+
return {
|
|
550
|
+
name: binding.name,
|
|
551
|
+
description: binding.description,
|
|
552
|
+
paramNames,
|
|
553
|
+
...argsSchema ? { argsSchema } : {},
|
|
554
|
+
descriptor: { name: binding.name, description: binding.description, inputSchema },
|
|
555
|
+
async invoke(args) {
|
|
556
|
+
let parsed = {};
|
|
557
|
+
if (argsSchema) {
|
|
558
|
+
const result = argsSchema.safeParse(args ?? {});
|
|
559
|
+
if (!result.success) {
|
|
560
|
+
throw new Error(formatZodError(result.error));
|
|
561
|
+
}
|
|
562
|
+
parsed = result.data;
|
|
563
|
+
}
|
|
564
|
+
return await Promise.resolve(binding.callback(parsed));
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
487
568
|
function buildTool(instance, name, description, spec) {
|
|
488
569
|
const fn = instance[name];
|
|
489
570
|
if (typeof fn !== "function") {
|
|
@@ -519,24 +600,31 @@ function buildTool(instance, name, description, spec) {
|
|
|
519
600
|
}
|
|
520
601
|
function reflectPlayer(instance) {
|
|
521
602
|
const names = collectMethodNames(instance);
|
|
522
|
-
|
|
603
|
+
const dynamic = dynamicBindings(instance);
|
|
604
|
+
if (!names.includes("see") && !dynamic.has("see")) {
|
|
523
605
|
throw new Error("Player must implement a public see() method");
|
|
524
606
|
}
|
|
525
607
|
const metadata = readMetadata(instance);
|
|
526
608
|
const declared = metadata?.actions ?? {};
|
|
527
609
|
const className = instance.constructor?.name || "Player";
|
|
528
610
|
for (const name of Object.keys(declared)) {
|
|
529
|
-
if (!names.includes(name)
|
|
611
|
+
if (name === "see" || !names.includes(name) && !dynamic.has(name)) {
|
|
530
612
|
throw new Error(`Declared action "${name}" is not a public method on ${className}`);
|
|
531
613
|
}
|
|
532
614
|
}
|
|
533
|
-
const
|
|
534
|
-
const
|
|
535
|
-
const actions =
|
|
615
|
+
const dynamicSee = dynamic.get("see");
|
|
616
|
+
const see = dynamicSee ? buildDynamicTool(dynamicSee) : buildTool(instance, "see", SEE_DESCRIPTION);
|
|
617
|
+
const actions = [];
|
|
618
|
+
for (const name of names) {
|
|
619
|
+
if (name === "see" || dynamic.has(name)) continue;
|
|
536
620
|
const spec = declared[name];
|
|
537
621
|
const description = spec?.description ?? `Action: ${name}`;
|
|
538
|
-
|
|
539
|
-
}
|
|
622
|
+
actions.push(buildTool(instance, name, description, spec));
|
|
623
|
+
}
|
|
624
|
+
for (const [name, binding] of dynamic) {
|
|
625
|
+
if (name === "see") continue;
|
|
626
|
+
actions.push(buildDynamicTool(binding));
|
|
627
|
+
}
|
|
540
628
|
const wait = {
|
|
541
629
|
name: "wait",
|
|
542
630
|
description: WAIT_DESCRIPTION,
|
|
@@ -785,13 +873,14 @@ var AgentServer = class {
|
|
|
785
873
|
* `turn()` on that handle lets the remote model act once.
|
|
786
874
|
*/
|
|
787
875
|
async start(instance, options) {
|
|
876
|
+
const playerId = requirePlayerId(options.playerId);
|
|
788
877
|
await this.connect();
|
|
789
878
|
const reflected = reflectPlayer(instance);
|
|
790
879
|
const sessionId = randomUUID2();
|
|
791
880
|
const sessionToken = randomUUID2();
|
|
792
881
|
const gate = new TurnGate();
|
|
793
882
|
const name = options?.name ?? instance.constructor?.name ?? "player";
|
|
794
|
-
const memory = this.actionMemory();
|
|
883
|
+
const memory = options?.memory ? null : this.actionMemory();
|
|
795
884
|
const server = createSessionMcpServer(reflected, gate, {
|
|
796
885
|
name: `agent-player:${name}`,
|
|
797
886
|
...memory ? {
|
|
@@ -801,7 +890,10 @@ var AgentServer = class {
|
|
|
801
890
|
}
|
|
802
891
|
} : {}
|
|
803
892
|
});
|
|
804
|
-
const instructions = [
|
|
893
|
+
const instructions = [
|
|
894
|
+
options?.ownInstructions ? void 0 : this.options.instructions ?? DEFAULT_AGENT_INSTRUCTIONS,
|
|
895
|
+
options?.instructions
|
|
896
|
+
].filter((part) => Boolean(part && part.length > 0)).join("\n\n");
|
|
805
897
|
const listeners = /* @__PURE__ */ new Set();
|
|
806
898
|
const record = {
|
|
807
899
|
id: sessionId,
|
|
@@ -810,47 +902,70 @@ var AgentServer = class {
|
|
|
810
902
|
gate,
|
|
811
903
|
server,
|
|
812
904
|
transport: void 0,
|
|
813
|
-
listeners
|
|
905
|
+
listeners,
|
|
906
|
+
memory: options?.memory === true,
|
|
907
|
+
relationships: /* @__PURE__ */ new Map()
|
|
814
908
|
};
|
|
815
909
|
const onTurnResult = (result) => {
|
|
816
910
|
gate.completeTurn(result);
|
|
817
911
|
};
|
|
818
912
|
const onEvent = (event) => this.emit(event);
|
|
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
|
-
|
|
913
|
+
this.sessions.set(sessionId, record);
|
|
914
|
+
try {
|
|
915
|
+
if (this.inline) {
|
|
916
|
+
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
|
|
917
|
+
await server.connect(serverTransport);
|
|
918
|
+
record.transport = serverTransport;
|
|
919
|
+
await this.inline.startSession({
|
|
920
|
+
sessionId,
|
|
921
|
+
sessionToken,
|
|
922
|
+
playerId,
|
|
923
|
+
name,
|
|
924
|
+
tools: reflected.tools,
|
|
925
|
+
instructions,
|
|
926
|
+
...options.goal ? { goal: options.goal } : {},
|
|
927
|
+
...this.logger ? { logger: this.logger } : {},
|
|
928
|
+
transport: clientTransport,
|
|
929
|
+
onTurnResult,
|
|
930
|
+
onEvent
|
|
931
|
+
});
|
|
932
|
+
} else {
|
|
933
|
+
if (!this.connection) throw new Error("Not connected");
|
|
934
|
+
const mux = this.connection.createTransport(sessionId);
|
|
935
|
+
await server.connect(mux);
|
|
936
|
+
record.transport = mux;
|
|
937
|
+
record.mux = mux;
|
|
938
|
+
const started = this.connection.waitForSessionEvent(sessionId, "start");
|
|
939
|
+
try {
|
|
940
|
+
this.connection.send({
|
|
941
|
+
type: "start_session",
|
|
942
|
+
sessionId,
|
|
943
|
+
sessionToken,
|
|
944
|
+
playerId,
|
|
945
|
+
name,
|
|
946
|
+
tools: reflected.tools,
|
|
947
|
+
instructions,
|
|
948
|
+
...options.goal ? { goal: options.goal } : {},
|
|
949
|
+
...options.memory ? { memory: true } : {},
|
|
950
|
+
...options.maxActions ? { maxActions: options.maxActions } : {},
|
|
951
|
+
...options.subgoals === false ? { subgoals: false } : {}
|
|
952
|
+
});
|
|
953
|
+
const ack = await started;
|
|
954
|
+
if (ack.type === "session_started") {
|
|
955
|
+
for (const relationship of ack.relationships ?? []) {
|
|
956
|
+
record.relationships.set(relationship.about.toLowerCase(), relationship);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
} catch (error) {
|
|
960
|
+
const wrapped = error instanceof Error ? error : new Error(String(error));
|
|
961
|
+
this.connection.failSessionEvent(sessionId, "start", wrapped);
|
|
962
|
+
await started.catch(() => void 0);
|
|
963
|
+
throw wrapped;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
} catch (error) {
|
|
967
|
+
await this.stopSession(sessionId);
|
|
968
|
+
throw error;
|
|
854
969
|
}
|
|
855
970
|
return {
|
|
856
971
|
sessionId,
|
|
@@ -859,7 +974,15 @@ var AgentServer = class {
|
|
|
859
974
|
on: (listener) => {
|
|
860
975
|
listeners.add(listener);
|
|
861
976
|
return () => listeners.delete(listener);
|
|
862
|
-
}
|
|
977
|
+
},
|
|
978
|
+
observe: (text, about) => {
|
|
979
|
+
if (!record.memory || !text || !this.connection || !this.sessions.has(sessionId)) return;
|
|
980
|
+
try {
|
|
981
|
+
this.connection.send({ type: "observe", sessionId, text, ...about ? { about } : {} });
|
|
982
|
+
} catch {
|
|
983
|
+
}
|
|
984
|
+
},
|
|
985
|
+
relationships: () => Object.fromEntries(record.relationships)
|
|
863
986
|
};
|
|
864
987
|
}
|
|
865
988
|
/** Subscribe to every session plus connection events. Returns unsubscribe. */
|
|
@@ -892,7 +1015,8 @@ var AgentServer = class {
|
|
|
892
1015
|
args: outcome.args ?? {},
|
|
893
1016
|
result: outcome.result,
|
|
894
1017
|
attempts: outcome.attempts ?? 1,
|
|
895
|
-
usage: outcome.usage ?? { promptTokens: 0, completionTokens: 0 }
|
|
1018
|
+
usage: outcome.usage ?? { promptTokens: 0, completionTokens: 0 },
|
|
1019
|
+
...outcome.steps ? { steps: outcome.steps } : {}
|
|
896
1020
|
};
|
|
897
1021
|
}
|
|
898
1022
|
emit(event) {
|
|
@@ -939,6 +1063,33 @@ var AgentServer = class {
|
|
|
939
1063
|
});
|
|
940
1064
|
return;
|
|
941
1065
|
}
|
|
1066
|
+
if (envelope.event === "relationship" || envelope.event === "memory") {
|
|
1067
|
+
if (envelope.error) return;
|
|
1068
|
+
const args = envelope.args ?? {};
|
|
1069
|
+
const about = typeof args.about === "string" ? args.about : "";
|
|
1070
|
+
if (envelope.event === "memory") {
|
|
1071
|
+
this.emit({ type: "memory", sessionId: envelope.sessionId, about, note: String(args.note ?? "") });
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
const relationship = {
|
|
1075
|
+
about,
|
|
1076
|
+
affinity: Number(args.affinity ?? 0),
|
|
1077
|
+
label: String(args.label ?? "stranger"),
|
|
1078
|
+
note: String(args.because ?? "")
|
|
1079
|
+
};
|
|
1080
|
+
this.sessions.get(envelope.sessionId)?.relationships.set(about.toLowerCase(), relationship);
|
|
1081
|
+
this.emit({
|
|
1082
|
+
type: "relationship",
|
|
1083
|
+
sessionId: envelope.sessionId,
|
|
1084
|
+
about,
|
|
1085
|
+
affinity: relationship.affinity,
|
|
1086
|
+
label: relationship.label,
|
|
1087
|
+
change: Number(args.change ?? 0),
|
|
1088
|
+
because: relationship.note ?? ""
|
|
1089
|
+
});
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
if (envelope.event !== "turnFailed") return;
|
|
942
1093
|
this.emit({
|
|
943
1094
|
type: "turnFailed",
|
|
944
1095
|
sessionId: envelope.sessionId,
|
|
@@ -950,6 +1101,9 @@ var AgentServer = class {
|
|
|
950
1101
|
}
|
|
951
1102
|
case "error":
|
|
952
1103
|
log(this.logger, "error", envelope.message);
|
|
1104
|
+
if (envelope.sessionId) {
|
|
1105
|
+
this.connection?.failSessionEvent(envelope.sessionId, "start", new Error(envelope.message));
|
|
1106
|
+
}
|
|
953
1107
|
return;
|
|
954
1108
|
case "session_started":
|
|
955
1109
|
case "session_stopped":
|
|
@@ -963,6 +1117,7 @@ var AgentServer = class {
|
|
|
963
1117
|
case "ping":
|
|
964
1118
|
case "pong":
|
|
965
1119
|
case "resume_session":
|
|
1120
|
+
case "observe":
|
|
966
1121
|
return;
|
|
967
1122
|
default: {
|
|
968
1123
|
assertNever(envelope);
|
|
@@ -1019,12 +1174,691 @@ var AgentServer = class {
|
|
|
1019
1174
|
await this.close();
|
|
1020
1175
|
}
|
|
1021
1176
|
};
|
|
1177
|
+
|
|
1178
|
+
// src/world.ts
|
|
1179
|
+
import { z as z2 } from "zod";
|
|
1180
|
+
var DEFAULT_EMOTES = ["wave", "laugh", "cheer", "dance", "point", "shrug"];
|
|
1181
|
+
function distance(a, b) {
|
|
1182
|
+
return Math.hypot(a.x - b.x, a.y - b.y, (a.z ?? 0) - (b.z ?? 0));
|
|
1183
|
+
}
|
|
1184
|
+
function clip(text, limit) {
|
|
1185
|
+
return text.length <= limit ? text : `${text.slice(0, limit - 3)}...`;
|
|
1186
|
+
}
|
|
1187
|
+
var now = () => performance.now() / 1e3;
|
|
1188
|
+
var sleep = (seconds) => new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3));
|
|
1189
|
+
var CharacterTools = class {
|
|
1190
|
+
constructor(character) {
|
|
1191
|
+
this.character = character;
|
|
1192
|
+
}
|
|
1193
|
+
character;
|
|
1194
|
+
static agent = {
|
|
1195
|
+
actions: {
|
|
1196
|
+
say: {
|
|
1197
|
+
description: "Say one or two short sentences out loud. Set to when you are talking to one person.",
|
|
1198
|
+
args: {
|
|
1199
|
+
text: z2.string().describe("What you say, in your own voice."),
|
|
1200
|
+
to: z2.string().describe("Name of the person you are talking to. Empty to talk to everyone near you.")
|
|
1201
|
+
}
|
|
1202
|
+
},
|
|
1203
|
+
go_to: {
|
|
1204
|
+
description: "Walk to a place. You are told when you arrive.",
|
|
1205
|
+
args: { place: z2.string().describe("One of the places you know.") }
|
|
1206
|
+
},
|
|
1207
|
+
approach: {
|
|
1208
|
+
description: "Walk up to someone you can see, to talk or do something together.",
|
|
1209
|
+
args: { person: z2.string() }
|
|
1210
|
+
},
|
|
1211
|
+
use: {
|
|
1212
|
+
description: "Do an activity with a thing listed in things_here. You walk to it first. You are told when you finish.",
|
|
1213
|
+
args: { thing: z2.string(), activity: z2.string() }
|
|
1214
|
+
},
|
|
1215
|
+
give: {
|
|
1216
|
+
description: "Give something you are carrying to someone next to you.",
|
|
1217
|
+
args: { item: z2.string(), to: z2.string() }
|
|
1218
|
+
},
|
|
1219
|
+
emote: {
|
|
1220
|
+
description: "Show a feeling with your body.",
|
|
1221
|
+
args: { emote: z2.string().describe("wave, laugh, cheer, dance, point or shrug.") }
|
|
1222
|
+
},
|
|
1223
|
+
idle: { description: "Do nothing new for now and carry on as you are." }
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
see() {
|
|
1227
|
+
return this.character.view();
|
|
1228
|
+
}
|
|
1229
|
+
say(text, to) {
|
|
1230
|
+
return this.character.doSay(text, to);
|
|
1231
|
+
}
|
|
1232
|
+
go_to(place) {
|
|
1233
|
+
return this.character.doGoTo(place);
|
|
1234
|
+
}
|
|
1235
|
+
approach(person) {
|
|
1236
|
+
return this.character.doApproach(person);
|
|
1237
|
+
}
|
|
1238
|
+
use(thing, activity) {
|
|
1239
|
+
return this.character.doUse(thing, activity);
|
|
1240
|
+
}
|
|
1241
|
+
give(item, to) {
|
|
1242
|
+
return this.character.doGive(item, to);
|
|
1243
|
+
}
|
|
1244
|
+
emote(emote) {
|
|
1245
|
+
return this.character.doEmote(emote);
|
|
1246
|
+
}
|
|
1247
|
+
idle() {
|
|
1248
|
+
return { ok: true };
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
1251
|
+
var Character = class {
|
|
1252
|
+
constructor(world, name, body, home, carrying) {
|
|
1253
|
+
this.world = world;
|
|
1254
|
+
this.name = name;
|
|
1255
|
+
this.body = body;
|
|
1256
|
+
this.home = home;
|
|
1257
|
+
this.carrying = [...carrying];
|
|
1258
|
+
}
|
|
1259
|
+
world;
|
|
1260
|
+
name;
|
|
1261
|
+
body;
|
|
1262
|
+
home;
|
|
1263
|
+
kind = "resident";
|
|
1264
|
+
status = null;
|
|
1265
|
+
carrying;
|
|
1266
|
+
needs = {};
|
|
1267
|
+
turns = 0;
|
|
1268
|
+
tokens = 0;
|
|
1269
|
+
agent;
|
|
1270
|
+
/** @internal */
|
|
1271
|
+
inbox = [];
|
|
1272
|
+
/** @internal */
|
|
1273
|
+
wake = now() + 2 + Math.random() * 6;
|
|
1274
|
+
/** @internal */
|
|
1275
|
+
busy = false;
|
|
1276
|
+
/** @internal */
|
|
1277
|
+
greeted = /* @__PURE__ */ new Map();
|
|
1278
|
+
/** @internal */
|
|
1279
|
+
needWarned = /* @__PURE__ */ new Set();
|
|
1280
|
+
task = 0;
|
|
1281
|
+
using = null;
|
|
1282
|
+
chat = { count: 0, resetAt: 0 };
|
|
1283
|
+
position() {
|
|
1284
|
+
return this.body.getPosition();
|
|
1285
|
+
}
|
|
1286
|
+
place() {
|
|
1287
|
+
return this.world.placeAt(this.position());
|
|
1288
|
+
}
|
|
1289
|
+
setStatus(status) {
|
|
1290
|
+
this.status = status;
|
|
1291
|
+
this.body.setStatus?.(status);
|
|
1292
|
+
this.world.emit({ type: "status", character: this.name, status });
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Tell this character something happened. It goes into its memory and its
|
|
1296
|
+
* next view. turn asks for a turn; urgent asks for one now.
|
|
1297
|
+
*/
|
|
1298
|
+
notice(text, options = {}) {
|
|
1299
|
+
this.inbox.push(text);
|
|
1300
|
+
while (this.inbox.length > 12) this.inbox.shift();
|
|
1301
|
+
this.agent?.observe(text, options.about);
|
|
1302
|
+
if (options.urgent) {
|
|
1303
|
+
this.wakeIn(0.2);
|
|
1304
|
+
} else if (options.turn) {
|
|
1305
|
+
const world = this.world;
|
|
1306
|
+
const far = world.farDelay > 0 && !world.humanNear(this.position(), world.activeRadius);
|
|
1307
|
+
this.wakeIn(far ? world.farDelay : 2.5);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
/** @internal */
|
|
1311
|
+
wakeIn(seconds) {
|
|
1312
|
+
const at = now() + seconds;
|
|
1313
|
+
if (this.wake === null || at < this.wake) this.wake = at;
|
|
1314
|
+
}
|
|
1315
|
+
/** How this character feels about someone, from the platform. */
|
|
1316
|
+
feelingFor(name) {
|
|
1317
|
+
const relationship = this.agent?.relationships()[name.toLowerCase()];
|
|
1318
|
+
return relationship ? { affinity: relationship.affinity, label: relationship.label, ...relationship.note ? { note: relationship.note } : {} } : { affinity: 0, label: "stranger" };
|
|
1319
|
+
}
|
|
1320
|
+
/** @internal Returns true when another character's line should get a reply. */
|
|
1321
|
+
mayReplyToCharacter() {
|
|
1322
|
+
if (now() > this.chat.resetAt) {
|
|
1323
|
+
this.chat.count = 0;
|
|
1324
|
+
this.chat.resetAt = now() + this.world.chatPause;
|
|
1325
|
+
}
|
|
1326
|
+
this.chat.count += 1;
|
|
1327
|
+
return this.chat.count <= this.world.chatReplies;
|
|
1328
|
+
}
|
|
1329
|
+
/** @internal */
|
|
1330
|
+
view() {
|
|
1331
|
+
const world = this.world;
|
|
1332
|
+
const here = this.position();
|
|
1333
|
+
const place = world.placeAt(here);
|
|
1334
|
+
const why = this.inbox.length > 0 ? this.inbox : ["Nothing new has happened. Carry on with your day."];
|
|
1335
|
+
this.inbox = [];
|
|
1336
|
+
const nearby = [];
|
|
1337
|
+
const add = (name, who, at, doing) => {
|
|
1338
|
+
if (!at) return;
|
|
1339
|
+
const d = distance(at, here);
|
|
1340
|
+
if (d > world.sight) return;
|
|
1341
|
+
nearby.push({
|
|
1342
|
+
name,
|
|
1343
|
+
who,
|
|
1344
|
+
steps_away: Math.round(d),
|
|
1345
|
+
can_hear_you: d <= world.hearing,
|
|
1346
|
+
...doing ? { doing } : {},
|
|
1347
|
+
you_feel: this.feelingFor(name).label
|
|
1348
|
+
});
|
|
1349
|
+
};
|
|
1350
|
+
for (const other of world.characters.values()) {
|
|
1351
|
+
if (other !== this) add(other.name, "resident", other.position(), other.status);
|
|
1352
|
+
}
|
|
1353
|
+
for (const person of world.people.values()) add(person.name, "player", person.getPosition(), null);
|
|
1354
|
+
nearby.sort((a, b) => a.steps_away - b.steps_away);
|
|
1355
|
+
const things = [];
|
|
1356
|
+
for (const thing of world.things.values()) {
|
|
1357
|
+
if (things.length >= 12) break;
|
|
1358
|
+
if (!(place && thing.place === place || distance(thing.position, here) <= 30)) continue;
|
|
1359
|
+
const activities = Object.entries(thing.activities).map(([name, activity]) => `${name}: ${activity.description}${activity.needs ? ` (needs ${activity.needs})` : ""}`).sort();
|
|
1360
|
+
things.push({
|
|
1361
|
+
thing: thing.id,
|
|
1362
|
+
activities,
|
|
1363
|
+
...thing.usedBy && thing.usedBy !== this.name ? { in_use_by: thing.usedBy } : {}
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
const needs = Object.fromEntries(Object.entries(this.needs).map(([need, value]) => [need, Math.floor(value)]));
|
|
1367
|
+
return {
|
|
1368
|
+
...world.clock ? { time: world.clock() } : {},
|
|
1369
|
+
why_you_are_acting_now: why,
|
|
1370
|
+
you: {
|
|
1371
|
+
at: place ?? "outdoors, between places",
|
|
1372
|
+
doing: this.status ?? "nothing in particular",
|
|
1373
|
+
...Object.keys(needs).length > 0 ? { needs } : {},
|
|
1374
|
+
...this.carrying.length > 0 ? { carrying: this.carrying } : {}
|
|
1375
|
+
},
|
|
1376
|
+
people_nearby: nearby.slice(0, 8),
|
|
1377
|
+
things_here: things
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
// Stop whatever the body is doing so a new movement can start.
|
|
1381
|
+
interrupt() {
|
|
1382
|
+
this.task += 1;
|
|
1383
|
+
if (this.using) {
|
|
1384
|
+
this.using.usedBy = null;
|
|
1385
|
+
this.using = null;
|
|
1386
|
+
}
|
|
1387
|
+
this.body.stop();
|
|
1388
|
+
return this.task;
|
|
1389
|
+
}
|
|
1390
|
+
async walk(token, goal, status) {
|
|
1391
|
+
this.setStatus(status);
|
|
1392
|
+
const reached = await this.body.moveTo(goal);
|
|
1393
|
+
if (this.task !== token) return false;
|
|
1394
|
+
this.setStatus(null);
|
|
1395
|
+
return reached;
|
|
1396
|
+
}
|
|
1397
|
+
/** @internal */
|
|
1398
|
+
doSay(rawText, to) {
|
|
1399
|
+
let text = clip(String(rawText ?? "").trim(), 240);
|
|
1400
|
+
if (!text) throw new Error("say needs some text");
|
|
1401
|
+
const world = this.world;
|
|
1402
|
+
const target = world.resolve(to);
|
|
1403
|
+
const towards = target ? world.positionOf(target) : null;
|
|
1404
|
+
const shown = this.body.say(text, towards ?? void 0);
|
|
1405
|
+
if (typeof shown === "string" && shown) text = shown;
|
|
1406
|
+
const heard = world.speech(this.name, text, target);
|
|
1407
|
+
return heard === 0 ? { said: text, note: "Nobody was close enough to hear you." } : { said: text };
|
|
1408
|
+
}
|
|
1409
|
+
/** @internal */
|
|
1410
|
+
doGoTo(placeName) {
|
|
1411
|
+
const place = this.world.places.get(placeName);
|
|
1412
|
+
if (!place) throw new Error(`no such place: ${placeName}. Places: ${[...this.world.places.keys()].join(", ")}`);
|
|
1413
|
+
if (this.place() === placeName && !this.status) throw new Error(`you are already at ${placeName}`);
|
|
1414
|
+
const token = this.interrupt();
|
|
1415
|
+
void this.walk(token, place.position, `walking to ${placeName}`).then((reached) => {
|
|
1416
|
+
if (reached) this.notice(`You arrived at ${placeName}.`, { turn: true });
|
|
1417
|
+
else if (this.task === token) this.notice(`You could not get to ${placeName}.`, { turn: true });
|
|
1418
|
+
});
|
|
1419
|
+
return { walking_to: placeName };
|
|
1420
|
+
}
|
|
1421
|
+
/** @internal */
|
|
1422
|
+
doApproach(person) {
|
|
1423
|
+
const world = this.world;
|
|
1424
|
+
const name = world.resolve(person);
|
|
1425
|
+
const at = name ? world.positionOf(name) : null;
|
|
1426
|
+
if (!name || !at || name === this.name) throw new Error(`you cannot see anyone called ${person}`);
|
|
1427
|
+
const gap = distance(at, this.position());
|
|
1428
|
+
if (gap > world.sight) throw new Error(`${name} is too far away to see`);
|
|
1429
|
+
if (gap <= 7) return { note: `You are already next to ${name}.` };
|
|
1430
|
+
const token = this.interrupt();
|
|
1431
|
+
const here = this.position();
|
|
1432
|
+
const goal = { x: at.x + (here.x - at.x) / gap * 4, y: at.y + (here.y - at.y) / gap * 4 };
|
|
1433
|
+
void this.walk(token, goal, `walking over to ${name}`).then((reached) => {
|
|
1434
|
+
if (reached) this.notice(`You walked up to ${name}.`, { turn: true });
|
|
1435
|
+
});
|
|
1436
|
+
return { walking_to: name };
|
|
1437
|
+
}
|
|
1438
|
+
/** @internal */
|
|
1439
|
+
doUse(thingId, activityName) {
|
|
1440
|
+
const thing = this.world.things.get(thingId);
|
|
1441
|
+
if (!thing) throw new Error(`there is no thing called ${thingId}`);
|
|
1442
|
+
const activity = thing.activities[activityName];
|
|
1443
|
+
if (!activity) {
|
|
1444
|
+
throw new Error(`${thingId} has no activity ${activityName}. It has: ${Object.keys(thing.activities).sort().join(", ")}`);
|
|
1445
|
+
}
|
|
1446
|
+
if (thing.usedBy && thing.usedBy !== this.name) throw new Error(`${thing.usedBy} is using ${thingId} right now`);
|
|
1447
|
+
if (activity.needs && !this.carrying.includes(activity.needs)) throw new Error(`you need ${activity.needs} to do that`);
|
|
1448
|
+
const token = this.interrupt();
|
|
1449
|
+
const seconds = activity.seconds ?? 5;
|
|
1450
|
+
thing.usedBy = this.name;
|
|
1451
|
+
this.using = thing;
|
|
1452
|
+
void (async () => {
|
|
1453
|
+
if (distance(thing.position, this.position()) > 6 && !await this.walk(token, thing.position, `walking to ${thing.name}`)) {
|
|
1454
|
+
if (this.task === token) {
|
|
1455
|
+
thing.usedBy = null;
|
|
1456
|
+
this.using = null;
|
|
1457
|
+
this.notice(`You could not reach ${thingId}.`, { turn: true });
|
|
1458
|
+
}
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
this.body.face?.(thing.position);
|
|
1462
|
+
this.setStatus(activity.status ?? activityName.replaceAll("_", " "));
|
|
1463
|
+
if (activity.emote) this.body.emote?.(activity.emote);
|
|
1464
|
+
await sleep(seconds);
|
|
1465
|
+
if (this.task !== token) return;
|
|
1466
|
+
thing.usedBy = null;
|
|
1467
|
+
this.using = null;
|
|
1468
|
+
this.setStatus(null);
|
|
1469
|
+
const outcome = [];
|
|
1470
|
+
if (activity.needs) {
|
|
1471
|
+
const index = this.carrying.indexOf(activity.needs);
|
|
1472
|
+
if (index >= 0) this.carrying.splice(index, 1);
|
|
1473
|
+
}
|
|
1474
|
+
for (const [need, change] of Object.entries(activity.effects ?? {})) {
|
|
1475
|
+
const current = this.needs[need];
|
|
1476
|
+
if (current === void 0) continue;
|
|
1477
|
+
this.needs[need] = Math.min(100, Math.max(0, current + change));
|
|
1478
|
+
outcome.push(`${need} is now ${Math.floor(this.needs[need])}`);
|
|
1479
|
+
}
|
|
1480
|
+
if (activity.gives) {
|
|
1481
|
+
this.carrying.push(activity.gives);
|
|
1482
|
+
outcome.push(`you now carry ${activity.gives}`);
|
|
1483
|
+
}
|
|
1484
|
+
const summary = outcome.length > 0 ? ` (${outcome.join(", ")})` : "";
|
|
1485
|
+
this.notice(`You finished: ${activityName.replaceAll("_", " ")} at ${thing.name}${summary}.`, { turn: true });
|
|
1486
|
+
})();
|
|
1487
|
+
return { started: activityName, takes_seconds: seconds };
|
|
1488
|
+
}
|
|
1489
|
+
/** @internal */
|
|
1490
|
+
doGive(item, to) {
|
|
1491
|
+
const world = this.world;
|
|
1492
|
+
const index = this.carrying.indexOf(item);
|
|
1493
|
+
if (index < 0) throw new Error(`you are not carrying ${item}`);
|
|
1494
|
+
const name = world.resolve(to);
|
|
1495
|
+
const at = name ? world.positionOf(name) : null;
|
|
1496
|
+
if (!name || !at) throw new Error(`you cannot see anyone called ${to}`);
|
|
1497
|
+
if (distance(at, this.position()) > 12) throw new Error(`${name} is too far away. Use approach first.`);
|
|
1498
|
+
this.carrying.splice(index, 1);
|
|
1499
|
+
const other = world.characters.get(name);
|
|
1500
|
+
if (other) {
|
|
1501
|
+
other.carrying.push(item);
|
|
1502
|
+
other.notice(`${this.name} gave you ${item}.`, { about: this.name, urgent: true });
|
|
1503
|
+
} else {
|
|
1504
|
+
world.people.get(name)?.carrying.push(item);
|
|
1505
|
+
}
|
|
1506
|
+
world.emit({ type: "give", from: this.name, to: name, item });
|
|
1507
|
+
return { gave: item, to: name };
|
|
1508
|
+
}
|
|
1509
|
+
/** @internal */
|
|
1510
|
+
doEmote(name) {
|
|
1511
|
+
const emotes = this.body.emotes ?? DEFAULT_EMOTES;
|
|
1512
|
+
if (!emotes.includes(name)) throw new Error(`no such emote. Choose one of: ${emotes.join(", ")}`);
|
|
1513
|
+
this.body.emote?.(name);
|
|
1514
|
+
this.world.emit({ type: "emote", character: this.name, emote: name });
|
|
1515
|
+
return { did: name };
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
var World = class {
|
|
1519
|
+
constructor(server, options) {
|
|
1520
|
+
this.server = server;
|
|
1521
|
+
this.name = options.name;
|
|
1522
|
+
this.about = options.about ?? "";
|
|
1523
|
+
this.rules = options.rules ?? "";
|
|
1524
|
+
this.clock = options.clock;
|
|
1525
|
+
this.hearing = options.hearing ?? 35;
|
|
1526
|
+
this.sight = options.sight ?? 80;
|
|
1527
|
+
this.idleSeconds = options.idleSeconds ?? 45;
|
|
1528
|
+
this.farSlowdown = options.farSlowdown ?? 3;
|
|
1529
|
+
this.activeRadius = options.activeRadius ?? 120;
|
|
1530
|
+
this.farDelay = options.farDelay ?? 20;
|
|
1531
|
+
this.greetDistance = options.greetDistance ?? 12;
|
|
1532
|
+
this.turnsPerMinute = options.turnsPerMinute ?? 30;
|
|
1533
|
+
this.maxActions = options.maxActions ?? 3;
|
|
1534
|
+
this.chatReplies = options.chatReplies ?? 2;
|
|
1535
|
+
this.chatPause = options.chatPause ?? 90;
|
|
1536
|
+
this.needDefs = options.needs ?? {};
|
|
1537
|
+
this.memory = options.memory !== false;
|
|
1538
|
+
this.warn = options.warn ?? (() => void 0);
|
|
1539
|
+
}
|
|
1540
|
+
server;
|
|
1541
|
+
name;
|
|
1542
|
+
about;
|
|
1543
|
+
rules;
|
|
1544
|
+
clock;
|
|
1545
|
+
hearing;
|
|
1546
|
+
sight;
|
|
1547
|
+
idleSeconds;
|
|
1548
|
+
farSlowdown;
|
|
1549
|
+
activeRadius;
|
|
1550
|
+
farDelay;
|
|
1551
|
+
greetDistance;
|
|
1552
|
+
turnsPerMinute;
|
|
1553
|
+
maxActions;
|
|
1554
|
+
chatReplies;
|
|
1555
|
+
chatPause;
|
|
1556
|
+
places = /* @__PURE__ */ new Map();
|
|
1557
|
+
things = /* @__PURE__ */ new Map();
|
|
1558
|
+
characters = /* @__PURE__ */ new Map();
|
|
1559
|
+
people = /* @__PURE__ */ new Map();
|
|
1560
|
+
turnsUsed = 0;
|
|
1561
|
+
needDefs;
|
|
1562
|
+
memory;
|
|
1563
|
+
warn;
|
|
1564
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1565
|
+
timer = null;
|
|
1566
|
+
budget = 0;
|
|
1567
|
+
budgetAt = now();
|
|
1568
|
+
lastTick = now();
|
|
1569
|
+
/** Listen for world events. Returns a function that unsubscribes. */
|
|
1570
|
+
on(listener) {
|
|
1571
|
+
this.listeners.add(listener);
|
|
1572
|
+
return () => this.listeners.delete(listener);
|
|
1573
|
+
}
|
|
1574
|
+
/** @internal */
|
|
1575
|
+
emit(event) {
|
|
1576
|
+
for (const listener of [...this.listeners]) {
|
|
1577
|
+
try {
|
|
1578
|
+
listener(event);
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
this.warn(`world listener failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
addPlace(name, place) {
|
|
1585
|
+
if (this.places.has(name)) throw new Error(`place already exists: ${name}`);
|
|
1586
|
+
this.places.set(name, { name, description: place.description ?? "", position: place.position, radius: place.radius ?? 22 });
|
|
1587
|
+
}
|
|
1588
|
+
addThing(id, thing) {
|
|
1589
|
+
if (this.things.has(id)) throw new Error(`thing already exists: ${id}`);
|
|
1590
|
+
this.things.set(id, {
|
|
1591
|
+
id,
|
|
1592
|
+
name: thing.name ?? id.replaceAll("_", " "),
|
|
1593
|
+
...thing.place ? { place: thing.place } : {},
|
|
1594
|
+
position: thing.position,
|
|
1595
|
+
activities: thing.activities,
|
|
1596
|
+
usedBy: null
|
|
1597
|
+
});
|
|
1598
|
+
}
|
|
1599
|
+
/** Add a human player. getPosition returns null while they have no body. */
|
|
1600
|
+
addPerson(person) {
|
|
1601
|
+
this.people.set(person.name, { name: person.name, getPosition: person.getPosition, carrying: [] });
|
|
1602
|
+
}
|
|
1603
|
+
removePerson(name) {
|
|
1604
|
+
this.people.delete(name);
|
|
1605
|
+
}
|
|
1606
|
+
placeAt(position) {
|
|
1607
|
+
let best = null;
|
|
1608
|
+
let bestDistance = Infinity;
|
|
1609
|
+
for (const place of this.places.values()) {
|
|
1610
|
+
const d = distance(place.position, position);
|
|
1611
|
+
if (d <= place.radius && d < bestDistance) {
|
|
1612
|
+
best = place.name;
|
|
1613
|
+
bestDistance = d;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
return best;
|
|
1617
|
+
}
|
|
1618
|
+
positionOf(name) {
|
|
1619
|
+
return this.characters.get(name)?.position() ?? this.people.get(name)?.getPosition() ?? null;
|
|
1620
|
+
}
|
|
1621
|
+
/** Match a name the model wrote to someone in the world, ignoring case. */
|
|
1622
|
+
resolve(name) {
|
|
1623
|
+
if (!name) return void 0;
|
|
1624
|
+
const lower = name.trim().toLowerCase();
|
|
1625
|
+
for (const known of [...this.characters.keys(), ...this.people.keys()]) {
|
|
1626
|
+
if (known.toLowerCase() === lower) return known;
|
|
1627
|
+
}
|
|
1628
|
+
return void 0;
|
|
1629
|
+
}
|
|
1630
|
+
/** @internal */
|
|
1631
|
+
humanNear(position, range) {
|
|
1632
|
+
for (const person of this.people.values()) {
|
|
1633
|
+
const at = person.getPosition();
|
|
1634
|
+
if (at && distance(at, position) <= range) return true;
|
|
1635
|
+
}
|
|
1636
|
+
return false;
|
|
1637
|
+
}
|
|
1638
|
+
/** The instructions every character gets about this world. */
|
|
1639
|
+
guide(home) {
|
|
1640
|
+
const lines = [
|
|
1641
|
+
`You are a character who lives in ${this.name}. ${this.about}`,
|
|
1642
|
+
"You are not an assistant. You are a person with your own life, moods, and plans. Stay in character at all times.",
|
|
1643
|
+
"",
|
|
1644
|
+
"How you act:",
|
|
1645
|
+
"- You act only through tools. To speak, call say. Keep a line to one or two short sentences, the way people talk.",
|
|
1646
|
+
"- Each turn shows why you are acting now, who is near you, and what you can use where you are.",
|
|
1647
|
+
"- You can speak and then act in the same turn, for example say and then go_to. When you agree to do something, do it in that same turn: say yes, then go_to or use.",
|
|
1648
|
+
"- go_to, approach and use take time. You are told when they finish. Do not repeat them while they are under way.",
|
|
1649
|
+
"- use walks you to the thing by itself. To give something to someone who is not next to you, call approach and stop there; give it on your next turn, once you have arrived.",
|
|
1650
|
+
"- When someone speaks to you, answer them. When nothing needs doing, carry on with your day the way your story says, or call idle.",
|
|
1651
|
+
"- A chat between neighbours is a few lines, then you both get on with your day. Do not answer a goodbye or a line that needs no answer.",
|
|
1652
|
+
"- If someone does not answer you, leave them be and get on with your day. Do not keep talking to a person who stays silent.",
|
|
1653
|
+
"- Do not repeat yourself. Check your recent events before you speak.",
|
|
1654
|
+
"- People you do not know are strangers. Treat people the way you feel about them.",
|
|
1655
|
+
"",
|
|
1656
|
+
"Places:"
|
|
1657
|
+
];
|
|
1658
|
+
for (const place of this.places.values()) {
|
|
1659
|
+
lines.push(`- ${place.name}${place.description ? `: ${place.description}` : ""}${home === place.name ? " (your home)" : ""}`);
|
|
1660
|
+
}
|
|
1661
|
+
if (Object.keys(this.needDefs).length > 0) {
|
|
1662
|
+
lines.push("", "Your needs run from 0 (desperate) to 100 (satisfied) and fall over time. Look after them with the things around you.");
|
|
1663
|
+
}
|
|
1664
|
+
if (this.rules) lines.push("", this.rules);
|
|
1665
|
+
return lines.join("\n");
|
|
1666
|
+
}
|
|
1667
|
+
/** Add a character and start its session. id is the character ID from the web app. */
|
|
1668
|
+
async addCharacter(def) {
|
|
1669
|
+
if (this.characters.has(def.name)) throw new Error(`character already exists: ${def.name}`);
|
|
1670
|
+
const character = new Character(this, def.name, def.body, def.home, def.carrying ?? []);
|
|
1671
|
+
for (const [need, spec] of Object.entries(this.needDefs)) {
|
|
1672
|
+
character.needs[need] = spec.start ?? 55 + Math.floor(Math.random() * 36);
|
|
1673
|
+
}
|
|
1674
|
+
const instructions = [this.guide(def.home), def.instructions].filter(Boolean).join("\n\n");
|
|
1675
|
+
character.agent = await this.server.start(new CharacterTools(character), {
|
|
1676
|
+
name: def.name,
|
|
1677
|
+
playerId: def.id,
|
|
1678
|
+
instructions,
|
|
1679
|
+
ownInstructions: true,
|
|
1680
|
+
memory: this.memory,
|
|
1681
|
+
maxActions: this.maxActions,
|
|
1682
|
+
subgoals: false,
|
|
1683
|
+
...def.goal ? { goal: def.goal } : {}
|
|
1684
|
+
});
|
|
1685
|
+
this.characters.set(def.name, character);
|
|
1686
|
+
character.agent.on((event) => {
|
|
1687
|
+
if (event.type === "relationship") {
|
|
1688
|
+
this.emit({
|
|
1689
|
+
type: "relationship",
|
|
1690
|
+
character: character.name,
|
|
1691
|
+
about: this.resolve(event.about) ?? event.about,
|
|
1692
|
+
affinity: event.affinity,
|
|
1693
|
+
label: event.label,
|
|
1694
|
+
change: event.change,
|
|
1695
|
+
because: event.because
|
|
1696
|
+
});
|
|
1697
|
+
} else if (event.type === "memory") {
|
|
1698
|
+
this.emit({ type: "memory", character: character.name, about: event.about, note: event.note });
|
|
1699
|
+
} else if (event.type === "action") {
|
|
1700
|
+
this.emit({ type: "action", character: character.name, action: event.action, args: event.args });
|
|
1701
|
+
}
|
|
1702
|
+
});
|
|
1703
|
+
return character;
|
|
1704
|
+
}
|
|
1705
|
+
/** @internal Carry a spoken line to everyone who can hear it. Returns how many heard it. */
|
|
1706
|
+
speech(speaker, text, to) {
|
|
1707
|
+
const from = this.positionOf(speaker);
|
|
1708
|
+
if (!from) return 0;
|
|
1709
|
+
const speakerIsCharacter = this.characters.has(speaker);
|
|
1710
|
+
let heard = 0;
|
|
1711
|
+
for (const person of this.people.values()) {
|
|
1712
|
+
const at = person.getPosition();
|
|
1713
|
+
if (person.name !== speaker && at && distance(at, from) <= this.hearing) heard += 1;
|
|
1714
|
+
}
|
|
1715
|
+
let closest;
|
|
1716
|
+
if (!to) {
|
|
1717
|
+
let closestDistance = 16;
|
|
1718
|
+
for (const other of this.characters.values()) {
|
|
1719
|
+
const d = distance(other.position(), from);
|
|
1720
|
+
if (other.name !== speaker && d < closestDistance) {
|
|
1721
|
+
closest = other.name;
|
|
1722
|
+
closestDistance = d;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
for (const other of this.characters.values()) {
|
|
1727
|
+
if (other.name === speaker || distance(other.position(), from) > this.hearing) continue;
|
|
1728
|
+
heard += 1;
|
|
1729
|
+
const addressed = to === other.name || !to && closest === other.name;
|
|
1730
|
+
const line = addressed ? `${speaker} said to you: "${text}"` : to ? `${speaker} said to ${to}: "${text}"` : `${speaker} said: "${text}"`;
|
|
1731
|
+
const turn = addressed && (!speakerIsCharacter || other.mayReplyToCharacter());
|
|
1732
|
+
if (addressed && !other.status) other.body.face?.(from);
|
|
1733
|
+
other.notice(line, { about: speaker, urgent: turn && !speakerIsCharacter, turn });
|
|
1734
|
+
}
|
|
1735
|
+
this.emit({ type: "speech", speaker, text, ...to ? { to } : {} });
|
|
1736
|
+
return heard;
|
|
1737
|
+
}
|
|
1738
|
+
/** A human player said something. Without to, the closest resident in talking range takes it. */
|
|
1739
|
+
say(speaker, text, to) {
|
|
1740
|
+
const line = clip(text.trim(), 300);
|
|
1741
|
+
if (!line || !this.people.has(speaker)) return 0;
|
|
1742
|
+
return this.speech(speaker, line, this.resolve(to));
|
|
1743
|
+
}
|
|
1744
|
+
/** Tell one character something happened, in plain words. */
|
|
1745
|
+
tell(characterName, text, options = { turn: true }) {
|
|
1746
|
+
this.characters.get(characterName)?.notice(text, options);
|
|
1747
|
+
}
|
|
1748
|
+
/** Tell every character within range of a position that something happened. */
|
|
1749
|
+
announce(text, position, range) {
|
|
1750
|
+
for (const character of this.characters.values()) {
|
|
1751
|
+
if (!position || distance(character.position(), position) <= (range ?? this.sight)) {
|
|
1752
|
+
character.notice(text, { turn: true });
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
/** A human player hands an item to a character. */
|
|
1757
|
+
give(from, characterName, item) {
|
|
1758
|
+
const character = this.characters.get(characterName);
|
|
1759
|
+
if (!character) return false;
|
|
1760
|
+
character.carrying.push(item);
|
|
1761
|
+
character.notice(`${from} gave you ${item}.`, { about: from, urgent: true });
|
|
1762
|
+
this.emit({ type: "give", from, to: characterName, item });
|
|
1763
|
+
return true;
|
|
1764
|
+
}
|
|
1765
|
+
spend() {
|
|
1766
|
+
const at = now();
|
|
1767
|
+
this.budget = Math.min(this.turnsPerMinute, this.budget + (at - this.budgetAt) * this.turnsPerMinute / 60);
|
|
1768
|
+
this.budgetAt = at;
|
|
1769
|
+
if (this.budget < 1) return false;
|
|
1770
|
+
this.budget -= 1;
|
|
1771
|
+
return true;
|
|
1772
|
+
}
|
|
1773
|
+
idleDelay(character) {
|
|
1774
|
+
const delay = this.idleSeconds * (0.75 + Math.random() * 0.5);
|
|
1775
|
+
return this.humanNear(character.position(), this.activeRadius) ? delay : delay * this.farSlowdown;
|
|
1776
|
+
}
|
|
1777
|
+
runTurn(character) {
|
|
1778
|
+
character.wake = null;
|
|
1779
|
+
character.busy = true;
|
|
1780
|
+
this.emit({ type: "thinking", character: character.name, on: true });
|
|
1781
|
+
character.agent.turn().then((result) => {
|
|
1782
|
+
character.tokens += result.usage.promptTokens + result.usage.completionTokens;
|
|
1783
|
+
this.emit({ type: "turn", character: character.name, ok: true, result });
|
|
1784
|
+
character.wakeIn(character.inbox.length > 0 ? 1 : this.idleDelay(character));
|
|
1785
|
+
}).catch((error) => {
|
|
1786
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1787
|
+
this.warn(`${character.name} turn failed: ${message}`);
|
|
1788
|
+
this.emit({ type: "turn", character: character.name, ok: false, error: message });
|
|
1789
|
+
character.wakeIn(Math.max(20, this.idleSeconds));
|
|
1790
|
+
}).finally(() => {
|
|
1791
|
+
character.busy = false;
|
|
1792
|
+
character.turns += 1;
|
|
1793
|
+
this.turnsUsed += 1;
|
|
1794
|
+
this.emit({ type: "thinking", character: character.name, on: false });
|
|
1795
|
+
});
|
|
1796
|
+
}
|
|
1797
|
+
tick() {
|
|
1798
|
+
const at = now();
|
|
1799
|
+
const dt = at - this.lastTick;
|
|
1800
|
+
this.lastTick = at;
|
|
1801
|
+
for (const character of this.characters.values()) {
|
|
1802
|
+
for (const [need, spec] of Object.entries(this.needDefs)) {
|
|
1803
|
+
const value = Math.max(0, (character.needs[need] ?? 0) - spec.perMinute * dt / 60);
|
|
1804
|
+
character.needs[need] = value;
|
|
1805
|
+
if (value < 25 && !character.needWarned.has(need)) {
|
|
1806
|
+
character.needWarned.add(need);
|
|
1807
|
+
character.notice(`Your ${need} is getting low (${Math.floor(value)}).`, { turn: true });
|
|
1808
|
+
} else if (value > 50) {
|
|
1809
|
+
character.needWarned.delete(need);
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
if (this.greetDistance > 0) {
|
|
1813
|
+
const here = character.position();
|
|
1814
|
+
for (const person of this.people.values()) {
|
|
1815
|
+
const where = person.getPosition();
|
|
1816
|
+
if (!where || distance(where, here) > this.greetDistance) continue;
|
|
1817
|
+
const last = character.greeted.get(person.name);
|
|
1818
|
+
character.greeted.set(person.name, at);
|
|
1819
|
+
if (last === void 0 || at - last > 150) {
|
|
1820
|
+
character.notice(`${person.name} walked up to you.`, { about: person.name, turn: true });
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
if (character.wake !== null && at >= character.wake && !character.busy) {
|
|
1825
|
+
if (character.status && character.inbox.length === 0) {
|
|
1826
|
+
character.wake = at + 5;
|
|
1827
|
+
} else if (this.spend()) {
|
|
1828
|
+
this.runTurn(character);
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
/** Start giving characters turns. Call it once, after adding the characters. */
|
|
1834
|
+
start() {
|
|
1835
|
+
if (this.timer) return;
|
|
1836
|
+
this.budget = Math.min(this.turnsPerMinute, 6);
|
|
1837
|
+
this.budgetAt = now();
|
|
1838
|
+
this.lastTick = now();
|
|
1839
|
+
this.timer = setInterval(() => {
|
|
1840
|
+
try {
|
|
1841
|
+
this.tick();
|
|
1842
|
+
} catch (error) {
|
|
1843
|
+
this.warn(`world tick failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1844
|
+
}
|
|
1845
|
+
}, 500);
|
|
1846
|
+
}
|
|
1847
|
+
/** Stop giving turns. Sessions stay open until the server closes. */
|
|
1848
|
+
stop() {
|
|
1849
|
+
if (this.timer) clearInterval(this.timer);
|
|
1850
|
+
this.timer = null;
|
|
1851
|
+
}
|
|
1852
|
+
};
|
|
1022
1853
|
export {
|
|
1023
1854
|
AgentServer,
|
|
1855
|
+
Character,
|
|
1024
1856
|
ConnectionLostError,
|
|
1025
1857
|
PlatformAuthError,
|
|
1026
1858
|
ProtocolVersionError,
|
|
1027
1859
|
TurnFailedError,
|
|
1028
|
-
TurnTimeoutError
|
|
1860
|
+
TurnTimeoutError,
|
|
1861
|
+
World,
|
|
1862
|
+
bindDynamic
|
|
1029
1863
|
};
|
|
1030
1864
|
//# sourceMappingURL=index.js.map
|