castle-web-cli 0.4.204 → 0.4.206

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.
Files changed (134) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +7 -2
  5. package/dist/agent.d.ts +3 -2
  6. package/dist/agent.js +29 -18
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/devSessionStorage.js +65 -4
  10. package/dist/effortSupport.d.ts +7 -0
  11. package/dist/effortSupport.js +31 -0
  12. package/dist/imports.d.ts +1 -1
  13. package/dist/imports.js +59 -19
  14. package/dist/index.js +4 -3
  15. package/dist/init.d.ts +9 -1
  16. package/dist/init.js +64 -25
  17. package/dist/kitCatalog.d.ts +13 -0
  18. package/dist/kitCatalog.js +111 -0
  19. package/dist/platformDoc.js +7 -2
  20. package/dist/serve.js +35 -2
  21. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  22. package/dist/shell/index.html +1 -1
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +5 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +5 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-2d/castle.json +1 -0
  56. package/kits/physics-3d/CLAUDE.md +65 -7
  57. package/kits/physics-3d/castle.json +4 -3
  58. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  59. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  60. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  61. package/kits/physics-3d/engine3d/blob.js +1058 -0
  62. package/kits/physics-3d/engine3d/branches.js +300 -0
  63. package/kits/physics-3d/engine3d/cage.js +496 -0
  64. package/kits/physics-3d/engine3d/cageops.js +516 -0
  65. package/kits/physics-3d/engine3d/frame.js +669 -0
  66. package/kits/physics-3d/engine3d/look.js +675 -0
  67. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  68. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  69. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  70. package/kits/physics-3d/engine3d/motion.js +560 -0
  71. package/kits/physics-3d/engine3d/objtext.js +37 -0
  72. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  73. package/kits/physics-3d/engine3d/paint.js +674 -0
  74. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  75. package/kits/physics-3d/engine3d/paths.js +324 -0
  76. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  77. package/kits/physics-3d/engine3d/scatter.js +102 -0
  78. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  79. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  80. package/kits/physics-3d/engine3d/sweep.js +480 -0
  81. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  82. package/kits/physics-3d/engine3d/world3d.js +119 -17
  83. package/kits/physics-3d/eslint.config.js +13 -0
  84. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  85. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  86. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  88. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  89. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  90. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  91. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  92. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  93. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  94. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  95. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  96. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  97. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  98. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  99. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  100. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  101. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  102. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  103. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  104. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  105. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  106. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  108. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  109. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  110. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  111. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  112. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  113. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  114. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  115. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  116. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  117. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  118. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  119. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  120. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  121. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  122. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  123. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  124. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  125. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  126. package/kits/physics-3d/scripts/render/index.html +20 -0
  127. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  128. package/kits/physics-3d/scripts/render.mjs +646 -0
  129. package/kits/real-time/castle.json +2 -2
  130. package/kits/real-time/code/client/ownership.js +14 -4
  131. package/kits/real-time/code/client/smooth.js +2 -2
  132. package/kits/real-time/code/server/session.js +20 -4
  133. package/kits/turn-based/castle.json +1 -0
  134. package/package.json +2 -2
@@ -10,7 +10,7 @@
10
10
  <link rel="icon" type="image/png" sizes="32x32" href="/__castle/ide/favicon-32x32.png" />
11
11
  <link rel="icon" type="image/png" sizes="16x16" href="/__castle/ide/favicon-16x16.png" />
12
12
  <link rel="icon" href="/__castle/ide/favicon.ico" sizes="any" />
13
- <script type="module" crossorigin src="/__castle/ide/assets/index-DHzA0-Sj.js"></script>
13
+ <script type="module" crossorigin src="/__castle/ide/assets/index-hWQTC8q6.js"></script>
14
14
  <link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-b_bebkRb.css">
15
15
  </head>
16
16
  <body>
@@ -112,6 +112,24 @@ function splitQuery(id) {
112
112
  const at = id.indexOf('?');
113
113
  return at < 0 ? [id, ''] : [id.slice(0, at), id.slice(at)];
114
114
  }
115
+ // A resolved file's path relative to the deck root. Vite resolves symlinks to
116
+ // their targets, so when `imports/` is a link to another deck's (a model
117
+ // render's scratch deck) its files resolve outside the root; those are mapped
118
+ // back under `imports/`.
119
+ function deckRelative(root, file) {
120
+ let linkedImports;
121
+ try {
122
+ linkedImports = fs.realpathSync(path.join(root, IMPORTS_DIR));
123
+ }
124
+ catch {
125
+ return path.relative(root, file);
126
+ }
127
+ const insideImports = path.relative(linkedImports, file);
128
+ if (insideImports.startsWith('..') || path.isAbsolute(insideImports)) {
129
+ return path.relative(root, file);
130
+ }
131
+ return path.join(IMPORTS_DIR, insideImports);
132
+ }
115
133
  // A forked file stands in for the imported one it overrides, at resolve time.
116
134
  //
117
135
  // Resolve rather than load, deliberately: the module id becomes the fork's own
@@ -152,7 +170,7 @@ export function forksOverlayPlugin() {
152
170
  // `?raw` and friends ride along: the query says how to hand the file back,
153
171
  // and that is the same question whether or not it was forked.
154
172
  const [file, query] = splitQuery(resolved);
155
- const rel = path.relative(root, file);
173
+ const rel = deckRelative(root, file);
156
174
  const inDeck = !rel.startsWith('..') && !path.isAbsolute(rel);
157
175
  const forked = inDeck ? resolveForkedFile(root, rel.split(path.sep).join('/')) : null;
158
176
  if (forked)
@@ -15,6 +15,8 @@ that framework provides. This one is true either way.
15
15
  <!-- Injected into Castle's create assistant every turn; keep this compact and factual. -->
16
16
 
17
17
  - `import { setup, initCard } from 'castle-web-sdk'`. Call `setup()` first, once; `initCard()` returns the element to render into (a React tree mounted at `#root` needs no `initCard`). Castle services — `Store`, `Leaderboard`, `Time`, `User`, `Haptics`, `Pass`, `Snapshot`, `Portal`, `Multiplayer`, `Lifecycle` — come from the same package. `Store` is how a deck saves anything; the older `Storage`/`SharedStorage` still work but should not be used in new decks; the full reference is `imports/castle.base/sdk/README.md`.
18
+ - `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3`) through Castle's oracle on the player's account. `onDelta` streams text and reasoning pieces and each finished tool call; `signal` cancels; `reasoning: { effort: 'minimal' | 'low' | 'medium' | 'high' }` sets how hard the model thinks, and minimal answers soonest. It resolves with the whole `message`: the deck runs any `tool_calls` itself, appends the message and the `tool` results, and calls again. Admin only: other players get `refused`.
19
+ - `Decks.mine({ limit? })` and `Decks.saved({ limit? })` list decks a portal can lead to (the player's published decks; their bookmarks and playlists) as `{ deckId, title, creator, coverUrl }`, with `coverUrl` a `data:` url. Use them to offer a portal destination picker. Admin only: other players get a `PERMISSION_DENIED` error.
18
20
  - The SDK is a file of this import, not an npm package: `castle-web-sdk` resolves here. Nothing needs installing, and nothing in a deck's `package.json` names it.
19
21
  - Vite serves and bundles the deck: ES modules, JSX, JSON, CSS and npm packages all work with no build step of your own — don't add one.
20
22
  - Details: `## Files`, `## Editors` and `## The SDK` in this file (`imports/castle.base/CLAUDE.md`). The rules every deck plays by -- the card, touch, assets and formats, imports, reloading -- are the platform's: `.castle/docs/platform.md`, written by the serve.
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-09-23T08:30:22.540Z",
85
+ "publishedVersion": "2026-09-24T21:25:28.679Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -24,7 +24,9 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
24
24
  - [Pass](#pass)
25
25
  - [Snapshot](#snapshot)
26
26
  - [Portal](#portal)
27
+ - [Decks](#decks)
27
28
  - [Haptics](#haptics)
29
+ - [Agent](#agent)
28
30
  - [Lifecycle](#lifecycle)
29
31
  - [Multiplayer](#multiplayer)
30
32
  - [Setup](#setup)
@@ -616,6 +618,38 @@ if (info.status === "ok") {
616
618
 
617
619
  Answers are kept per deck for the session, so asking again is cheap.
618
620
 
621
+ ## Decks
622
+
623
+ `Decks` lists decks the player can point a portal at: their own published
624
+ decks, and the decks they saved. A deck can offer these as a picker rather
625
+ than asking for a pasted link.
626
+ Decks is limited to Castle admins for now; for every other player both calls
627
+ reject with a `PERMISSION_DENIED` error.
628
+
629
+ ### `Decks.mine(options?): Promise<DecksListResult>`
630
+
631
+ The player's own decks, newest first, leaving out private ones.
632
+
633
+ ### `Decks.saved(options?): Promise<DecksListResult>`
634
+
635
+ The decks the player bookmarked, then the decks in their playlists, each
636
+ once.
637
+
638
+ Both take `{ limit }`, from 1 through 50 (default 20), and both leave out
639
+ decks whose creator turned portals off. The result is
640
+ `{ status: 'ok', decks }`, where each deck is
641
+ `{ deckId, title, creator: { userId, username } | null, coverUrl }` — the
642
+ same shape as `Portal.info`. `coverUrl` is a `data:` url, since a deck may
643
+ not load remote images; it is null when the deck has no cover. A player
644
+ who is not signed in gets an empty list.
645
+
646
+ ```js
647
+ const { decks } = await Decks.mine({ limit: 12 });
648
+ for (const deck of decks) {
649
+ addPickerTile(deck.title, deck.coverUrl, () => placePortal(deck.deckId));
650
+ }
651
+ ```
652
+
619
653
  ## Haptics
620
654
 
621
655
  `Haptics` plays a short device vibration ("buzz") for tactile feedback —
@@ -651,6 +685,103 @@ Haptics respect the player's settings — if a player has muted haptics,
651
685
  `play` does nothing and resolves `'unavailable'`. Rapid repeated calls may
652
686
  be coalesced, so it's safe to call on frequent events.
653
687
 
688
+ ## Agent
689
+
690
+ `Agent` asks a language model for one chat completion. The host sends it
691
+ through Castle's oracle on the player's own Castle account, so the deck
692
+ holds no key. Agent.chat is limited to Castle admins for now; every other
693
+ player gets `'refused'`.
694
+
695
+ ### `Agent.chat(params): Promise<AgentChatResult>`
696
+
697
+ `params`:
698
+
699
+ - `messages` — the conversation, in the OpenAI chat format
700
+ (`{ role, content }`, plus `tool_calls` on an assistant message and
701
+ `tool_call_id` on a `'tool'` message).
702
+ - `tools` — optional function tools, in the OpenAI function-tool schema.
703
+ - `toolChoice` — optional: `'auto'` (the default), `'none'`, `'required'`,
704
+ or `{ type: 'function', function: { name } }` to force one tool.
705
+ - `model` — optional OpenRouter model id. Defaults to
706
+ `'meta/muse-spark-1.3'`.
707
+ - `maxTokens` — optional cap on the reply's length.
708
+ - `reasoning` — optional `{ effort: 'minimal' | 'low' | 'medium' | 'high' }`,
709
+ how hard the model thinks before it answers. Lower effort answers sooner.
710
+ Left out, the model uses its own default. Muse can't turn reasoning off;
711
+ `'minimal'` is its least.
712
+ - `onDelta` — optional callback for the reply as it streams in. It gets
713
+ `{ type: 'text', text }` and `{ type: 'reasoning', text }` pieces, and
714
+ `{ type: 'toolCall', toolCall }` once for each tool call, when its
715
+ arguments are complete. Pieces come in the order the model wrote them.
716
+ - `signal` — optional `AbortSignal`. Aborting it stops the model and
717
+ resolves the call with `'cancelled'` at once.
718
+
719
+ The promise resolves with the whole message when the model finishes. A deck
720
+ runs any tool calls itself, appends the message and one `'tool'` message per
721
+ call, and calls Agent.chat again, until a reply has no tool calls:
722
+
723
+ ```js
724
+ import { Agent } from "castle-web-sdk";
725
+
726
+ const tools = [
727
+ {
728
+ type: "function",
729
+ function: {
730
+ name: "roll_dice",
731
+ description: "Roll six-sided dice.",
732
+ parameters: {
733
+ type: "object",
734
+ properties: { count: { type: "integer" } },
735
+ required: ["count"],
736
+ },
737
+ },
738
+ },
739
+ ];
740
+ const messages = [{ role: "user", content: "Roll two dice and add them." }];
741
+ const stop = new AbortController();
742
+
743
+ for (let round = 0; round < 8; round++) {
744
+ const result = await Agent.chat({
745
+ messages,
746
+ tools,
747
+ signal: stop.signal,
748
+ onDelta: (delta) => {
749
+ if (delta.type === "text") {
750
+ showText(delta.text);
751
+ }
752
+ },
753
+ });
754
+ if (result.status !== "ok") {
755
+ break;
756
+ }
757
+ messages.push(result.message);
758
+ const calls = result.message.tool_calls ?? [];
759
+ if (calls.length === 0) {
760
+ break;
761
+ }
762
+ for (const call of calls) {
763
+ const { count } = JSON.parse(call.function.arguments);
764
+ const faces = Array.from({ length: count }, () => 1 + Math.floor(Math.random() * 6));
765
+ messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(faces) });
766
+ }
767
+ }
768
+ ```
769
+
770
+ `AgentChatResult` has a `status`:
771
+
772
+ - `'ok'` — `message` is the assistant's reply: `{ role, content,
773
+ tool_calls? }`, with `content` null when the reply is only tool calls.
774
+ `reasoning` is the model's reasoning summary when it gave one, for
775
+ display; it is not part of `message`. `finishReason` is `'stop'`,
776
+ `'tool_calls'` or `'length'`. `usage` carries `prompt_tokens`,
777
+ `completion_tokens` and `total_tokens`.
778
+ - `'refused'` — the player is not a Castle admin. The model was not called.
779
+ - `'unavailable'` — this host has no route to the oracle.
780
+ - `'cancelled'` — the call's `signal` was aborted.
781
+ - `'error'` — the oracle or the model failed; `reason` says how.
782
+
783
+ Every status but `'ok'` carries a `reason`.
784
+
654
785
  ## Lifecycle
655
786
 
656
787
  `Lifecycle` tells the host when the deck has painted its first frame, so
@@ -0,0 +1,6 @@
1
+ import type { AgentChatParams, AgentChatResult } from "./commands";
2
+ export type { AgentChatDelta, AgentChatParams, AgentChatResult, AgentMessage, AgentReasoning, AgentTool, AgentToolCall, AgentToolChoice, AgentUsage, } from "./commands";
3
+ export interface CastleAgentApi {
4
+ chat(params: AgentChatParams): Promise<AgentChatResult>;
5
+ }
6
+ export declare const Agent: CastleAgentApi;
@@ -0,0 +1,70 @@
1
+ // Agent — one chat completion from a language model, run by the host through
2
+ // Castle's oracle with the player's own Castle account. Messages and tools
3
+ // follow the OpenAI chat completions format. The reply streams: `onDelta` gets
4
+ // text and reasoning as they arrive and each tool call once its arguments are
5
+ // complete, and the promise resolves with the whole message. A deck runs any
6
+ // tool calls itself and calls Agent.chat again with the results.
7
+ //
8
+ // Agent.chat is limited to Castle admins for now: every other player gets
9
+ // `refused`. A host with no route to the oracle answers `unavailable`.
10
+ import { CastleError } from "./errors";
11
+ import { hostRequest } from "./transport";
12
+ async function chat(params) {
13
+ validate(params);
14
+ const onDelta = params.onDelta;
15
+ try {
16
+ return await hostRequest("agent.chat", {
17
+ messages: params.messages,
18
+ tools: params.tools,
19
+ toolChoice: params.toolChoice,
20
+ model: params.model,
21
+ maxTokens: params.maxTokens,
22
+ reasoning: params.reasoning,
23
+ }, {
24
+ onStream: onDelta ? (event) => deliverDelta(onDelta, event) : undefined,
25
+ signal: params.signal,
26
+ });
27
+ }
28
+ catch (error) {
29
+ if (error instanceof CastleError && error.code === "CANCELLED") {
30
+ return { status: "cancelled", reason: "Agent.chat was cancelled." };
31
+ }
32
+ throw error;
33
+ }
34
+ }
35
+ const REASONING_EFFORTS = ["minimal", "low", "medium", "high"];
36
+ function validate(params) {
37
+ if (!params || typeof params !== "object") {
38
+ invalid("Agent.chat requires { messages }.");
39
+ }
40
+ if (!Array.isArray(params.messages) || params.messages.length === 0) {
41
+ invalid("Agent.chat messages must be a non-empty array.");
42
+ }
43
+ if (params.tools !== undefined && !Array.isArray(params.tools)) {
44
+ invalid("Agent.chat tools must be an array.");
45
+ }
46
+ if (params.model !== undefined && (typeof params.model !== "string" || params.model === "")) {
47
+ invalid("Agent.chat model must be a model id.");
48
+ }
49
+ if (params.maxTokens !== undefined &&
50
+ (!Number.isSafeInteger(params.maxTokens) || params.maxTokens < 1)) {
51
+ invalid("Agent.chat maxTokens must be a positive integer.");
52
+ }
53
+ if (params.reasoning !== undefined && !REASONING_EFFORTS.includes(params.reasoning?.effort)) {
54
+ invalid("Agent.chat reasoning must be { effort: 'minimal' | 'low' | 'medium' | 'high' }.");
55
+ }
56
+ if (params.onDelta !== undefined && typeof params.onDelta !== "function") {
57
+ invalid("Agent.chat onDelta must be a function.");
58
+ }
59
+ }
60
+ // Keepalives only restart the wait in transport.ts; the deck never sees them.
61
+ function deliverDelta(onDelta, event) {
62
+ const type = event?.type;
63
+ if (type === "text" || type === "reasoning" || type === "toolCall") {
64
+ onDelta(event);
65
+ }
66
+ }
67
+ function invalid(message) {
68
+ throw new CastleError({ code: "INVALID_ARGUMENT", message, operation: "Agent.chat" });
69
+ }
70
+ export const Agent = Object.freeze({ chat });
@@ -1,6 +1,10 @@
1
1
  export { isEdit } from "./context";
2
+ export { Agent } from "./agent";
3
+ export type { AgentChatDelta, AgentChatParams, AgentChatResult, AgentMessage, AgentReasoning, AgentTool, AgentToolCall, AgentToolChoice, AgentUsage, CastleAgentApi, } from "./agent";
2
4
  export { Characters } from "./characters";
3
5
  export type { CastleCharactersApi, CharacterHandle, CharacterHistoryOptions, CharacterSendInput, } from "./characters";
6
+ export { Decks } from "./decks";
7
+ export type { CastleDecksApi, DeckSummary, DecksListParams, DecksListResult } from "./decks";
4
8
  export { CastleError } from "./errors";
5
9
  export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
6
10
  export { Haptics } from "./haptics";
@@ -1,6 +1,8 @@
1
1
  // Castle Web SDK
2
2
  export { isEdit } from "./context";
3
+ export { Agent } from "./agent";
3
4
  export { Characters } from "./characters";
5
+ export { Decks } from "./decks";
4
6
  export { CastleError } from "./errors";
5
7
  export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
6
8
  export { Haptics } from "./haptics";
@@ -142,7 +142,97 @@ export interface CharacterHistory {
142
142
  operations: CharacterOperation[];
143
143
  cursor: string | null;
144
144
  }
145
+ export interface AgentToolCall {
146
+ id: string;
147
+ type: "function";
148
+ function: {
149
+ name: string;
150
+ arguments: string;
151
+ };
152
+ }
153
+ export interface AgentMessage {
154
+ role: "system" | "user" | "assistant" | "tool";
155
+ content: string | Json[] | null;
156
+ tool_calls?: AgentToolCall[];
157
+ tool_call_id?: string;
158
+ name?: string;
159
+ }
160
+ export interface AgentTool {
161
+ type: "function";
162
+ function: {
163
+ name: string;
164
+ description?: string;
165
+ parameters?: Json;
166
+ };
167
+ }
168
+ export type AgentToolChoice = "auto" | "none" | "required" | {
169
+ type: "function";
170
+ function: {
171
+ name: string;
172
+ };
173
+ };
174
+ export type AgentChatDelta = {
175
+ type: "text";
176
+ text: string;
177
+ } | {
178
+ type: "reasoning";
179
+ text: string;
180
+ } | {
181
+ type: "toolCall";
182
+ toolCall: AgentToolCall;
183
+ };
184
+ export type AgentChatStreamEvent = AgentChatDelta | {
185
+ type: "keepalive";
186
+ };
187
+ export interface AgentReasoning {
188
+ effort: "minimal" | "low" | "medium" | "high";
189
+ }
190
+ export interface AgentChatParams {
191
+ messages: AgentMessage[];
192
+ tools?: AgentTool[];
193
+ toolChoice?: AgentToolChoice;
194
+ model?: string;
195
+ maxTokens?: number;
196
+ reasoning?: AgentReasoning;
197
+ onDelta?: (delta: AgentChatDelta) => void;
198
+ signal?: AbortSignal;
199
+ }
200
+ export type AgentChatRequest = Omit<AgentChatParams, "onDelta" | "signal">;
201
+ export interface AgentUsage {
202
+ prompt_tokens: number;
203
+ completion_tokens: number;
204
+ total_tokens: number;
205
+ }
206
+ export type AgentChatResult = {
207
+ status: "ok";
208
+ message: AgentMessage;
209
+ reasoning?: string;
210
+ finishReason: string | null;
211
+ usage?: AgentUsage;
212
+ } | {
213
+ status: "unavailable" | "refused" | "error" | "cancelled";
214
+ reason: string;
215
+ };
216
+ export interface DeckSummary {
217
+ deckId: string;
218
+ title: string;
219
+ creator: {
220
+ userId: string;
221
+ username: string;
222
+ } | null;
223
+ coverUrl: string | null;
224
+ }
225
+ export interface DecksListParams {
226
+ limit?: number | null;
227
+ }
228
+ export interface DecksListResult {
229
+ status: "ok";
230
+ decks: DeckSummary[];
231
+ }
145
232
  export interface CommandParams {
233
+ "agent.chat": AgentChatRequest;
234
+ "decks.mine": DecksListParams;
235
+ "decks.saved": DecksListParams;
146
236
  "deckStorage.load": Record<string, never>;
147
237
  "deckStorage.update": {
148
238
  updates: StorageUpdate[];
@@ -279,6 +369,9 @@ export interface CommandParams {
279
369
  "lifecycle.restoreState": Record<string, never>;
280
370
  }
281
371
  export interface CommandResult {
372
+ "agent.chat": AgentChatResult;
373
+ "decks.mine": DecksListResult;
374
+ "decks.saved": DecksListResult;
282
375
  "deckStorage.load": {
283
376
  blob: StorageBlob;
284
377
  };
@@ -365,6 +458,8 @@ export interface UserPayload {
365
458
  color: string | null;
366
459
  }
367
460
  export type CommandName = keyof CommandParams;
461
+ export declare const COMMAND_TIMEOUTS_MS: Partial<Record<CommandName, number>>;
462
+ export declare const STREAM_IDLE_TIMEOUT_MS = 60000;
368
463
  export interface SerializedCommandError {
369
464
  code: string;
370
465
  message: string;
@@ -385,6 +480,17 @@ export interface CommandResponseEnvelope {
385
480
  error?: SerializedCommandError;
386
481
  }
387
482
  export declare function isResponseEnvelope(value: unknown): value is CommandResponseEnvelope;
483
+ export interface CommandStreamEnvelope {
484
+ castleSdk: typeof CASTLE_SDK_PROTOCOL;
485
+ requestId: string;
486
+ stream: unknown;
487
+ }
488
+ export declare function isStreamEnvelope(value: unknown): value is CommandStreamEnvelope;
489
+ export interface CommandCancelEnvelope {
490
+ castleSdk: typeof CASTLE_SDK_PROTOCOL;
491
+ requestId: string;
492
+ cancel: true;
493
+ }
388
494
  export type LifecycleEvent = "ready" | "unloadInterest";
389
495
  export interface LifecycleEnvelope {
390
496
  castleSdk: typeof CASTLE_SDK_PROTOCOL;
@@ -6,6 +6,18 @@
6
6
  // Marker + protocol version. Doubles as a discriminator so host messages can't
7
7
  // be confused with embed.js `castlexyz:` strings or RN console messages.
8
8
  export const CASTLE_SDK_PROTOCOL = 1;
9
+ // How long the deck waits for a reply to these commands, in place of the
10
+ // data-command timeout. A deck list fetches every cover on the list. A host
11
+ // from before streaming reads a whole model reply before answering agent.chat.
12
+ export const COMMAND_TIMEOUTS_MS = {
13
+ "agent.chat": 180_000,
14
+ "decks.mine": 30_000,
15
+ "decks.saved": 30_000,
16
+ };
17
+ // Once a host streams a command, each stream envelope restarts the wait at this
18
+ // length instead. The oracle sends a heartbeat every 15 seconds, and the host
19
+ // passes each one on.
20
+ export const STREAM_IDLE_TIMEOUT_MS = 60_000;
9
21
  export function isResponseEnvelope(value) {
10
22
  if (typeof value !== "object" || value === null)
11
23
  return false;
@@ -14,6 +26,15 @@ export function isResponseEnvelope(value) {
14
26
  typeof record.requestId === "string" &&
15
27
  typeof record.ok === "boolean");
16
28
  }
29
+ export function isStreamEnvelope(value) {
30
+ if (typeof value !== "object" || value === null) {
31
+ return false;
32
+ }
33
+ const record = value;
34
+ return (record.castleSdk === CASTLE_SDK_PROTOCOL &&
35
+ typeof record.requestId === "string" &&
36
+ "stream" in record);
37
+ }
17
38
  export function unloadRequestId(value) {
18
39
  if (typeof value !== "object" || value === null)
19
40
  return null;
@@ -0,0 +1,7 @@
1
+ import type { DecksListParams, DecksListResult } from "./commands";
2
+ export type { DeckSummary, DecksListParams, DecksListResult } from "./commands";
3
+ export interface CastleDecksApi {
4
+ mine(options?: DecksListParams): Promise<DecksListResult>;
5
+ saved(options?: DecksListParams): Promise<DecksListResult>;
6
+ }
7
+ export declare const Decks: CastleDecksApi;
@@ -0,0 +1,31 @@
1
+ // Decks — the player's own published decks and the decks they saved, for
2
+ // picking where a portal leads. Each entry has the same shape as Portal.info:
3
+ // deckId, title, creator and a cover as a data: url.
4
+ //
5
+ // Both lists leave out decks a portal cannot reach: a private deck, or one
6
+ // whose creator turned portals off.
7
+ //
8
+ // Decks is limited to Castle admins for now; other players get a
9
+ // PERMISSION_DENIED error.
10
+ import { CastleError } from "./errors";
11
+ import { hostRequest } from "./transport";
12
+ function mine(options = {}) {
13
+ return hostRequest("decks.mine", { limit: listLimit(options.limit, "Decks.mine") });
14
+ }
15
+ function saved(options = {}) {
16
+ return hostRequest("decks.saved", { limit: listLimit(options.limit, "Decks.saved") });
17
+ }
18
+ function listLimit(value, operation) {
19
+ if (value === undefined || value === null) {
20
+ return null;
21
+ }
22
+ if (Number.isSafeInteger(value) && value >= 1 && value <= 50) {
23
+ return value;
24
+ }
25
+ throw new CastleError({
26
+ code: "INVALID_ARGUMENT",
27
+ message: `${operation} limit must be an integer from 1 through 50.`,
28
+ operation,
29
+ });
30
+ }
31
+ export const Decks = Object.freeze({ mine, saved });
@@ -1,4 +1,4 @@
1
- import { type CommandName, type CommandParams, type CommandResponseEnvelope } from "./commands";
1
+ import { type CommandName, type CommandParams, type CommandResponseEnvelope, type CommandStreamEnvelope } from "./commands";
2
2
  import { type TunedParam } from "./paramsRegistry";
3
3
  export declare const CARD_RATIO: number;
4
4
  interface LocalResponse {
@@ -43,7 +43,9 @@ export declare function renameFile(from: string, to: string): Promise<void>;
43
43
  export declare function deleteFile(path: string): Promise<void>;
44
44
  export declare function openFile(path: string): void;
45
45
  export declare function initCard(): HTMLDivElement;
46
- export declare function sendLocalCommand<C extends CommandName>(command: C, params: CommandParams[C]): Promise<CommandResponseEnvelope>;
46
+ export declare function sendLocalCommand<C extends CommandName>(requestId: string, command: C, params: CommandParams[C], listener: (message: CommandResponseEnvelope | CommandStreamEnvelope) => void): Promise<void>;
47
+ export declare function cancelLocalCommand(requestId: string): void;
48
+ export declare function releaseLocalCommand(requestId: string): void;
47
49
  /**
48
50
  * Notified `true` on every fresh dev-server socket and `false` when one is lost.
49
51
  * What lets a queued write know the moment retrying is worth it again.
@@ -13,10 +13,9 @@ const pendingRequests = new Map();
13
13
  // Local-dev command channel: the `castle-web serve` dev server is the host, so
14
14
  // SDK commands ride the same websocket runtime.ts already uses for
15
15
  // logs/screenshots/restart. Correlated by requestId, separate from the
16
- // screenshot/write_file request map above.
17
- const COMMAND_TIMEOUT_MS = 15000;
16
+ // screenshot/write_file request map above. transport.ts owns the timeouts.
18
17
  const SOCKET_WAIT_TIMEOUT_MS = 10000;
19
- const pendingCommands = new Map();
18
+ const localCommandListeners = new Map();
20
19
  const origLog = console.log;
21
20
  const origWarn = console.warn;
22
21
  const origError = console.error;
@@ -324,38 +323,42 @@ function sendLocalRequest(msg) {
324
323
  ws.send(JSON.stringify(request));
325
324
  });
326
325
  }
327
- // Send an SDK command to the dev server and resolve with the raw response
328
- // envelope (ok/data/error). transport.ts interprets it — error reconstruction
329
- // stays uniform across all three channels there. Waits for the socket to open
330
- // so a command issued during startup isn't dropped.
331
- export function sendLocalCommand(command, params) {
332
- const requestId = `cmd_${nextRequestId++}`;
333
- return new Promise((resolve, reject) => {
334
- const timeout = setTimeout(() => {
335
- pendingCommands.delete(requestId);
336
- reject(new Error(`Timed out waiting for command ${command}.`));
337
- }, COMMAND_TIMEOUT_MS);
338
- pendingCommands.set(requestId, (env) => {
339
- clearTimeout(timeout);
340
- pendingCommands.delete(requestId);
341
- resolve(env);
342
- });
343
- waitForSocket()
344
- .then((socket) => {
345
- socket.send(JSON.stringify({
346
- type: "castle_command",
347
- castleSdk: CASTLE_SDK_PROTOCOL,
348
- requestId,
349
- command,
350
- params,
351
- }));
352
- })
353
- .catch((error) => {
354
- clearTimeout(timeout);
355
- pendingCommands.delete(requestId);
356
- reject(error instanceof Error ? error : new Error(String(error)));
357
- });
358
- });
326
+ // Send an SDK command to the dev server. Its stream envelopes and its response
327
+ // go to `listener` as they arrive, and the listener is dropped after the
328
+ // response. transport.ts interprets them, so error reconstruction stays uniform
329
+ // across all three channels there. Waits for the socket to open so a command
330
+ // issued during startup isn't dropped; rejects if it never opens.
331
+ export async function sendLocalCommand(requestId, command, params, listener) {
332
+ localCommandListeners.set(requestId, listener);
333
+ try {
334
+ const socket = await waitForSocket();
335
+ // Cancelled or timed out while the socket was opening.
336
+ if (!localCommandListeners.has(requestId)) {
337
+ return;
338
+ }
339
+ socket.send(JSON.stringify({
340
+ type: "castle_command",
341
+ castleSdk: CASTLE_SDK_PROTOCOL,
342
+ requestId,
343
+ command,
344
+ params,
345
+ }));
346
+ }
347
+ catch (error) {
348
+ localCommandListeners.delete(requestId);
349
+ throw error;
350
+ }
351
+ }
352
+ // Ask the dev server to stop a streaming command, and stop listening for it.
353
+ export function cancelLocalCommand(requestId) {
354
+ localCommandListeners.delete(requestId);
355
+ if (ws && ws.readyState === WebSocket.OPEN) {
356
+ ws.send(JSON.stringify({ type: "castle_command_cancel", castleSdk: CASTLE_SDK_PROTOCOL, requestId }));
357
+ }
358
+ }
359
+ // Stop listening for a command the deck has given up on.
360
+ export function releaseLocalCommand(requestId) {
361
+ localCommandListeners.delete(requestId);
359
362
  }
360
363
  function waitForSocket() {
361
364
  if (ws && ws.readyState === WebSocket.OPEN)
@@ -374,10 +377,15 @@ function waitForSocket() {
374
377
  }, 100);
375
378
  });
376
379
  }
377
- function resolveLocalCommand(msg) {
378
- const pending = pendingCommands.get(msg.requestId);
379
- if (pending)
380
- pending(msg);
380
+ function deliverLocalCommand(msg) {
381
+ const listener = localCommandListeners.get(msg.requestId);
382
+ if (!listener) {
383
+ return;
384
+ }
385
+ if (!("stream" in msg)) {
386
+ localCommandListeners.delete(msg.requestId);
387
+ }
388
+ listener(msg);
381
389
  }
382
390
  function resolveLocalRequest(msg) {
383
391
  if (!msg.requestId)
@@ -919,7 +927,10 @@ function handleLocalMessage(msg) {
919
927
  resolveLocalRequest(msg);
920
928
  }
921
929
  else if (msg.type === "castle_command_response") {
922
- resolveLocalCommand(msg);
930
+ deliverLocalCommand(msg);
931
+ }
932
+ else if (msg.type === "castle_command_stream") {
933
+ deliverLocalCommand(msg);
923
934
  }
924
935
  }
925
936
  // Files-changed listeners, registered by consumers (the kit engine, editors).