castle-web-cli 0.4.204 → 0.4.205
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-failures.d.ts +3 -1
- package/dist/agent-failures.js +19 -0
- package/dist/agent-prompts.js +2 -1
- package/dist/agent.d.ts +3 -2
- package/dist/agent.js +19 -10
- package/dist/castle-host/host.d.ts +17 -0
- package/dist/castle-host/host.js +551 -4
- package/dist/devSessionStorage.js +65 -4
- package/dist/effortSupport.d.ts +7 -0
- package/dist/effortSupport.js +31 -0
- package/dist/init.js +13 -3
- package/dist/platformDoc.js +6 -1
- package/dist/serve.js +35 -2
- package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
- package/dist/shell/index.html +1 -1
- package/dist/vitePlugins.js +19 -1
- package/kits/base/CLAUDE.md +2 -0
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +131 -0
- package/kits/base/sdk/agent.d.ts +6 -0
- package/kits/base/sdk/agent.js +70 -0
- package/kits/base/sdk/castle.d.ts +4 -0
- package/kits/base/sdk/castle.js +2 -0
- package/kits/base/sdk/commands.d.ts +106 -0
- package/kits/base/sdk/commands.js +21 -0
- package/kits/base/sdk/decks.d.ts +7 -0
- package/kits/base/sdk/decks.js +31 -0
- package/kits/base/sdk/runtime.d.ts +4 -2
- package/kits/base/sdk/runtime.js +51 -40
- package/kits/base/sdk/server/storage.d.ts +44 -0
- package/kits/base/sdk/server/storage.js +54 -0
- package/kits/base/sdk/transport.d.ts +5 -1
- package/kits/base/sdk/transport.js +106 -23
- package/kits/multiplayer-2d/castle.json +4 -4
- package/kits/multiplayer-2d/code/client/poses.js +7 -0
- package/kits/multiplayer-2d/code/server/limits.js +3 -0
- package/kits/multiplayer-2d/code/server/ownership.js +36 -8
- package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
- package/kits/multiplayer-3d/CLAUDE.md +12 -1
- package/kits/multiplayer-3d/castle.json +4 -4
- package/kits/multiplayer-3d/code/client/avatars.js +7 -1
- package/kits/multiplayer-3d/code/client/poses.js +61 -1
- package/kits/multiplayer-3d/code/client/steer.js +383 -0
- package/kits/multiplayer-3d/code/server/limits.js +3 -0
- package/kits/multiplayer-3d/code/server/ownership.js +114 -18
- package/kits/multiplayer-3d/code/server/world.js +12 -4
- package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
- package/kits/physics-3d/CLAUDE.md +65 -7
- package/kits/physics-3d/castle.json +3 -3
- package/kits/physics-3d/docs/pxmodel-format.md +916 -15
- package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
- package/kits/physics-3d/engine3d/artobjects.js +218 -0
- package/kits/physics-3d/engine3d/blob.js +1058 -0
- package/kits/physics-3d/engine3d/branches.js +300 -0
- package/kits/physics-3d/engine3d/cage.js +496 -0
- package/kits/physics-3d/engine3d/cageops.js +516 -0
- package/kits/physics-3d/engine3d/frame.js +669 -0
- package/kits/physics-3d/engine3d/look.js +675 -0
- package/kits/physics-3d/engine3d/materialpresets.js +486 -0
- package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
- package/kits/physics-3d/engine3d/modelrefs.js +120 -0
- package/kits/physics-3d/engine3d/motion.js +560 -0
- package/kits/physics-3d/engine3d/objtext.js +37 -0
- package/kits/physics-3d/engine3d/optimize.js +1083 -0
- package/kits/physics-3d/engine3d/paint.js +674 -0
- package/kits/physics-3d/engine3d/partgeometry.js +467 -0
- package/kits/physics-3d/engine3d/paths.js +324 -0
- package/kits/physics-3d/engine3d/pxmodel.js +429 -26
- package/kits/physics-3d/engine3d/scatter.js +102 -0
- package/kits/physics-3d/engine3d/sculpt.js +1148 -0
- package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
- package/kits/physics-3d/engine3d/sweep.js +480 -0
- package/kits/physics-3d/engine3d/thumbnails.js +6 -4
- package/kits/physics-3d/engine3d/world3d.js +119 -17
- package/kits/physics-3d/eslint.config.js +13 -0
- package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
- package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
- package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
- package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
- package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
- package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
- package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
- package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
- package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
- package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
- package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
- package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
- package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
- package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
- package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
- package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
- package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
- package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
- package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
- package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
- package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
- package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
- package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
- package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
- package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
- package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
- package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
- package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
- package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
- package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
- package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
- package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
- package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
- package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
- package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
- package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
- package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
- package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
- package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
- package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
- package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
- package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
- package/kits/physics-3d/scripts/render/index.html +20 -0
- package/kits/physics-3d/scripts/render/sheet.js +411 -0
- package/kits/physics-3d/scripts/render.mjs +646 -0
- package/kits/real-time/castle.json +2 -2
- package/kits/real-time/code/client/ownership.js +14 -4
- package/kits/real-time/code/client/smooth.js +2 -2
- package/kits/real-time/code/server/session.js +20 -4
- package/package.json +2 -2
package/dist/castle-host/host.js
CHANGED
|
@@ -11,11 +11,17 @@
|
|
|
11
11
|
//
|
|
12
12
|
// Usage from a host:
|
|
13
13
|
// import { executeCommand } from "castle-web-sdk/host";
|
|
14
|
-
// const result = await executeCommand(ctx, command, params,
|
|
14
|
+
// const result = await executeCommand(ctx, command, params, capabilities, {
|
|
15
|
+
// onStream: (event) => post({ castleSdk: 1, requestId, stream: event }),
|
|
16
|
+
// signal, // aborted when the deck sends { castleSdk: 1, requestId, cancel: true }
|
|
17
|
+
// });
|
|
15
18
|
// // reply { castleSdk: 1, requestId, ...result } back to the deck.
|
|
16
19
|
// Runtime command allowlist — kept here (not in commands.ts) so the import
|
|
17
20
|
// above stays type-only. Must stay in sync with CommandParams in commands.ts.
|
|
18
21
|
const COMMAND_NAMES = [
|
|
22
|
+
"agent.chat",
|
|
23
|
+
"decks.mine",
|
|
24
|
+
"decks.saved",
|
|
19
25
|
"deckStorage.load",
|
|
20
26
|
"deckStorage.update",
|
|
21
27
|
"sharedDeckStorage.load",
|
|
@@ -85,7 +91,7 @@ class HostCommandError extends Error {
|
|
|
85
91
|
this.extensions = extensions;
|
|
86
92
|
}
|
|
87
93
|
}
|
|
88
|
-
export async function executeCommand(ctx, command, params, capabilities) {
|
|
94
|
+
export async function executeCommand(ctx, command, params, capabilities, options = {}) {
|
|
89
95
|
if (!isCommandName(command)) {
|
|
90
96
|
return {
|
|
91
97
|
ok: false,
|
|
@@ -97,14 +103,14 @@ export async function executeCommand(ctx, command, params, capabilities) {
|
|
|
97
103
|
};
|
|
98
104
|
}
|
|
99
105
|
try {
|
|
100
|
-
const data = await runCommand(ctx, command, (params ?? {}), capabilities);
|
|
106
|
+
const data = await runCommand(ctx, command, (params ?? {}), capabilities, options);
|
|
101
107
|
return { ok: true, data };
|
|
102
108
|
}
|
|
103
109
|
catch (error) {
|
|
104
110
|
return { ok: false, error: toSerializedError(error, command) };
|
|
105
111
|
}
|
|
106
112
|
}
|
|
107
|
-
function runCommand(ctx, command, params, caps) {
|
|
113
|
+
function runCommand(ctx, command, params, caps, options) {
|
|
108
114
|
if (command === "multiplayer.getSession" && caps.getMultiplayerSession) {
|
|
109
115
|
return caps.getMultiplayerSession(multiplayerSessionRequest(params), ctx);
|
|
110
116
|
}
|
|
@@ -113,6 +119,12 @@ function runCommand(ctx, command, params, caps) {
|
|
|
113
119
|
}
|
|
114
120
|
const gql = caps.graphqlFetch;
|
|
115
121
|
switch (command) {
|
|
122
|
+
case "agent.chat":
|
|
123
|
+
return agentChat(ctx, params, caps, options);
|
|
124
|
+
case "decks.mine":
|
|
125
|
+
return decksMine(params, gql);
|
|
126
|
+
case "decks.saved":
|
|
127
|
+
return decksSaved(ctx, params, gql);
|
|
116
128
|
case "deckStorage.load":
|
|
117
129
|
return deckStorageLoad(ctx, gql);
|
|
118
130
|
case "deckStorage.update":
|
|
@@ -1014,6 +1026,541 @@ function requirePublishedCharacter(admission, characterId, command) {
|
|
|
1014
1026
|
throw new HostCommandError("CAULDRON_CHARACTER_NOT_FOUND", `This deck has no published character ${JSON.stringify(characterId)}.`, command);
|
|
1015
1027
|
}
|
|
1016
1028
|
// ---------------------------------------------------------------------------
|
|
1029
|
+
// The player's decks.
|
|
1030
|
+
//
|
|
1031
|
+
// Lists to pick a portal's destination from: the player's own published
|
|
1032
|
+
// decks, and the decks they saved (bookmarks, then their playlists). Both leave
|
|
1033
|
+
// out decks a portal cannot reach -- a private deck, or one whose creator
|
|
1034
|
+
// turned portals off. Covers come as data: urls, as for portal.info.
|
|
1035
|
+
const DECKS_DEFAULT_LIMIT = 20;
|
|
1036
|
+
const DECKS_MAX_LIMIT = 50;
|
|
1037
|
+
const DECKS_PLAYLIST_CAP = 10;
|
|
1038
|
+
async function decksMine(params, gql) {
|
|
1039
|
+
await requireDecksAdmin(gql, "decks.mine");
|
|
1040
|
+
const limit = decksLimit(params.limit, "decks.mine");
|
|
1041
|
+
const data = await graphql(gql, DECKS_MINE_QUERY, {}, "decks.mine");
|
|
1042
|
+
return decksResult(data.me?.decks ?? [], limit);
|
|
1043
|
+
}
|
|
1044
|
+
async function decksSaved(ctx, params, gql) {
|
|
1045
|
+
const command = "decks.saved";
|
|
1046
|
+
await requireDecksAdmin(gql, command);
|
|
1047
|
+
const limit = decksLimit(params.limit, command);
|
|
1048
|
+
const bookmarks = await feedDecks(gql, "bookmarks", command);
|
|
1049
|
+
const playlistIds = ctx.userId ? await savedPlaylistIds(gql, ctx.userId) : [];
|
|
1050
|
+
// One broken playlist costs only its own decks.
|
|
1051
|
+
const playlists = await Promise.all(playlistIds.map((id) => feedDecks(gql, `playlist:${id}`, command).catch(() => [])));
|
|
1052
|
+
return decksResult([bookmarks, ...playlists].flat(), limit);
|
|
1053
|
+
}
|
|
1054
|
+
// Decks is limited to Castle admins for now, like Agent.chat.
|
|
1055
|
+
async function requireDecksAdmin(gql, command) {
|
|
1056
|
+
if (!(await isCastleAdmin(gql, command))) {
|
|
1057
|
+
throw new HostCommandError("PERMISSION_DENIED", "Decks is limited to Castle admins.", command);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
function decksLimit(value, command) {
|
|
1061
|
+
if (value === undefined || value === null) {
|
|
1062
|
+
return DECKS_DEFAULT_LIMIT;
|
|
1063
|
+
}
|
|
1064
|
+
if (Number.isSafeInteger(value) && value >= 1 && value <= DECKS_MAX_LIMIT) {
|
|
1065
|
+
return value;
|
|
1066
|
+
}
|
|
1067
|
+
throw new HostCommandError("INVALID_ARGUMENT", `Castle command ${command} takes a limit from 1 through ${DECKS_MAX_LIMIT}.`, command);
|
|
1068
|
+
}
|
|
1069
|
+
async function feedDecks(gql, feedId, command) {
|
|
1070
|
+
const data = await graphql(gql, DECKS_FEED_QUERY, { feedId, limit: DECKS_MAX_LIMIT }, command);
|
|
1071
|
+
return data.paginateFeed ?? [];
|
|
1072
|
+
}
|
|
1073
|
+
// The bookmarks playlist (`bookmarks-<userId>`) is one of the user's
|
|
1074
|
+
// playlists, and is already read as the bookmarks feed.
|
|
1075
|
+
async function savedPlaylistIds(gql, userId) {
|
|
1076
|
+
const data = await graphql(gql, DECKS_PLAYLISTS_QUERY, { userId, limit: DECKS_PLAYLIST_CAP * 2 }, "decks.saved");
|
|
1077
|
+
return (data.playlistsForUser?.items ?? [])
|
|
1078
|
+
.map((item) => item?.playlistId)
|
|
1079
|
+
.filter((id) => typeof id === "string" && !id.startsWith("bookmarks-"))
|
|
1080
|
+
.slice(0, DECKS_PLAYLIST_CAP);
|
|
1081
|
+
}
|
|
1082
|
+
// The first `limit` reachable decks, each once, in list order.
|
|
1083
|
+
async function decksResult(rows, limit) {
|
|
1084
|
+
const seen = new Set();
|
|
1085
|
+
const kept = [];
|
|
1086
|
+
for (const row of rows) {
|
|
1087
|
+
if (kept.length >= limit) {
|
|
1088
|
+
break;
|
|
1089
|
+
}
|
|
1090
|
+
const deckId = row?.deckId;
|
|
1091
|
+
if (!deckId || seen.has(deckId) || !portalCanReach(row)) {
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
1094
|
+
seen.add(deckId);
|
|
1095
|
+
kept.push(row);
|
|
1096
|
+
}
|
|
1097
|
+
return { status: "ok", decks: await Promise.all(kept.map(deckSummary)) };
|
|
1098
|
+
}
|
|
1099
|
+
function portalCanReach(row) {
|
|
1100
|
+
return row.visibility !== "private" && row.portalsEnabled !== false;
|
|
1101
|
+
}
|
|
1102
|
+
async function deckSummary(row) {
|
|
1103
|
+
const creator = row.creator?.userId && row.creator.username
|
|
1104
|
+
? { userId: row.creator.userId, username: row.creator.username }
|
|
1105
|
+
: null;
|
|
1106
|
+
return {
|
|
1107
|
+
deckId: row.deckId,
|
|
1108
|
+
title: row.title ?? "",
|
|
1109
|
+
creator,
|
|
1110
|
+
coverUrl: await imageDataUrl(row.initialCard?.backgroundImage?.smallCardUrl),
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
const DECK_SUMMARY_FIELDS = `
|
|
1114
|
+
deckId
|
|
1115
|
+
title
|
|
1116
|
+
visibility
|
|
1117
|
+
portalsEnabled
|
|
1118
|
+
creator { userId username }
|
|
1119
|
+
initialCard { backgroundImage { smallCardUrl } }
|
|
1120
|
+
`;
|
|
1121
|
+
const DECKS_MINE_QUERY = `
|
|
1122
|
+
query CastleDecksMine {
|
|
1123
|
+
me { decks { ${DECK_SUMMARY_FIELDS} } }
|
|
1124
|
+
}
|
|
1125
|
+
`;
|
|
1126
|
+
const DECKS_FEED_QUERY = `
|
|
1127
|
+
query CastleDecksFeed($feedId: ID!, $limit: Int) {
|
|
1128
|
+
paginateFeed(feedId: $feedId, limit: $limit) { ${DECK_SUMMARY_FIELDS} }
|
|
1129
|
+
}
|
|
1130
|
+
`;
|
|
1131
|
+
const DECKS_PLAYLISTS_QUERY = `
|
|
1132
|
+
query CastleDecksPlaylists($userId: ID!, $limit: Int) {
|
|
1133
|
+
playlistsForUser(userId: $userId, limit: $limit) { items { playlistId } }
|
|
1134
|
+
}
|
|
1135
|
+
`;
|
|
1136
|
+
// ---------------------------------------------------------------------------
|
|
1137
|
+
// Agent chat.
|
|
1138
|
+
//
|
|
1139
|
+
// The oracle is Castle's proxy to OpenRouter. It answers with a server-sent
|
|
1140
|
+
// event stream: its own `{ castle }` header, a heartbeat event every 15
|
|
1141
|
+
// seconds, OpenRouter's chunks, and `[DONE]`. The executor reads the stream as
|
|
1142
|
+
// it arrives, passes text, reasoning and finished tool calls on to the deck,
|
|
1143
|
+
// and resolves with the whole message. The oracle does not refuse a non-admin;
|
|
1144
|
+
// it swaps in its own model. The admin check is made here, before the request.
|
|
1145
|
+
const ORACLE_CHAT_URL = "https://oracle-server.castle.xyz/chat/completions";
|
|
1146
|
+
const AGENT_DEFAULT_MODEL = "meta/muse-spark-1.3";
|
|
1147
|
+
// Three missed heartbeats; the oracle sends one every 15 seconds.
|
|
1148
|
+
const ORACLE_SILENCE_MS = 45_000;
|
|
1149
|
+
// Text and reasoning pieces are sent to the deck in batches this far apart. A
|
|
1150
|
+
// model sends a piece every few milliseconds, and each post to a mobile deck
|
|
1151
|
+
// is a call into its WebView.
|
|
1152
|
+
const DELTA_BATCH_MS = 40;
|
|
1153
|
+
// The oracle's own admin test. `me.isAdmin` is moderator status, a wider group.
|
|
1154
|
+
const AGENT_ADMIN_QUERY = `
|
|
1155
|
+
query { me { castleUserGroups { isAdmin } } }
|
|
1156
|
+
`;
|
|
1157
|
+
async function agentChat(ctx, params, caps, options) {
|
|
1158
|
+
const openrouter = agentChatRequest(params);
|
|
1159
|
+
if (!caps.oracleStream) {
|
|
1160
|
+
return { status: "unavailable", reason: "This host has no route to the Castle oracle." };
|
|
1161
|
+
}
|
|
1162
|
+
try {
|
|
1163
|
+
if (!(await isCastleAdmin(caps.graphqlFetch, "agent.chat"))) {
|
|
1164
|
+
return { status: "refused", reason: "Agent.chat is limited to Castle admins." };
|
|
1165
|
+
}
|
|
1166
|
+
const body = { openrouter, castle: { mode: "deck-agent", deckId: ctx.deckId } };
|
|
1167
|
+
return await streamAgentReply(caps.oracleStream, JSON.stringify(body), options);
|
|
1168
|
+
}
|
|
1169
|
+
catch (error) {
|
|
1170
|
+
return { status: "error", reason: error instanceof Error ? error.message : String(error) };
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
// The OpenRouter body. The oracle raises `max_tokens` to its own ceiling for
|
|
1174
|
+
// admins, whatever is sent.
|
|
1175
|
+
function agentChatRequest(params) {
|
|
1176
|
+
const command = "agent.chat";
|
|
1177
|
+
if (!Array.isArray(params.messages) || params.messages.length === 0) {
|
|
1178
|
+
throw new HostCommandError("INVALID_ARGUMENT", "agent.chat requires messages.", command);
|
|
1179
|
+
}
|
|
1180
|
+
if (params.tools !== undefined && params.tools !== null && !Array.isArray(params.tools)) {
|
|
1181
|
+
throw new HostCommandError("INVALID_ARGUMENT", "agent.chat tools must be an array.", command);
|
|
1182
|
+
}
|
|
1183
|
+
const request = {
|
|
1184
|
+
model: asOptionalString(params.model) ?? AGENT_DEFAULT_MODEL,
|
|
1185
|
+
messages: params.messages,
|
|
1186
|
+
stream: true,
|
|
1187
|
+
usage: { include: true },
|
|
1188
|
+
};
|
|
1189
|
+
if (Array.isArray(params.tools) && params.tools.length > 0) {
|
|
1190
|
+
request.tools = params.tools;
|
|
1191
|
+
}
|
|
1192
|
+
const toolChoice = params.toolChoice;
|
|
1193
|
+
if (typeof toolChoice === "string" || (typeof toolChoice === "object" && toolChoice !== null)) {
|
|
1194
|
+
request.tool_choice = toolChoice;
|
|
1195
|
+
}
|
|
1196
|
+
const maxTokens = asOptionalNumber(params.maxTokens);
|
|
1197
|
+
if (maxTokens !== null) {
|
|
1198
|
+
request.max_tokens = Math.floor(maxTokens);
|
|
1199
|
+
}
|
|
1200
|
+
const effort = params.reasoning?.effort;
|
|
1201
|
+
if (effort === "minimal" || effort === "low" || effort === "medium" || effort === "high") {
|
|
1202
|
+
request.reasoning = { effort };
|
|
1203
|
+
}
|
|
1204
|
+
return request;
|
|
1205
|
+
}
|
|
1206
|
+
async function isCastleAdmin(gql, command) {
|
|
1207
|
+
const data = await graphql(gql, AGENT_ADMIN_QUERY, {}, command);
|
|
1208
|
+
return data.me?.castleUserGroups?.isAdmin === true;
|
|
1209
|
+
}
|
|
1210
|
+
// Resolves once, on whichever comes first: `[DONE]`, the end of the body, a
|
|
1211
|
+
// failure, the deck's cancel, or ORACLE_SILENCE_MS without an event.
|
|
1212
|
+
function streamAgentReply(oracleStream, body, options) {
|
|
1213
|
+
return new Promise((resolve) => {
|
|
1214
|
+
const reply = {
|
|
1215
|
+
content: "",
|
|
1216
|
+
reasoning: "",
|
|
1217
|
+
toolCalls: [],
|
|
1218
|
+
toolCallsSent: 0,
|
|
1219
|
+
finishReason: null,
|
|
1220
|
+
};
|
|
1221
|
+
const outbox = createOutbox(options.onStream);
|
|
1222
|
+
const signal = options.signal;
|
|
1223
|
+
let settled = false;
|
|
1224
|
+
let abortRequest = null;
|
|
1225
|
+
let silenceTimer = null;
|
|
1226
|
+
const finish = (result) => {
|
|
1227
|
+
if (settled) {
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
settled = true;
|
|
1231
|
+
if (silenceTimer) {
|
|
1232
|
+
clearTimeout(silenceTimer);
|
|
1233
|
+
}
|
|
1234
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1235
|
+
abortRequest?.();
|
|
1236
|
+
flushOutbox(outbox);
|
|
1237
|
+
resolve(result);
|
|
1238
|
+
};
|
|
1239
|
+
const onAbort = () => finish({ status: "cancelled", reason: "Agent.chat was cancelled." });
|
|
1240
|
+
const restartSilence = () => {
|
|
1241
|
+
if (silenceTimer) {
|
|
1242
|
+
clearTimeout(silenceTimer);
|
|
1243
|
+
}
|
|
1244
|
+
silenceTimer = setTimeout(() => {
|
|
1245
|
+
finish({ status: "error", reason: "The model stream went silent." });
|
|
1246
|
+
}, ORACLE_SILENCE_MS);
|
|
1247
|
+
};
|
|
1248
|
+
if (signal?.aborted) {
|
|
1249
|
+
onAbort();
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
signal?.addEventListener("abort", onAbort);
|
|
1253
|
+
restartSilence();
|
|
1254
|
+
const abort = oracleStream(ORACLE_CHAT_URL, body, {
|
|
1255
|
+
event(name, data) {
|
|
1256
|
+
if (settled) {
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
restartSilence();
|
|
1260
|
+
if (data === "[DONE]") {
|
|
1261
|
+
finish(agentChatResult(reply, outbox));
|
|
1262
|
+
}
|
|
1263
|
+
else if (name === "message") {
|
|
1264
|
+
applyOracleEvent(reply, outbox, parseOracleEvent(data));
|
|
1265
|
+
// The oracle ends the body after an error chunk, with no `[DONE]`. A
|
|
1266
|
+
// host whose stream cannot report the end of the body would wait
|
|
1267
|
+
// out ORACLE_SILENCE_MS.
|
|
1268
|
+
if (reply.error) {
|
|
1269
|
+
finish(agentChatResult(reply, outbox));
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
else {
|
|
1273
|
+
sendKeepalive(outbox);
|
|
1274
|
+
}
|
|
1275
|
+
},
|
|
1276
|
+
end() {
|
|
1277
|
+
finish(agentChatResult(reply, outbox));
|
|
1278
|
+
},
|
|
1279
|
+
fail(status, text) {
|
|
1280
|
+
finish({ status: "error", reason: oracleErrorReason(status, text) });
|
|
1281
|
+
},
|
|
1282
|
+
});
|
|
1283
|
+
// The sink can finish before oracleStream returns, on a request that fails
|
|
1284
|
+
// at once.
|
|
1285
|
+
if (settled) {
|
|
1286
|
+
abort();
|
|
1287
|
+
}
|
|
1288
|
+
else {
|
|
1289
|
+
abortRequest = abort;
|
|
1290
|
+
}
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
function parseOracleEvent(data) {
|
|
1294
|
+
try {
|
|
1295
|
+
const event = JSON.parse(data);
|
|
1296
|
+
return typeof event === "object" && event !== null ? event : null;
|
|
1297
|
+
}
|
|
1298
|
+
catch {
|
|
1299
|
+
return null;
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
// The oracle's own failures are JSON with an `error` string: a bad token, no
|
|
1303
|
+
// credits left, or the model provider failing before the stream began.
|
|
1304
|
+
function oracleErrorReason(status, text) {
|
|
1305
|
+
if (status === 0) {
|
|
1306
|
+
return `Could not reach the Castle oracle: ${text}`;
|
|
1307
|
+
}
|
|
1308
|
+
try {
|
|
1309
|
+
const body = JSON.parse(text);
|
|
1310
|
+
if (typeof body.error === "string") {
|
|
1311
|
+
return `oracle ${status}: ${body.error}`;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
catch {
|
|
1315
|
+
// not JSON
|
|
1316
|
+
}
|
|
1317
|
+
return `oracle ${status}`;
|
|
1318
|
+
}
|
|
1319
|
+
function applyOracleEvent(reply, outbox, event) {
|
|
1320
|
+
if (!event) {
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
// The oracle's header comes first, before the model has said anything.
|
|
1324
|
+
if (event.castle) {
|
|
1325
|
+
sendKeepalive(outbox);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
const error = event.error;
|
|
1329
|
+
if (error) {
|
|
1330
|
+
reply.error = typeof error.message === "string" ? error.message : "The model stream failed.";
|
|
1331
|
+
}
|
|
1332
|
+
const usage = event.usage;
|
|
1333
|
+
if (usage) {
|
|
1334
|
+
reply.usage = {
|
|
1335
|
+
prompt_tokens: usage.prompt_tokens ?? 0,
|
|
1336
|
+
completion_tokens: usage.completion_tokens ?? 0,
|
|
1337
|
+
total_tokens: usage.total_tokens ?? 0,
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
const choices = event.choices;
|
|
1341
|
+
const choice = choices?.[0];
|
|
1342
|
+
if (!choice) {
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
const delta = choice.delta ?? {};
|
|
1346
|
+
const reasoning = reasoningText(delta);
|
|
1347
|
+
if (reasoning !== "") {
|
|
1348
|
+
reply.reasoning += reasoning;
|
|
1349
|
+
queueText(outbox, "reasoning", reasoning);
|
|
1350
|
+
}
|
|
1351
|
+
if (typeof delta.content === "string" && delta.content !== "") {
|
|
1352
|
+
reply.content += delta.content;
|
|
1353
|
+
queueText(outbox, "text", delta.content);
|
|
1354
|
+
}
|
|
1355
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
1356
|
+
for (const piece of delta.tool_calls) {
|
|
1357
|
+
applyToolCallPiece(reply, outbox, piece);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if (typeof choice.finish_reason === "string") {
|
|
1361
|
+
reply.finishReason = choice.finish_reason;
|
|
1362
|
+
sendToolCalls(reply, outbox, reply.toolCalls.length);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
// OpenRouter puts reasoning in `reasoning`, some providers in
|
|
1366
|
+
// `reasoning_content`, and others only in `reasoning_details` text blocks.
|
|
1367
|
+
// Encrypted blocks carry no text.
|
|
1368
|
+
function reasoningText(delta) {
|
|
1369
|
+
if (typeof delta.reasoning === "string") {
|
|
1370
|
+
return delta.reasoning;
|
|
1371
|
+
}
|
|
1372
|
+
if (typeof delta.reasoning_content === "string") {
|
|
1373
|
+
return delta.reasoning_content;
|
|
1374
|
+
}
|
|
1375
|
+
if (!Array.isArray(delta.reasoning_details)) {
|
|
1376
|
+
return "";
|
|
1377
|
+
}
|
|
1378
|
+
let text = "";
|
|
1379
|
+
for (const block of delta.reasoning_details) {
|
|
1380
|
+
if (block?.type === "reasoning.text" && typeof block.text === "string") {
|
|
1381
|
+
text += block.text;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
return text;
|
|
1385
|
+
}
|
|
1386
|
+
// The first piece of a call carries its id and name; the arguments are a JSON
|
|
1387
|
+
// string split across every piece. Calls arrive one after another, so a piece
|
|
1388
|
+
// for a later index means every earlier call is complete.
|
|
1389
|
+
function applyToolCallPiece(reply, outbox, piece) {
|
|
1390
|
+
const calls = reply.toolCalls;
|
|
1391
|
+
const index = typeof piece.index === "number" ? piece.index : calls.length;
|
|
1392
|
+
sendToolCalls(reply, outbox, index);
|
|
1393
|
+
calls[index] ??= { id: "", type: "function", function: { name: "", arguments: "" } };
|
|
1394
|
+
const call = calls[index];
|
|
1395
|
+
const pieceFunction = (piece.function ?? {});
|
|
1396
|
+
if (typeof piece.id === "string" && piece.id !== "") {
|
|
1397
|
+
call.id = piece.id;
|
|
1398
|
+
}
|
|
1399
|
+
if (typeof pieceFunction.name === "string") {
|
|
1400
|
+
call.function.name += pieceFunction.name;
|
|
1401
|
+
}
|
|
1402
|
+
if (typeof pieceFunction.arguments === "string") {
|
|
1403
|
+
call.function.arguments += pieceFunction.arguments;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
// Send every call below `end` that has not been sent yet. A provider that
|
|
1407
|
+
// leaves out a call's id gets one here, so the deck can answer the call.
|
|
1408
|
+
function sendToolCalls(reply, outbox, end) {
|
|
1409
|
+
for (; reply.toolCallsSent < end; reply.toolCallsSent++) {
|
|
1410
|
+
const call = reply.toolCalls[reply.toolCallsSent];
|
|
1411
|
+
if (!call) {
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
if (call.id === "") {
|
|
1415
|
+
call.id = `call_${reply.toolCallsSent}`;
|
|
1416
|
+
}
|
|
1417
|
+
flushOutbox(outbox);
|
|
1418
|
+
outbox.send({ type: "toolCall", toolCall: { ...call, function: { ...call.function } } });
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
function agentChatResult(reply, outbox) {
|
|
1422
|
+
sendToolCalls(reply, outbox, reply.toolCalls.length);
|
|
1423
|
+
const toolCalls = reply.toolCalls.filter((call) => call !== undefined);
|
|
1424
|
+
if (reply.error) {
|
|
1425
|
+
return { status: "error", reason: reply.error };
|
|
1426
|
+
}
|
|
1427
|
+
if (reply.finishReason === null) {
|
|
1428
|
+
return { status: "error", reason: "The model stream ended before the reply finished." };
|
|
1429
|
+
}
|
|
1430
|
+
if (reply.content === "" && toolCalls.length === 0) {
|
|
1431
|
+
return { status: "error", reason: "The model returned an empty reply." };
|
|
1432
|
+
}
|
|
1433
|
+
const message = {
|
|
1434
|
+
role: "assistant",
|
|
1435
|
+
content: reply.content === "" ? null : reply.content,
|
|
1436
|
+
};
|
|
1437
|
+
if (toolCalls.length > 0) {
|
|
1438
|
+
message.tool_calls = toolCalls;
|
|
1439
|
+
}
|
|
1440
|
+
const result = { status: "ok", message, finishReason: reply.finishReason };
|
|
1441
|
+
if (reply.reasoning !== "") {
|
|
1442
|
+
result.reasoning = reply.reasoning;
|
|
1443
|
+
}
|
|
1444
|
+
if (reply.usage) {
|
|
1445
|
+
result.usage = reply.usage;
|
|
1446
|
+
}
|
|
1447
|
+
return result;
|
|
1448
|
+
}
|
|
1449
|
+
// A host's post to the deck can throw once the deck is gone. The throw is
|
|
1450
|
+
// dropped and the result still resolves. With no onStream, nothing is sent.
|
|
1451
|
+
function createOutbox(onStream) {
|
|
1452
|
+
return {
|
|
1453
|
+
send: (event) => {
|
|
1454
|
+
try {
|
|
1455
|
+
onStream?.(event);
|
|
1456
|
+
}
|
|
1457
|
+
catch {
|
|
1458
|
+
// dropped
|
|
1459
|
+
}
|
|
1460
|
+
},
|
|
1461
|
+
pending: null,
|
|
1462
|
+
timer: null,
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
function queueText(outbox, type, text) {
|
|
1466
|
+
if (outbox.pending && outbox.pending.type !== type) {
|
|
1467
|
+
flushOutbox(outbox);
|
|
1468
|
+
}
|
|
1469
|
+
outbox.pending ??= { type, text: "" };
|
|
1470
|
+
outbox.pending.text += text;
|
|
1471
|
+
outbox.timer ??= setTimeout(() => flushOutbox(outbox), DELTA_BATCH_MS);
|
|
1472
|
+
}
|
|
1473
|
+
function flushOutbox(outbox) {
|
|
1474
|
+
if (outbox.timer) {
|
|
1475
|
+
clearTimeout(outbox.timer);
|
|
1476
|
+
outbox.timer = null;
|
|
1477
|
+
}
|
|
1478
|
+
if (outbox.pending) {
|
|
1479
|
+
const event = outbox.pending;
|
|
1480
|
+
outbox.pending = null;
|
|
1481
|
+
outbox.send(event);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
// Queued text reaches the deck within DELTA_BATCH_MS and restarts its wait the
|
|
1485
|
+
// same way, so none is sent while text is pending.
|
|
1486
|
+
function sendKeepalive(outbox) {
|
|
1487
|
+
if (!outbox.pending) {
|
|
1488
|
+
outbox.send({ type: "keepalive" });
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
// An OracleStream over fetch and a streamed response body, for hosts that have
|
|
1492
|
+
// both: the browser and Node. `getToken` is read for each request.
|
|
1493
|
+
export function fetchOracleStream(getToken) {
|
|
1494
|
+
return (url, body, sink) => {
|
|
1495
|
+
const controller = new AbortController();
|
|
1496
|
+
const headers = { "Content-Type": "application/json" };
|
|
1497
|
+
const token = getToken();
|
|
1498
|
+
if (token) {
|
|
1499
|
+
headers["X-Auth-Token"] = token;
|
|
1500
|
+
}
|
|
1501
|
+
const request = fetch(url, { method: "POST", headers, body, signal: controller.signal });
|
|
1502
|
+
readFetchedStream(request, sink).catch((error) => {
|
|
1503
|
+
if (!controller.signal.aborted) {
|
|
1504
|
+
sink.fail(0, error instanceof Error ? error.message : String(error));
|
|
1505
|
+
}
|
|
1506
|
+
});
|
|
1507
|
+
return () => controller.abort();
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
async function readFetchedStream(request, sink) {
|
|
1511
|
+
const response = await request;
|
|
1512
|
+
if (response.status !== 200 || !response.body) {
|
|
1513
|
+
sink.fail(response.status, await response.text());
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
const parser = createEventParser(sink);
|
|
1517
|
+
const reader = response.body.getReader();
|
|
1518
|
+
const decoder = new TextDecoder();
|
|
1519
|
+
for (;;) {
|
|
1520
|
+
const { done, value } = await reader.read();
|
|
1521
|
+
if (done) {
|
|
1522
|
+
break;
|
|
1523
|
+
}
|
|
1524
|
+
parser.push(decoder.decode(value, { stream: true }));
|
|
1525
|
+
}
|
|
1526
|
+
parser.push(decoder.decode());
|
|
1527
|
+
// A last event with no blank line after it is still delivered.
|
|
1528
|
+
parser.push("\n\n");
|
|
1529
|
+
sink.end();
|
|
1530
|
+
}
|
|
1531
|
+
// Server-sent events: lines of `field: value`, a blank line ending each event.
|
|
1532
|
+
// Lines starting with ':' are comments, which OpenRouter sends while the model
|
|
1533
|
+
// is working. Pieces of text can split a line anywhere.
|
|
1534
|
+
function createEventParser(sink) {
|
|
1535
|
+
let buffer = "";
|
|
1536
|
+
let name = "message";
|
|
1537
|
+
let data = [];
|
|
1538
|
+
return {
|
|
1539
|
+
push(text) {
|
|
1540
|
+
buffer += text;
|
|
1541
|
+
let newline = buffer.indexOf("\n");
|
|
1542
|
+
while (newline >= 0) {
|
|
1543
|
+
const line = buffer.slice(0, newline).replace(/\r$/, "");
|
|
1544
|
+
buffer = buffer.slice(newline + 1);
|
|
1545
|
+
newline = buffer.indexOf("\n");
|
|
1546
|
+
if (line === "") {
|
|
1547
|
+
if (data.length > 0) {
|
|
1548
|
+
sink.event(name, data.join("\n"));
|
|
1549
|
+
}
|
|
1550
|
+
name = "message";
|
|
1551
|
+
data = [];
|
|
1552
|
+
}
|
|
1553
|
+
else if (line.startsWith("data:")) {
|
|
1554
|
+
data.push(line.slice(5).replace(/^ /, ""));
|
|
1555
|
+
}
|
|
1556
|
+
else if (line.startsWith("event:")) {
|
|
1557
|
+
name = line.slice(6).trim();
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
},
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
// ---------------------------------------------------------------------------
|
|
1017
1564
|
// Cauldron deck storage.
|
|
1018
1565
|
//
|
|
1019
1566
|
// Each of these maps to exactly one bounded server-side operation. The deck
|
|
@@ -47,6 +47,44 @@ const OPERATIONS = {
|
|
|
47
47
|
) { operationId characterId status result archived }
|
|
48
48
|
}`,
|
|
49
49
|
},
|
|
50
|
+
characterEvaluateBeats: {
|
|
51
|
+
field: 'cauldronCharacterWorldCommand',
|
|
52
|
+
query: `mutation CastleDevCharacterEvaluateBeats(
|
|
53
|
+
$deckId: ID!
|
|
54
|
+
$subject: ID!
|
|
55
|
+
$generation: Int!
|
|
56
|
+
$operationId: String!
|
|
57
|
+
$command: Json!
|
|
58
|
+
) {
|
|
59
|
+
cauldronCharacterWorldCommand(
|
|
60
|
+
deckId: $deckId
|
|
61
|
+
subject: $subject
|
|
62
|
+
generation: $generation
|
|
63
|
+
operationId: $operationId
|
|
64
|
+
command: $command
|
|
65
|
+
asServer: true
|
|
66
|
+
) { operationId characterId status result archived }
|
|
67
|
+
}`,
|
|
68
|
+
},
|
|
69
|
+
characterCompleteScheduledBeat: {
|
|
70
|
+
field: 'cauldronCharacterWorldCommand',
|
|
71
|
+
query: `mutation CastleDevCharacterCompleteScheduledBeat(
|
|
72
|
+
$deckId: ID!
|
|
73
|
+
$subject: ID!
|
|
74
|
+
$generation: Int!
|
|
75
|
+
$operationId: String!
|
|
76
|
+
$command: Json!
|
|
77
|
+
) {
|
|
78
|
+
cauldronCharacterWorldCommand(
|
|
79
|
+
deckId: $deckId
|
|
80
|
+
subject: $subject
|
|
81
|
+
generation: $generation
|
|
82
|
+
operationId: $operationId
|
|
83
|
+
command: $command
|
|
84
|
+
asServer: true
|
|
85
|
+
) { operationId characterId status result archived }
|
|
86
|
+
}`,
|
|
87
|
+
},
|
|
50
88
|
characterStatus: {
|
|
51
89
|
field: 'cauldronCharacterStatus',
|
|
52
90
|
query: `query CastleDevCharacterStatus($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!) {
|
|
@@ -331,12 +369,35 @@ export async function runDevStorageOperation(deckId, op, args, connectedUserIds
|
|
|
331
369
|
operationId: args.operationId,
|
|
332
370
|
command: {
|
|
333
371
|
type: 'evaluate_information',
|
|
334
|
-
...(args.maxDeliveries === undefined
|
|
335
|
-
? {}
|
|
336
|
-
: { maxDeliveries: args.maxDeliveries }),
|
|
372
|
+
...(args.maxDeliveries === undefined ? {} : { maxDeliveries: args.maxDeliveries }),
|
|
337
373
|
},
|
|
338
374
|
}
|
|
339
|
-
:
|
|
375
|
+
: op === 'characterEvaluateBeats'
|
|
376
|
+
? {
|
|
377
|
+
deckId,
|
|
378
|
+
subject: args.subject,
|
|
379
|
+
generation: args.generation,
|
|
380
|
+
operationId: args.operationId,
|
|
381
|
+
command: {
|
|
382
|
+
type: 'evaluate_beats',
|
|
383
|
+
opportunityId: args.opportunityId,
|
|
384
|
+
opportunity: args.opportunity,
|
|
385
|
+
presentCharacterIds: args.presentCharacterIds,
|
|
386
|
+
},
|
|
387
|
+
}
|
|
388
|
+
: op === 'characterCompleteScheduledBeat'
|
|
389
|
+
? {
|
|
390
|
+
deckId,
|
|
391
|
+
subject: args.subject,
|
|
392
|
+
generation: args.generation,
|
|
393
|
+
operationId: args.operationId,
|
|
394
|
+
command: {
|
|
395
|
+
type: 'complete_scheduled_beat',
|
|
396
|
+
deliveryId: args.deliveryId,
|
|
397
|
+
outcomeId: args.outcomeId,
|
|
398
|
+
},
|
|
399
|
+
}
|
|
400
|
+
: { ...args, deckId };
|
|
340
401
|
const response = await graphql(operation.query, variables);
|
|
341
402
|
const error = response.errors?.[0];
|
|
342
403
|
if (error) {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type EffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
2
|
+
export declare const EFFORT_ORDER: readonly EffortLevel[];
|
|
3
|
+
export declare const UNSUPPORTED_EFFORTS: Readonly<Record<string, readonly EffortLevel[]>>;
|
|
4
|
+
export declare function effortSupported(slug: string, effort: EffortLevel): boolean;
|
|
5
|
+
export declare function supportedEffort(slug: string, effort: EffortLevel): EffortLevel;
|
|
6
|
+
export declare function isEffortLevel(value: string): value is EffortLevel;
|
|
7
|
+
export declare function pressedEffort(slug: string | null, stored: string): string;
|