castle-web-cli 0.4.218 → 0.4.220
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/agent.js +11 -1
- package/dist/api.d.ts +3 -1
- package/dist/api.js +16 -5
- package/dist/cloudGit.d.ts +7 -0
- package/dist/cloudGit.js +13 -1
- package/dist/cloudGitServe.d.ts +25 -0
- package/dist/cloudGitServe.js +62 -21
- package/dist/get-deck.d.ts +17 -0
- package/dist/get-deck.js +149 -0
- package/dist/gitRemote.d.ts +38 -0
- package/dist/gitRemote.js +168 -0
- package/dist/index.js +90 -4
- package/dist/init.js +1 -1
- package/dist/login.js +30 -0
- package/dist/save-deck.d.ts +6 -1
- package/dist/save-deck.js +66 -6
- package/dist/webSourceSync.d.ts +83 -0
- package/dist/webSourceSync.js +229 -0
- package/kits/base/castle.json +1 -1
- package/kits/base/package-lock.json +1 -1
- package/kits/base/sdk/server/platformHandle.d.ts +2 -0
- package/kits/base/sdk/server/wrapper.d.ts +34 -0
- package/kits/base/sdk/server/wrapper.js +154 -6
- package/package.json +1 -1
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as api from './api.js';
|
|
4
|
+
import { atomicWriteFileSync } from './atomicFile.js';
|
|
5
|
+
import { readCastleJson } from './castleJson.js';
|
|
6
|
+
import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
|
|
7
|
+
// Which saved source a deck folder came from. `web_deck_sources` holds one row per deck and
|
|
8
|
+
// mints a fresh `s3Key` on every save, so the key names one saved version exactly; the folder
|
|
9
|
+
// records the key it last fetched or saved, and a save compares it with the server's before
|
|
10
|
+
// writing over someone else's newer save.
|
|
11
|
+
//
|
|
12
|
+
// It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
|
|
13
|
+
// save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
|
|
14
|
+
// it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
|
|
15
|
+
export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
|
|
16
|
+
/** `get-deck --side` copies of the saved source, one folder per saved version. */
|
|
17
|
+
export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
|
|
18
|
+
export const SAVED_SOURCE_KEEP = 2;
|
|
19
|
+
const VIAS = ['get-deck', 'save-deck', 'adopt', 'force'];
|
|
20
|
+
/** The folder's marker, or null when missing, malformed, or recorded for another deck. */
|
|
21
|
+
export function readSyncMarker(dir, deckId) {
|
|
22
|
+
let value;
|
|
23
|
+
try {
|
|
24
|
+
value = JSON.parse(fs.readFileSync(path.join(dir, WEB_SOURCE_SYNC_FILE), 'utf-8'));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
if (!value ||
|
|
30
|
+
typeof value.deckId !== 'string' ||
|
|
31
|
+
typeof value.s3Key !== 'string' ||
|
|
32
|
+
!value.s3Key ||
|
|
33
|
+
typeof value.updatedAt !== 'string' ||
|
|
34
|
+
typeof value.syncedAt !== 'string' ||
|
|
35
|
+
!VIAS.includes(value.via)) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (deckId !== undefined && value.deckId !== deckId)
|
|
39
|
+
return null;
|
|
40
|
+
return {
|
|
41
|
+
deckId: value.deckId,
|
|
42
|
+
s3Key: value.s3Key,
|
|
43
|
+
updatedAt: value.updatedAt,
|
|
44
|
+
syncedAt: value.syncedAt,
|
|
45
|
+
via: value.via,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function writeSyncMarker(dir, deckId, source, via, now = new Date()) {
|
|
49
|
+
const marker = {
|
|
50
|
+
deckId,
|
|
51
|
+
s3Key: source.s3Key,
|
|
52
|
+
updatedAt: source.updatedAt,
|
|
53
|
+
syncedAt: now.toISOString(),
|
|
54
|
+
via,
|
|
55
|
+
};
|
|
56
|
+
const file = path.join(dir, WEB_SOURCE_SYNC_FILE);
|
|
57
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
58
|
+
atomicWriteFileSync(file, `${JSON.stringify(marker, null, 2)}\n`);
|
|
59
|
+
// The folder now matches a saved version, so a pending "saved copy is newer" notice is moot.
|
|
60
|
+
clearSourceNewerNotice(dir);
|
|
61
|
+
return marker;
|
|
62
|
+
}
|
|
63
|
+
/** Removes a `source-status --notify` notice the serve has not consumed yet. */
|
|
64
|
+
export function clearSourceNewerNotice(dir) {
|
|
65
|
+
fs.rmSync(path.join(dir, WEB_SOURCE_NEWER_MARKER_FILE), { force: true });
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
|
|
69
|
+
* server can still show the previous row: a different key alone is not proof of a newer save.
|
|
70
|
+
* Saved-newer only when the keys differ AND the server's save time is strictly newer than the
|
|
71
|
+
* marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
|
|
72
|
+
*/
|
|
73
|
+
export function compareSync(marker, server) {
|
|
74
|
+
if (marker.s3Key === server.s3Key)
|
|
75
|
+
return 'in-sync';
|
|
76
|
+
const serverMs = Date.parse(server.updatedAt);
|
|
77
|
+
const markerMs = Date.parse(marker.updatedAt);
|
|
78
|
+
if (Number.isFinite(serverMs) && Number.isFinite(markerMs) && serverMs > markerMs) {
|
|
79
|
+
return 'saved-newer';
|
|
80
|
+
}
|
|
81
|
+
return 'lag';
|
|
82
|
+
}
|
|
83
|
+
/** What save-deck does, given the folder's marker and the server's current saved source. */
|
|
84
|
+
export function decideSavePrecondition(marker, server, force) {
|
|
85
|
+
if (force) {
|
|
86
|
+
// A third writer between this observation and the save still trips the server -- for a
|
|
87
|
+
// marked folder. An unmarked one never sends the precondition (below), forced or not.
|
|
88
|
+
return {
|
|
89
|
+
kind: 'proceed',
|
|
90
|
+
expectedS3Key: marker ? (server?.s3Key ?? null) : undefined,
|
|
91
|
+
adopt: false,
|
|
92
|
+
via: 'force',
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (!marker) {
|
|
96
|
+
// A folder with no marker never sends the precondition: it has nothing to compare, and a
|
|
97
|
+
// server refusal would only arrive after the deck went live. It is adopted (a row exists)
|
|
98
|
+
// or saved as the first source, and guarded from the marker the save writes.
|
|
99
|
+
return { kind: 'proceed', expectedS3Key: undefined, adopt: server !== null, via: 'save-deck' };
|
|
100
|
+
}
|
|
101
|
+
// No row is lag too (a first save the replica hasn't seen yet); the server decides.
|
|
102
|
+
if (server && compareSync(marker, server) === 'saved-newer') {
|
|
103
|
+
return {
|
|
104
|
+
kind: 'refuse',
|
|
105
|
+
savedAt: server.updatedAt,
|
|
106
|
+
syncedAt: marker.updatedAt,
|
|
107
|
+
savedS3Key: server.s3Key,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return { kind: 'proceed', expectedS3Key: marker.s3Key, adopt: false, via: 'save-deck' };
|
|
111
|
+
}
|
|
112
|
+
export async function fetchServerSourceVersion(deckId) {
|
|
113
|
+
const source = await api.webDeckSource(deckId);
|
|
114
|
+
return source ? { s3Key: source.s3Key, updatedAt: source.updatedAt } : null;
|
|
115
|
+
}
|
|
116
|
+
/** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
|
|
117
|
+
export function humanTime(iso) {
|
|
118
|
+
const ms = Date.parse(iso);
|
|
119
|
+
if (!Number.isFinite(ms))
|
|
120
|
+
return iso;
|
|
121
|
+
return `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
122
|
+
}
|
|
123
|
+
// --- save-deck refusal --------------------------------------------------------
|
|
124
|
+
/** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
|
|
125
|
+
export const EXIT_SAVED_DECK_NEWER = 5;
|
|
126
|
+
export const SAVE_REFUSED_PREFIX = 'CASTLE_SAVE_REFUSED ';
|
|
127
|
+
export const SAVED_DECK_NEWER_CODE = 'SAVED_DECK_NEWER';
|
|
128
|
+
/** Ghost's code when its own check (primary, under lock) refuses the source commit. */
|
|
129
|
+
export const WEB_DECK_SOURCE_STALE_CODE = 'WEB_DECK_SOURCE_STALE';
|
|
130
|
+
/** The single machine-readable stdout line castle-www parses from a refused save. */
|
|
131
|
+
export function saveRefusedLine(refusal) {
|
|
132
|
+
return `${SAVE_REFUSED_PREFIX}${JSON.stringify({
|
|
133
|
+
event: 'castle_web_save_refused',
|
|
134
|
+
code: SAVED_DECK_NEWER_CODE,
|
|
135
|
+
savedAt: refusal.savedAt,
|
|
136
|
+
syncedAt: refusal.syncedAt,
|
|
137
|
+
savedS3Key: refusal.savedS3Key,
|
|
138
|
+
})}`;
|
|
139
|
+
}
|
|
140
|
+
export function saveRefusedMessage(dir, refusal) {
|
|
141
|
+
const saved = refusal.savedAt ? `saved ${humanTime(refusal.savedAt)}` : 'saved from elsewhere';
|
|
142
|
+
const synced = refusal.syncedAt
|
|
143
|
+
? `this folder last synced ${humanTime(refusal.syncedAt)}`
|
|
144
|
+
: 'this folder never synced with it';
|
|
145
|
+
return [
|
|
146
|
+
`Not saved: the saved copy of this deck is newer than this folder (${saved}; ${synced}).`,
|
|
147
|
+
'Saving now would overwrite changes made elsewhere. Either:',
|
|
148
|
+
` castle-web get-deck ${dir} --side fetch the saved copy beside this one (.castle/agent/saved-source/) to compare`,
|
|
149
|
+
` castle-web save-deck ${dir} --force overwrite the saved copy with this folder`,
|
|
150
|
+
].join('\n');
|
|
151
|
+
}
|
|
152
|
+
export function sourceNewerNotice(dir, savedAt, syncedAt) {
|
|
153
|
+
const notice = `The saved copy of this deck is newer than this workspace (saved ${humanTime(savedAt)}; ` +
|
|
154
|
+
`this workspace last synced ${humanTime(syncedAt)}). Ask before saving over it.`;
|
|
155
|
+
const instruction = [
|
|
156
|
+
`[Castle] The saved copy of this deck was saved at ${savedAt}, after this workspace last synced with it (${syncedAt}): someone saved this deck from somewhere else since, and this workspace does not have those changes.`,
|
|
157
|
+
`Do not run \`castle-web save-deck\` (and never \`save-deck --force\`) over the saved copy without the user's explicit OK: it would overwrite those changes.`,
|
|
158
|
+
`To compare, \`castle-web get-deck ${dir} --side\` fetches the saved copy into .castle/agent/saved-source/<stamp>/ without touching this workspace; diff it against the workspace and tell the user what differs.`,
|
|
159
|
+
'Tell the user about this in one or two sentences and ask how they want to proceed.',
|
|
160
|
+
].join('\n');
|
|
161
|
+
return { notice, instruction };
|
|
162
|
+
}
|
|
163
|
+
export async function sourceStatus(dir, opts = {}) {
|
|
164
|
+
const result = await computeSourceStatus(dir, opts);
|
|
165
|
+
// Whatever a notice said no longer holds unless the saved copy is still newer.
|
|
166
|
+
if (result.status !== 'saved-newer')
|
|
167
|
+
clearSourceNewerNotice(path.resolve(dir));
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
async function computeSourceStatus(dir, opts) {
|
|
171
|
+
const projectDir = path.resolve(dir);
|
|
172
|
+
// An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
|
|
173
|
+
if (!fs.statSync(projectDir).isDirectory())
|
|
174
|
+
throw new Error(`Not a directory: ${projectDir}`);
|
|
175
|
+
fs.readdirSync(projectDir);
|
|
176
|
+
const deckId = readCastleJson(projectDir)?.deckId;
|
|
177
|
+
if (typeof deckId !== 'string' || !deckId) {
|
|
178
|
+
return { deckId: null, status: 'no-deck', marker: null, server: null };
|
|
179
|
+
}
|
|
180
|
+
const marker = readSyncMarker(projectDir, deckId);
|
|
181
|
+
const server = await (opts.fetchServer ?? fetchServerSourceVersion)(deckId);
|
|
182
|
+
const result = {
|
|
183
|
+
deckId,
|
|
184
|
+
status: 'no-source',
|
|
185
|
+
marker: marker
|
|
186
|
+
? { s3Key: marker.s3Key, updatedAt: marker.updatedAt, syncedAt: marker.syncedAt, via: marker.via }
|
|
187
|
+
: null,
|
|
188
|
+
server,
|
|
189
|
+
};
|
|
190
|
+
if (!server)
|
|
191
|
+
return result;
|
|
192
|
+
if (!marker) {
|
|
193
|
+
result.status = 'no-marker';
|
|
194
|
+
if (opts.adopt) {
|
|
195
|
+
const written = writeSyncMarker(projectDir, deckId, server, 'adopt', opts.now?.());
|
|
196
|
+
result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
|
|
197
|
+
result.adopted = true;
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
result.status = compareSync(marker, server);
|
|
202
|
+
if (result.status === 'saved-newer' && opts.notify) {
|
|
203
|
+
const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
|
|
204
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
205
|
+
atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
|
|
206
|
+
result.notified = true;
|
|
207
|
+
}
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
export function describeSourceStatus(result) {
|
|
211
|
+
switch (result.status) {
|
|
212
|
+
case 'no-deck':
|
|
213
|
+
return 'Not a saved deck (castle.json has no deckId).';
|
|
214
|
+
case 'no-source':
|
|
215
|
+
return `Deck ${result.deckId} has no saved source yet.`;
|
|
216
|
+
case 'no-marker':
|
|
217
|
+
return result.adopted
|
|
218
|
+
? `Adopted this folder as deck ${result.deckId}'s saved copy (saved ${humanTime(result.server.updatedAt)}).`
|
|
219
|
+
: `This folder has no sync record for deck ${result.deckId}; the saved copy is from ${humanTime(result.server.updatedAt)}.`;
|
|
220
|
+
case 'in-sync':
|
|
221
|
+
return `In sync with the saved copy (saved ${humanTime(result.server.updatedAt)}).`;
|
|
222
|
+
case 'lag':
|
|
223
|
+
return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
|
|
224
|
+
case 'saved-newer':
|
|
225
|
+
return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
|
|
226
|
+
`this folder last synced ${humanTime(result.marker.updatedAt)}).` +
|
|
227
|
+
(result.notified ? ' The agent has been told.' : ''));
|
|
228
|
+
}
|
|
229
|
+
}
|
package/kits/base/castle.json
CHANGED
|
@@ -53,6 +53,8 @@ export interface PlatformHandle {
|
|
|
53
53
|
worldCharacterSend?(grantId: string): Promise<string>;
|
|
54
54
|
worldCharacterCommand?(grantId: string): Promise<string>;
|
|
55
55
|
worldCharacterRead?(grantId: string): Promise<string>;
|
|
56
|
+
worldCharacterRuntimeCreate?(argsJson: string): Promise<string>;
|
|
57
|
+
worldCharacterRuntimeList?(): Promise<string>;
|
|
56
58
|
worldCharacterReject?(grantId: string, code?: string): void;
|
|
57
59
|
readonly config: PlatformSessionConfig;
|
|
58
60
|
}
|
|
@@ -55,6 +55,8 @@ export interface MultiplayerServerWorld {
|
|
|
55
55
|
readonly characters: MultiplayerServerWorldCharacters;
|
|
56
56
|
}
|
|
57
57
|
export interface MultiplayerServerWorldCharacters {
|
|
58
|
+
create(input: MultiplayerWorldRuntimeCharacterCreateInput): Promise<MultiplayerWorldRuntimeCharacterCreateReceipt>;
|
|
59
|
+
list(): Promise<MultiplayerWorldCharacterList>;
|
|
58
60
|
publicInspect<T = unknown>(): Promise<T>;
|
|
59
61
|
publicRelay(input: {
|
|
60
62
|
operationId: string;
|
|
@@ -63,6 +65,38 @@ export interface MultiplayerServerWorldCharacters {
|
|
|
63
65
|
recipientCharacterIds: string[];
|
|
64
66
|
}): Promise<unknown>;
|
|
65
67
|
}
|
|
68
|
+
export interface MultiplayerWorldRuntimeCharacterKnowledge {
|
|
69
|
+
kind: "belief";
|
|
70
|
+
text: string;
|
|
71
|
+
}
|
|
72
|
+
export interface MultiplayerWorldRuntimeCharacterDefinition {
|
|
73
|
+
name: string;
|
|
74
|
+
instructions: string;
|
|
75
|
+
background?: string;
|
|
76
|
+
initialKnowledge?: readonly MultiplayerWorldRuntimeCharacterKnowledge[];
|
|
77
|
+
}
|
|
78
|
+
export interface MultiplayerWorldRuntimeCharacterCreateInput {
|
|
79
|
+
operationId: string;
|
|
80
|
+
definition: MultiplayerWorldRuntimeCharacterDefinition;
|
|
81
|
+
capabilities: {
|
|
82
|
+
actionIds: readonly string[];
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export interface MultiplayerWorldCharacterSummary {
|
|
86
|
+
id: string;
|
|
87
|
+
name: string;
|
|
88
|
+
source: "published" | "runtime";
|
|
89
|
+
}
|
|
90
|
+
export interface MultiplayerWorldRuntimeCharacterCreateReceipt {
|
|
91
|
+
operationId: string;
|
|
92
|
+
character: MultiplayerWorldCharacterSummary & {
|
|
93
|
+
source: "runtime";
|
|
94
|
+
};
|
|
95
|
+
replayed: boolean;
|
|
96
|
+
}
|
|
97
|
+
export interface MultiplayerWorldCharacterList {
|
|
98
|
+
characters: readonly MultiplayerWorldCharacterSummary[];
|
|
99
|
+
}
|
|
66
100
|
export interface MultiplayerWorldCharacterCommandRequest {
|
|
67
101
|
readonly requestId: string;
|
|
68
102
|
readonly operationId: string;
|
|
@@ -290,16 +290,28 @@ function createServerWorld(platformHandle) {
|
|
|
290
290
|
}
|
|
291
291
|
function createServerWorldCharacters(platformHandle) {
|
|
292
292
|
return Object.freeze({
|
|
293
|
-
async
|
|
294
|
-
if (typeof platformHandle.
|
|
295
|
-
throw new TypeError("The
|
|
293
|
+
async create(input) {
|
|
294
|
+
if (typeof platformHandle.worldCharacterRuntimeCreate !== "function") {
|
|
295
|
+
throw new TypeError("The runtime character broker is unavailable.");
|
|
296
|
+
}
|
|
297
|
+
const operationId = assertWorldOperationId(input?.operationId);
|
|
298
|
+
const definition = assertRuntimeCharacterDefinition(input?.definition);
|
|
299
|
+
const capabilities = assertRuntimeCharacterCapabilities(input?.capabilities);
|
|
300
|
+
const result = parseSharedCharacterJson(await platformHandle.worldCharacterRuntimeCreate(JSON.stringify({ operationId, definition, capabilities })));
|
|
301
|
+
return parseRuntimeCharacterCreateReceipt(result, operationId);
|
|
302
|
+
},
|
|
303
|
+
async list() {
|
|
304
|
+
if (typeof platformHandle.worldCharacterRuntimeList !== "function") {
|
|
305
|
+
throw new TypeError("The runtime character broker is unavailable.");
|
|
296
306
|
}
|
|
307
|
+
return parseRuntimeCharacterList(parseSharedCharacterJson(await platformHandle.worldCharacterRuntimeList()));
|
|
308
|
+
},
|
|
309
|
+
async publicInspect() {
|
|
310
|
+
requireSharedCharacterBroker(platformHandle);
|
|
297
311
|
return parseSharedCharacterJson(await platformHandle.storage("worldCharacterPublicInspect", "{}"));
|
|
298
312
|
},
|
|
299
313
|
async publicRelay(input) {
|
|
300
|
-
|
|
301
|
-
throw new TypeError("The shared character broker is unavailable.");
|
|
302
|
-
}
|
|
314
|
+
requireSharedCharacterBroker(platformHandle);
|
|
303
315
|
const operationId = assertWorldOperationId(input?.operationId);
|
|
304
316
|
const sourceId = assertWorldCharacterId(input?.sourceId, "sourceId", 128);
|
|
305
317
|
const transmittingCharacterId = assertWorldCharacterId(input?.transmittingCharacterId, "transmittingCharacterId");
|
|
@@ -320,6 +332,142 @@ function createServerWorldCharacters(platformHandle) {
|
|
|
320
332
|
},
|
|
321
333
|
});
|
|
322
334
|
}
|
|
335
|
+
const RUNTIME_CHARACTER_MAX_COUNT = 16;
|
|
336
|
+
const RUNTIME_CHARACTER_MAX_KNOWLEDGE = 8;
|
|
337
|
+
const RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS = 8_000;
|
|
338
|
+
const RUNTIME_CHARACTER_ID = /^runtime_[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
339
|
+
const SAFE_RUNTIME_ACTION_ID = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
340
|
+
const FORBIDDEN_RUNTIME_ACTION_IDS = new Set(["__proto__", "prototype", "constructor"]);
|
|
341
|
+
function requireSharedCharacterBroker(platformHandle) {
|
|
342
|
+
if (typeof platformHandle.storage !== "function") {
|
|
343
|
+
throw new TypeError("The shared character broker is unavailable.");
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function assertRuntimeCharacterDefinition(value) {
|
|
347
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
348
|
+
throw new TypeError("session.world.characters.create: definition must be an object.");
|
|
349
|
+
}
|
|
350
|
+
const definition = value;
|
|
351
|
+
if (Object.keys(definition).some((key) => !["name", "instructions", "background", "initialKnowledge"].includes(key))) {
|
|
352
|
+
throw new TypeError("session.world.characters.create: definition contains an unsupported field.");
|
|
353
|
+
}
|
|
354
|
+
const name = assertRuntimeCharacterText(definition.name, "definition.name", 100, 400);
|
|
355
|
+
const instructions = assertRuntimeCharacterText(definition.instructions, "definition.instructions", 8_000, 32_000);
|
|
356
|
+
if (JSON.stringify(instructions).length - 2 > 10_000) {
|
|
357
|
+
throw new TypeError("session.world.characters.create: definition.instructions is too large when serialized.");
|
|
358
|
+
}
|
|
359
|
+
const background = definition.background === undefined
|
|
360
|
+
? undefined
|
|
361
|
+
: assertRuntimeCharacterText(definition.background, "definition.background", 2_000, 8_000);
|
|
362
|
+
let initialKnowledge;
|
|
363
|
+
if (definition.initialKnowledge !== undefined) {
|
|
364
|
+
if (!Array.isArray(definition.initialKnowledge) ||
|
|
365
|
+
definition.initialKnowledge.length > RUNTIME_CHARACTER_MAX_KNOWLEDGE) {
|
|
366
|
+
throw new TypeError(`session.world.characters.create: definition.initialKnowledge may contain at most ${RUNTIME_CHARACTER_MAX_KNOWLEDGE} beliefs.`);
|
|
367
|
+
}
|
|
368
|
+
initialKnowledge = definition.initialKnowledge.map((entry, index) => {
|
|
369
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
370
|
+
throw new TypeError(`session.world.characters.create: definition.initialKnowledge[${index}] must be a belief.`);
|
|
371
|
+
}
|
|
372
|
+
const knowledge = entry;
|
|
373
|
+
if (Object.keys(knowledge).some((key) => key !== "kind" && key !== "text") ||
|
|
374
|
+
knowledge.kind !== "belief") {
|
|
375
|
+
throw new TypeError(`session.world.characters.create: definition.initialKnowledge[${index}] must contain only kind "belief" and text.`);
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
kind: "belief",
|
|
379
|
+
text: assertRuntimeCharacterText(knowledge.text, `definition.initialKnowledge[${index}].text`, 500, 2_000),
|
|
380
|
+
};
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
const promptCharacters = instructions.length + (background?.length ?? 0) +
|
|
384
|
+
(initialKnowledge?.reduce((sum, item) => sum + item.text.length, 0) ?? 0);
|
|
385
|
+
if (promptCharacters > RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS) {
|
|
386
|
+
throw new TypeError(`session.world.characters.create: definition prompt fields may total at most ${RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS} characters.`);
|
|
387
|
+
}
|
|
388
|
+
return Object.freeze({
|
|
389
|
+
name,
|
|
390
|
+
instructions,
|
|
391
|
+
...(background === undefined ? {} : { background }),
|
|
392
|
+
...(initialKnowledge === undefined
|
|
393
|
+
? {}
|
|
394
|
+
: { initialKnowledge: Object.freeze(initialKnowledge.map((item) => Object.freeze(item))) }),
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
function assertRuntimeCharacterCapabilities(value) {
|
|
398
|
+
if (!value ||
|
|
399
|
+
typeof value !== "object" ||
|
|
400
|
+
Array.isArray(value) ||
|
|
401
|
+
Object.keys(value).some((key) => key !== "actionIds")) {
|
|
402
|
+
throw new TypeError("session.world.characters.create: capabilities must contain only actionIds.");
|
|
403
|
+
}
|
|
404
|
+
const actionIds = value.actionIds;
|
|
405
|
+
if (!Array.isArray(actionIds) || actionIds.length > RUNTIME_CHARACTER_MAX_COUNT) {
|
|
406
|
+
throw new TypeError(`session.world.characters.create: capabilities.actionIds may contain at most ${RUNTIME_CHARACTER_MAX_COUNT} ids.`);
|
|
407
|
+
}
|
|
408
|
+
const normalized = actionIds.map((id, index) => {
|
|
409
|
+
if (typeof id !== "string" ||
|
|
410
|
+
!SAFE_RUNTIME_ACTION_ID.test(id) ||
|
|
411
|
+
FORBIDDEN_RUNTIME_ACTION_IDS.has(id)) {
|
|
412
|
+
throw new TypeError(`session.world.characters.create: capabilities.actionIds[${index}] is invalid.`);
|
|
413
|
+
}
|
|
414
|
+
return id;
|
|
415
|
+
});
|
|
416
|
+
if (new Set(normalized).size !== normalized.length) {
|
|
417
|
+
throw new TypeError("session.world.characters.create: capabilities.actionIds may not contain duplicates.");
|
|
418
|
+
}
|
|
419
|
+
return Object.freeze({ actionIds: Object.freeze([...normalized].sort()) });
|
|
420
|
+
}
|
|
421
|
+
function assertRuntimeCharacterText(value, field, maxCharacters, maxBytes) {
|
|
422
|
+
if (typeof value !== "string" ||
|
|
423
|
+
value.length === 0 ||
|
|
424
|
+
value.length > maxCharacters ||
|
|
425
|
+
value.includes("\0") ||
|
|
426
|
+
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value) ||
|
|
427
|
+
new TextEncoder().encode(value).byteLength > maxBytes) {
|
|
428
|
+
throw new TypeError(`session.world.characters.create: ${field} must be valid non-empty text of at most ${maxCharacters} characters.`);
|
|
429
|
+
}
|
|
430
|
+
return value;
|
|
431
|
+
}
|
|
432
|
+
function parseRuntimeCharacterCreateReceipt(value, operationId) {
|
|
433
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
434
|
+
throw new TypeError("The platform returned an invalid runtime character receipt.");
|
|
435
|
+
}
|
|
436
|
+
const receipt = value;
|
|
437
|
+
const character = parseRuntimeCharacterSummary(receipt.character, true);
|
|
438
|
+
if (receipt.operationId !== operationId || typeof receipt.replayed !== "boolean") {
|
|
439
|
+
throw new TypeError("The platform returned an invalid runtime character receipt.");
|
|
440
|
+
}
|
|
441
|
+
return Object.freeze({ operationId, character, replayed: receipt.replayed });
|
|
442
|
+
}
|
|
443
|
+
function parseRuntimeCharacterList(value) {
|
|
444
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
445
|
+
throw new TypeError("The platform returned an invalid runtime character list.");
|
|
446
|
+
}
|
|
447
|
+
const characters = value.characters;
|
|
448
|
+
if (!Array.isArray(characters) || characters.length > RUNTIME_CHARACTER_MAX_COUNT) {
|
|
449
|
+
throw new TypeError("The platform returned an invalid runtime character list.");
|
|
450
|
+
}
|
|
451
|
+
const normalized = characters.map((character) => parseRuntimeCharacterSummary(character));
|
|
452
|
+
if (new Set(normalized.map((character) => character.id)).size !== normalized.length) {
|
|
453
|
+
throw new TypeError("The platform returned an invalid runtime character list.");
|
|
454
|
+
}
|
|
455
|
+
return Object.freeze({ characters: Object.freeze(normalized) });
|
|
456
|
+
}
|
|
457
|
+
function parseRuntimeCharacterSummary(value, requireRuntime = false) {
|
|
458
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
459
|
+
throw new TypeError("The platform returned an invalid runtime character summary.");
|
|
460
|
+
}
|
|
461
|
+
const summary = value;
|
|
462
|
+
const id = assertWorldCharacterId(summary.id, "character.id");
|
|
463
|
+
const name = assertRuntimeCharacterText(summary.name, "character.name", 100, 400);
|
|
464
|
+
if ((summary.source !== "runtime" && summary.source !== "published") ||
|
|
465
|
+
(requireRuntime && summary.source !== "runtime") ||
|
|
466
|
+
(summary.source === "runtime" && !RUNTIME_CHARACTER_ID.test(id))) {
|
|
467
|
+
throw new TypeError("The platform returned an invalid runtime character summary.");
|
|
468
|
+
}
|
|
469
|
+
return Object.freeze({ id, name, source: summary.source });
|
|
470
|
+
}
|
|
323
471
|
function parseWorldSnapshot(value, operation) {
|
|
324
472
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
325
473
|
throw worldError("The platform returned an invalid world checkpoint.", "read");
|