@spellkave/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +155 -2
  3. package/package.json +63 -4
  4. package/src/binding_rows.ts +186 -0
  5. package/src/connection.ts +964 -0
  6. package/src/core/actor.ts +62 -0
  7. package/src/core/actor_control.ts +193 -0
  8. package/src/core/actor_control_query_methods.ts +101 -0
  9. package/src/core/actor_control_reaction_methods.ts +79 -0
  10. package/src/core/actor_control_sense_methods.ts +81 -0
  11. package/src/core/actor_control_source.ts +57 -0
  12. package/src/core/actor_session_methods.ts +226 -0
  13. package/src/core/binding_drift.ts +301 -0
  14. package/src/core/credential.ts +259 -0
  15. package/src/core/driver_control.ts +54 -0
  16. package/src/core/effective_environment_state.ts +71 -0
  17. package/src/core/factored_manipulation_attempt.ts +158 -0
  18. package/src/core/ids.ts +60 -0
  19. package/src/core/interaction/canonical.ts +15 -0
  20. package/src/core/interaction/fingerprint.ts +118 -0
  21. package/src/core/interaction/index.ts +31 -0
  22. package/src/core/interaction/intent.ts +284 -0
  23. package/src/core/interaction/outcome.ts +67 -0
  24. package/src/core/interaction/rejection_ledger.ts +108 -0
  25. package/src/core/kernel_contract.generated.ts +10 -0
  26. package/src/core/log.ts +23 -0
  27. package/src/core/movement.ts +111 -0
  28. package/src/core/node-io.ts +208 -0
  29. package/src/core/paths.ts +220 -0
  30. package/src/core/profile.ts +270 -0
  31. package/src/core/profiles.ts +9 -0
  32. package/src/core/provenance_buffer.ts +102 -0
  33. package/src/core/readers/_helpers.ts +273 -0
  34. package/src/core/readers/action_description.ts +17 -0
  35. package/src/core/readers/action_economy_events.ts +149 -0
  36. package/src/core/readers/actor_body_swaps.ts +62 -0
  37. package/src/core/readers/actor_snapshot.ts +197 -0
  38. package/src/core/readers/actor_states.ts +163 -0
  39. package/src/core/readers/actors_and_bodies.ts +179 -0
  40. package/src/core/readers/affordance_cue.ts +59 -0
  41. package/src/core/readers/affordance_defaults.ts +158 -0
  42. package/src/core/readers/affordance_group_membership.ts +67 -0
  43. package/src/core/readers/affordance_input.ts +129 -0
  44. package/src/core/readers/affordance_reference.ts +41 -0
  45. package/src/core/readers/apply_consequences.ts +54 -0
  46. package/src/core/readers/audience_trace_presentation.ts +62 -0
  47. package/src/core/readers/bounded_collection.ts +29 -0
  48. package/src/core/readers/bundle_definitions.ts +74 -0
  49. package/src/core/readers/bundle_entities.ts +62 -0
  50. package/src/core/readers/co_location.ts +71 -0
  51. package/src/core/readers/combat_session.ts +124 -0
  52. package/src/core/readers/combat_session_active.ts +44 -0
  53. package/src/core/readers/combat_session_feedback.ts +37 -0
  54. package/src/core/readers/combat_session_grid.ts +117 -0
  55. package/src/core/readers/combat_session_roster.ts +98 -0
  56. package/src/core/readers/combat_session_types.ts +51 -0
  57. package/src/core/readers/condition_deltas.ts +53 -0
  58. package/src/core/readers/container_contents.ts +92 -0
  59. package/src/core/readers/dialogue_guide.ts +99 -0
  60. package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
  61. package/src/core/readers/driver_control.ts +64 -0
  62. package/src/core/readers/entity_art.ts +219 -0
  63. package/src/core/readers/entity_containment.ts +119 -0
  64. package/src/core/readers/equipment.ts +99 -0
  65. package/src/core/readers/intervention_windows.ts +136 -0
  66. package/src/core/readers/inventory_query.ts +145 -0
  67. package/src/core/readers/item_detail.ts +198 -0
  68. package/src/core/readers/location_snapshot.ts +216 -0
  69. package/src/core/readers/manifest_apply_provenance.ts +32 -0
  70. package/src/core/readers/manifest_export.ts +81 -0
  71. package/src/core/readers/manipulation_context.ts +475 -0
  72. package/src/core/readers/map_layers.ts +49 -0
  73. package/src/core/readers/metadata_rows.ts +56 -0
  74. package/src/core/readers/object_state.ts +124 -0
  75. package/src/core/readers/observer_knowledge.ts +41 -0
  76. package/src/core/readers/observer_place_knowledge.ts +37 -0
  77. package/src/core/readers/observer_trace_knowledge.ts +45 -0
  78. package/src/core/readers/outcome_template.ts +41 -0
  79. package/src/core/readers/place_topology.ts +109 -0
  80. package/src/core/readers/reaction_options.ts +156 -0
  81. package/src/core/readers/resource_deltas.ts +47 -0
  82. package/src/core/readers/scene.ts +275 -0
  83. package/src/core/readers/seats.ts +33 -0
  84. package/src/core/readers/self.ts +245 -0
  85. package/src/core/readers/self_capabilities.ts +159 -0
  86. package/src/core/readers/self_economy.ts +101 -0
  87. package/src/core/readers/self_economy_budget.ts +93 -0
  88. package/src/core/readers/self_evaluations.ts +128 -0
  89. package/src/core/readers/self_identity.ts +104 -0
  90. package/src/core/readers/sense_context.ts +112 -0
  91. package/src/core/readers/session.ts +207 -0
  92. package/src/core/readers/session_detail.ts +211 -0
  93. package/src/core/readers/session_status.ts +68 -0
  94. package/src/core/readers/spatial_environment_state.ts +74 -0
  95. package/src/core/readers/spatial_niche_attachments.ts +28 -0
  96. package/src/core/readers/substrate_definitions.ts +27 -0
  97. package/src/core/readers/suggest_next_action.ts +72 -0
  98. package/src/core/readers/surface_membership.ts +78 -0
  99. package/src/core/readers/tag_reads.ts +54 -0
  100. package/src/core/readers/trace_query.ts +120 -0
  101. package/src/core/readers/trace_response.ts +80 -0
  102. package/src/core/readers/traces.ts +124 -0
  103. package/src/core/readers/travel_session.ts +88 -0
  104. package/src/core/readers/turn_state.ts +34 -0
  105. package/src/core/readers/world_events.ts +43 -0
  106. package/src/core/readers/world_status.ts +63 -0
  107. package/src/core/reducers/manipulation_args.ts +239 -0
  108. package/src/core/reducers/manipulation_receipt.ts +66 -0
  109. package/src/core/reducers/r_actor_wake_up.ts +32 -0
  110. package/src/core/reducers/r_inscribe_trace.ts +109 -0
  111. package/src/core/reducers/r_manipulate.ts +163 -0
  112. package/src/core/reducers/r_move.ts +155 -0
  113. package/src/core/reducers/r_react.ts +143 -0
  114. package/src/core/reducers/r_release_claim.ts +81 -0
  115. package/src/core/reducers/r_sense.ts +84 -0
  116. package/src/core/reducers/r_session_close.ts +130 -0
  117. package/src/core/reducers/r_session_move.ts +116 -0
  118. package/src/core/reducers/r_session_open.ts +91 -0
  119. package/src/core/reducers/session_lookup.ts +64 -0
  120. package/src/core/reducers/tick.ts +65 -0
  121. package/src/core/reducers/trace_lookup.ts +29 -0
  122. package/src/core/reducers/transport.ts +84 -0
  123. package/src/core/resolve.ts +228 -0
  124. package/src/core/shape_telemetry.ts +146 -0
  125. package/src/core/snapshot_rows.ts +109 -0
  126. package/src/core/tick_cadence.ts +61 -0
  127. package/src/core/types.ts +501 -0
  128. package/src/core/watch_provenance.ts +113 -0
  129. package/src/core/world-contract/classify.ts +38 -0
  130. package/src/core/world-contract/index.ts +12 -0
  131. package/src/core/world-contract/normalise.ts +574 -0
  132. package/src/core/world-contract/runtime.ts +144 -0
  133. package/src/core/world-contract/served.ts +173 -0
  134. package/src/core/world-contract/strict-reducers.ts +14 -0
  135. package/src/core/world-contract/typetext.ts +94 -0
  136. package/src/core/world_time.ts +22 -0
  137. package/src/index.ts +262 -0
  138. package/src/manifest-apply.ts +497 -0
  139. package/src/provenance.ts +568 -0
  140. package/src/reader-manifest.ts +338 -0
  141. package/src/readers.ts +392 -0
  142. package/src/replay.ts +515 -0
  143. package/src/watch-buffer.ts +438 -0
  144. package/src/world-events/builder.ts +1042 -0
@@ -0,0 +1,259 @@
1
+ // Credential reference resolution.
2
+ //
3
+ // Mirrors the Rust `CredentialRef` enum in `client/src/credential.rs` and
4
+ // the documented `cloud`/maincloud token-fallback semantics from
5
+ // `openspec/specs/cli-persona-profiles/spec.md`.
6
+ //
7
+ // Variants supported:
8
+ // * { kind: "env_var", name } — read non-empty env var
9
+ // * { kind: "file", path } — read first non-empty line of file
10
+ // * { kind: "inline", value } — literal value (local-dev only)
11
+ // * undefined credential + cloud preset → resolve via `spacetime login` token
12
+ //
13
+ // Failure modes are uniform: missing, unreadable, or empty source → throw.
14
+ //
15
+ // Browser-reachable through the `@spellkave/sdk` barrel: NO top-level `node:*`
16
+ // imports. File reads and the `home` dir come in through injected readers; Node
17
+ // hosts get the `node:fs`/`node:os`-backed defaults from `@spellkave/sdk/node`
18
+ // (`node-io.ts`). `smol-toml` and `Buffer` are pure/runtime-shimmed, so they
19
+ // stay.
20
+
21
+ import { parse as parseToml } from "smol-toml";
22
+
23
+ /**
24
+ * Pure POSIX-style path join. The credential/token files this module addresses
25
+ * live under `$HOME` with forward-slash segments; a segment join + slash
26
+ * collapse matches `node:path`'s `join` without dragging it into the browser
27
+ * bundle.
28
+ */
29
+ function joinPath(...segments: string[]): string {
30
+ return segments
31
+ .filter((s) => s.length > 0)
32
+ .join("/")
33
+ .replace(/\/{2,}/g, "/");
34
+ }
35
+
36
+ export type CredentialRef =
37
+ | { kind: "env_var"; name: string }
38
+ | { kind: "file"; path: string }
39
+ | { kind: "inline"; value: string };
40
+
41
+ /**
42
+ * Static well-formedness check that does NOT touch env or fs (except File,
43
+ * which we leave to `resolveCredential`). Mirrors the Rust `validate()`.
44
+ */
45
+ export type CredentialValidation =
46
+ | { kind: "ok" }
47
+ | { kind: "empty" }
48
+ | { kind: "missing_path"; path: string };
49
+
50
+ export function validateCredentialRef(ref: CredentialRef): CredentialValidation {
51
+ switch (ref.kind) {
52
+ case "env_var":
53
+ return ref.name.length === 0 ? { kind: "empty" } : { kind: "ok" };
54
+ case "inline":
55
+ return ref.value.length === 0 ? { kind: "empty" } : { kind: "ok" };
56
+ case "file":
57
+ return ref.path.length === 0 ? { kind: "empty" } : { kind: "ok" };
58
+ }
59
+ }
60
+
61
+ export interface CredentialResolveEnv {
62
+ env?: NodeJS.ProcessEnv;
63
+ /** Override fs reader; tests inject. */
64
+ readFile?: (path: string) => string;
65
+ /** Override `spacetime login` token reader; tests inject. */
66
+ readSpacetimeToken?: () => string | undefined;
67
+ /** Optional home dir override for the default token reader. */
68
+ home?: string;
69
+ }
70
+
71
+ export interface SpacetimeConfigTokenResolveEnv {
72
+ env?: NodeJS.ProcessEnv;
73
+ /** Override fs reader; tests inject. */
74
+ readFile?: (path: string) => string;
75
+ /** Override binary fs reader; tests inject. */
76
+ readFileBytes?: (path: string) => Uint8Array;
77
+ /** Optional home dir override for the Rust SDK credential-file reader. */
78
+ home?: string;
79
+ }
80
+
81
+ /**
82
+ * Resolve a credential reference to its raw secret string. Fails closed on
83
+ * missing, unreadable, or empty sources. The caller must NEVER catch and
84
+ * fall back silently — that would defeat the contract.
85
+ */
86
+ export function resolveCredential(ref: CredentialRef, opts: CredentialResolveEnv = {}): string {
87
+ switch (ref.kind) {
88
+ case "env_var": {
89
+ if (ref.name.length === 0) {
90
+ throw new Error("credential env_var.name is empty");
91
+ }
92
+ const env = opts.env ?? process.env;
93
+ const v = env[ref.name];
94
+ if (v === undefined || v.length === 0) {
95
+ throw new Error(`credential env_var '${ref.name}' is missing or empty`);
96
+ }
97
+ return v;
98
+ }
99
+ case "file": {
100
+ if (ref.path.length === 0) {
101
+ throw new Error("credential file.path is empty");
102
+ }
103
+ const reader = opts.readFile;
104
+ if (reader === undefined) {
105
+ throw new Error(
106
+ "credential file resolution requires opts.readFile; use @spellkave/sdk/node for the Node-bound default",
107
+ );
108
+ }
109
+ let raw: string;
110
+ try {
111
+ raw = reader(ref.path);
112
+ } catch (err) {
113
+ const msg = err instanceof Error ? err.message : String(err);
114
+ throw new Error(`credential file '${ref.path}' is unreadable: ${msg}`);
115
+ }
116
+ const trimmed = raw.split(/\r?\n/, 1)[0]?.trim() ?? "";
117
+ if (trimmed.length === 0) {
118
+ throw new Error(`credential file '${ref.path}' is empty`);
119
+ }
120
+ return trimmed;
121
+ }
122
+ case "inline": {
123
+ if (ref.value.length === 0) {
124
+ throw new Error("credential inline.value is empty");
125
+ }
126
+ return ref.value;
127
+ }
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Resolve identity for the documented `cloud`/maincloud profile preset where
133
+ * the profile carries NO `credential` field — read the host's
134
+ * `spacetime login` token instead. Fails closed when no token is present.
135
+ *
136
+ * The default reader prefers the real Spacetime CLI config at
137
+ * `~/.config/spacetime/cli.toml` (top-level `spacetimedb_token` key — the
138
+ * same store written by `spacetime login`), then falls back to legacy bare
139
+ * `token` files for older installs. Callers can override via
140
+ * `opts.readSpacetimeToken` for tests.
141
+ */
142
+ export function resolveSpacetimeLoginToken(opts: CredentialResolveEnv = {}): string {
143
+ const reader = opts.readSpacetimeToken ?? (() => defaultReadSpacetimeToken(opts));
144
+ const token = reader();
145
+ if (token === undefined || token.length === 0) {
146
+ throw new Error(
147
+ "no `spacetime login` token found; run `spacetime login` or set a credential reference on the profile",
148
+ );
149
+ }
150
+ return token;
151
+ }
152
+
153
+ /**
154
+ * Resolve the per-worktree SpacetimeDB token from SPACETIME_CONFIG_PATH.
155
+ *
156
+ * Unlike `resolveSpacetimeLoginToken`, this is best-effort: local harnesses use
157
+ * it only when they explicitly opt into token reuse, and callers that still need
158
+ * anonymous connections can ignore the undefined result.
159
+ */
160
+ export function resolveSpacetimeConfigPathToken(
161
+ opts: SpacetimeConfigTokenResolveEnv = {},
162
+ ): string | undefined {
163
+ const env = opts.env ?? process.env;
164
+ const configPath = env.SPACETIME_CONFIG_PATH;
165
+ if (configPath === undefined || configPath.length === 0) return undefined;
166
+
167
+ const reader = opts.readFile;
168
+ if (reader === undefined) {
169
+ throw new Error(
170
+ "resolveSpacetimeConfigPathToken requires opts.readFile; use @spellkave/sdk/node for the Node-bound default",
171
+ );
172
+ }
173
+ try {
174
+ const parsed = parseToml(reader(configPath)) as Record<string, unknown>;
175
+ const token = parsed.spacetimedb_token;
176
+ return typeof token === "string" && token.length > 0 ? token : undefined;
177
+ } catch {
178
+ return undefined;
179
+ }
180
+ }
181
+
182
+ export function spacetimeClientCredentialKey(url: string, db: string): string {
183
+ let key = "spellkave-";
184
+ for (const ch of `${url}-${db}`) {
185
+ key += /[A-Za-z0-9_-]/.test(ch) ? ch : "_";
186
+ }
187
+ return key;
188
+ }
189
+
190
+ /**
191
+ * Resolve the token saved by the Rust `spacetimedb_sdk::credentials::File`
192
+ * store used by `spellkave manifest apply`. Local walkthrough sweeps seed via
193
+ * that Rust client, so this is the authoritative token for `$sender`-bound
194
+ * actors in the freshly seeded world.
195
+ */
196
+ export function resolveSpacetimeClientCredentialToken(
197
+ url: string,
198
+ db: string,
199
+ opts: SpacetimeConfigTokenResolveEnv = {},
200
+ ): string | undefined {
201
+ const home = opts.home;
202
+ const reader = opts.readFileBytes;
203
+ if (home === undefined || reader === undefined) {
204
+ throw new Error(
205
+ "resolveSpacetimeClientCredentialToken requires opts.home + opts.readFileBytes; use @spellkave/sdk/node for the Node-bound defaults",
206
+ );
207
+ }
208
+ const path = joinPath(
209
+ home,
210
+ ".spacetimedb_client_credentials",
211
+ spacetimeClientCredentialKey(url, db),
212
+ );
213
+ try {
214
+ return decodeRustSdkCredentialToken(reader(path));
215
+ } catch {
216
+ return undefined;
217
+ }
218
+ }
219
+
220
+ export function decodeRustSdkCredentialToken(bytes: Uint8Array): string | undefined {
221
+ if (bytes.length < 4) return undefined;
222
+ // biome-ignore lint/style/noNonNullAssertion: pre-existing debt from #1368 biome onboarding, tracked in #1455
223
+ const len = bytes[0]! | (bytes[1]! << 8) | (bytes[2]! << 16) | (bytes[3]! << 24);
224
+ if (len <= 0 || bytes.length < 4 + len) return undefined;
225
+ return Buffer.from(bytes.subarray(4, 4 + len)).toString("utf8");
226
+ }
227
+
228
+ function defaultReadSpacetimeToken(opts: CredentialResolveEnv): string | undefined {
229
+ const home = opts.home;
230
+ const reader = opts.readFile;
231
+ if (home === undefined || reader === undefined) {
232
+ throw new Error(
233
+ "resolveSpacetimeLoginToken's default reader requires opts.home + opts.readFile; use @spellkave/sdk/node for the Node-bound defaults",
234
+ );
235
+ }
236
+ const cliToml = joinPath(home, ".config", "spacetime", "cli.toml");
237
+ try {
238
+ const raw = reader(cliToml);
239
+ const parsed = parseToml(raw) as Record<string, unknown>;
240
+ const tok = parsed.spacetimedb_token;
241
+ if (typeof tok === "string" && tok.trim().length > 0) return tok.trim();
242
+ } catch {
243
+ // fall through to legacy candidates
244
+ }
245
+ const legacy = [
246
+ joinPath(home, ".config", "spacetime", "token"),
247
+ joinPath(home, "Library", "Application Support", "SpacetimeDB", "token"),
248
+ ];
249
+ for (const path of legacy) {
250
+ try {
251
+ const raw = reader(path);
252
+ const trimmed = raw.trim();
253
+ if (trimmed.length > 0) return trimmed;
254
+ } catch {
255
+ // try next
256
+ }
257
+ }
258
+ return undefined;
259
+ }
@@ -0,0 +1,54 @@
1
+ import type { DbConnection } from "@spellkave/bindings";
2
+ export type DriverToken = NonNullable<
3
+ Parameters<DbConnection["reducers"]["rMove"]>[0]["driverToken"]
4
+ >;
5
+
6
+ const DRIVER_REDUCERS = [
7
+ "rAdvanceTurn",
8
+ "mtAdvanceCompoundIntent",
9
+ "commitPendingResolution",
10
+ "arbitrationRequestCreate",
11
+ "arbitrationAnswerSubmit",
12
+ "rMove",
13
+ "rManipulate",
14
+ "rSense",
15
+ "rInscribeTrace",
16
+ "rReact",
17
+ "rReleaseClaim",
18
+ "rActorWakeUp",
19
+ "rSessionClose",
20
+ "rSessionMove",
21
+ ] as const;
22
+
23
+ /** Capture once with the decision. Dispatch never reads the current generation. */
24
+ export function freezeDriverReducers<T extends object>(reducers: T, observed?: DriverToken): T {
25
+ if (observed === undefined) return reducers;
26
+ const token = Object.freeze({ ...observed });
27
+ const result = { ...reducers } as Record<string, unknown>;
28
+ for (const name of DRIVER_REDUCERS) {
29
+ const reducer = (reducers as Record<string, unknown>)[name];
30
+ if (typeof reducer !== "function") continue;
31
+ result[name] = (args: Record<string, unknown>) => reducer({ ...args, driverToken: token });
32
+ }
33
+ const batch = (reducers as Record<string, unknown>).rAdvanceTurns;
34
+ if (typeof batch === "function")
35
+ result.rAdvanceTurns = (args: Record<string, unknown>) =>
36
+ batch({ ...args, driverTokens: [token] });
37
+ const open = (reducers as Record<string, unknown>).rSessionOpen;
38
+ if (typeof open === "function")
39
+ result.rSessionOpen = (args: Record<string, unknown>) =>
40
+ open({ ...args, driverTokens: [token] });
41
+ return result as T;
42
+ }
43
+
44
+ export type ControlReducerPort = Pick<
45
+ DbConnection["reducers"],
46
+ | "rOfferControl"
47
+ | "rWithdrawControl"
48
+ | "rTakeNpcControl"
49
+ | "rReturnNpcControl"
50
+ | "rPrepareSteeredActor"
51
+ | "rMove"
52
+ | "rManipulate"
53
+ | "rSense"
54
+ >;
@@ -0,0 +1,71 @@
1
+ /** Minimal projected columns used for identity and ordering; values stay opaque. */
2
+ export interface EnvironmentStateCandidate {
3
+ bundleId?: string;
4
+ stateId?: string;
5
+ stateRowId?: bigint;
6
+ updatedTick?: bigint;
7
+ targetKind?: string;
8
+ targetRef?: unknown;
9
+ placeNodeId?: string;
10
+ placeEdgeId?: bigint | string;
11
+ locationDefId?: string;
12
+ cellRes10?: bigint;
13
+ cellRes7?: bigint;
14
+ cellRes4?: bigint;
15
+ substrateId?: string;
16
+ }
17
+
18
+ /** Projection/ancestor columns describe locality, not the logical target. */
19
+ function targetIdentity(row: EnvironmentStateCandidate): unknown {
20
+ const kind = row.targetKind ?? "";
21
+ if ((!kind || kind === "place_node") && row.placeNodeId) return ["node", row.placeNodeId];
22
+ if ((!kind || kind === "place_edge") && row.placeEdgeId && String(row.placeEdgeId) !== "0")
23
+ return ["edge", String(row.placeEdgeId)];
24
+ if ((!kind || kind === "location") && row.locationDefId) return ["location", row.locationDefId];
25
+ if (row.targetRef !== undefined) return ["reference", canonicalReference(row.targetRef)];
26
+ return [
27
+ kind,
28
+ String(row.cellRes10 ?? 0),
29
+ String(row.cellRes7 ?? 0),
30
+ String(row.cellRes4 ?? 0),
31
+ row.substrateId ?? "",
32
+ ];
33
+ }
34
+
35
+ function canonicalReference(value: unknown): unknown {
36
+ if (typeof value === "bigint" || typeof value === "number") return String(value);
37
+ if (Array.isArray(value)) return value.map(canonicalReference);
38
+ if (value && typeof value === "object")
39
+ return Object.entries(value)
40
+ .sort(([a], [b]) => a.localeCompare(b))
41
+ .map(([key, field]) => [key, canonicalReference(field)]);
42
+ return value;
43
+ }
44
+
45
+ /** Resolve only the rows already admitted to this caller; never expire values. */
46
+ export function resolveEffectiveSpatialEnvironmentStates<T extends EnvironmentStateCandidate>(
47
+ input: Iterable<T>,
48
+ ): T[] {
49
+ const effective = new Map<string, T>();
50
+ const rank = (row: T): [number, bigint, bigint] => [
51
+ row.bundleId === "" ? 1 : 0,
52
+ BigInt(row.updatedTick ?? 0),
53
+ BigInt(row.stateRowId ?? 0),
54
+ ];
55
+ for (const row of input) {
56
+ const key = JSON.stringify([row.stateId ?? "", targetIdentity(row)]);
57
+ const prior = effective.get(key);
58
+ if (!prior) {
59
+ effective.set(key, row);
60
+ continue;
61
+ }
62
+ const left = rank(row),
63
+ right = rank(prior);
64
+ if (
65
+ left[0] > right[0] ||
66
+ (left[0] === right[0] && (left[1] > right[1] || (left[1] === right[1] && left[2] > right[2])))
67
+ )
68
+ effective.set(key, row);
69
+ }
70
+ return [...effective.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, row]) => row);
71
+ }
@@ -0,0 +1,158 @@
1
+ // ADR-0139 client-side lazy composition for one ordinary manipulation attempt.
2
+ //
3
+ // This is deliberately a transport and disclosure policy, not an eligibility
4
+ // evaluator. It accepts one open authored action id and one already-disclosed
5
+ // target, then leaves template selection, authority, predicates, budget, and
6
+ // consequences to r_manipulate at dispatch time.
7
+
8
+ import type { ManipulationContext } from "./readers/manipulation_context";
9
+ import { manipulationArgsFromJson } from "./reducers/manipulation_args";
10
+ import { targetRefFromString, targetRefToString } from "./reducers/transport";
11
+
12
+ export interface FactoredManipulationAttemptInput {
13
+ /** An authored action id from the caller's ready manipulation context. */
14
+ action_id: string;
15
+ /** A typed target string from the caller's disclosed target facts. */
16
+ target_ref: string;
17
+ /** Existing JSON arguments, preserved except for a selected mpc token. */
18
+ args_json?: string;
19
+ /** Select one disclosed mpc token when an action has more than one. */
20
+ participant_context?: string;
21
+ /** The occurrence and source this response answers (ADR-0142 D-3), when
22
+ * `action_id` is prompt-bound. The caller picks it from `context.prompts`
23
+ * (ADR-0142 D-6/D-7: "clients rank; nothing becomes eligible client-side"
24
+ * — this composer never infers it). Forwarded 1:1 under `args_json`'s
25
+ * `semantic_context` key, exactly as the server reads it. */
26
+ semantic_context?: { source_ref: string; occurrence_id: string };
27
+ }
28
+
29
+ /** One lazy candidate. `not_assessed` means only that its transport is shaped;
30
+ * it makes no claim that the server will admit the attempt. */
31
+ export interface FactoredManipulationAttempt {
32
+ status: "not_assessed";
33
+ action_id: string;
34
+ target_ref: string;
35
+ args_json: string;
36
+ participant_context?: string;
37
+ semantic_context?: { source_ref: string; occurrence_id: string };
38
+ }
39
+
40
+ export type FactoredManipulationAttemptResult =
41
+ | FactoredManipulationAttempt
42
+ | { status: "context_unavailable" }
43
+ | { status: "unknown_action"; action_id: string }
44
+ | { status: "invalid_target_ref"; target_ref: string }
45
+ | { status: "undisclosed_target"; target_ref: string }
46
+ | { status: "malformed_args"; reason: string }
47
+ | { status: "participant_context_conflict" }
48
+ | { status: "unknown_participant_context"; participant_context: string }
49
+ | { status: "participant_context_required"; action_id: string; choices: string[] };
50
+
51
+ /**
52
+ * Composes exactly one attempt from a ready factored context. It never reads a
53
+ * database, calls an eligibility reader, or constructs an action × target
54
+ * list. A caller may use the returned value to invoke the existing
55
+ * r_manipulate transport once.
56
+ */
57
+ export function composeFactoredManipulationAttempt(
58
+ context: ManipulationContext,
59
+ input: FactoredManipulationAttemptInput,
60
+ ): FactoredManipulationAttemptResult {
61
+ if (context.status !== "ready") return { status: "context_unavailable" };
62
+ const actionId = input.action_id.trim();
63
+ if (!context.actions.some((action) => action.action_id === actionId)) {
64
+ return { status: "unknown_action", action_id: input.action_id };
65
+ }
66
+
67
+ let targetRef: string;
68
+ try {
69
+ targetRef = targetRefToString(targetRefFromString(input.target_ref));
70
+ } catch {
71
+ return { status: "invalid_target_ref", target_ref: input.target_ref };
72
+ }
73
+ if (!context.targets.some((target) => target.target_ref === targetRef)) {
74
+ return { status: "undisclosed_target", target_ref: targetRef };
75
+ }
76
+
77
+ const args = parseArgs(input.args_json ?? "{}");
78
+ if ("reason" in args) return { status: "malformed_args", reason: args.reason };
79
+ const rawContext = stringField(args.value, "participant_context", "participantContext");
80
+ const requestedContext = input.participant_context?.trim() || rawContext;
81
+ if (
82
+ input.participant_context !== undefined &&
83
+ rawContext !== undefined &&
84
+ input.participant_context.trim() !== rawContext
85
+ ) {
86
+ return { status: "participant_context_conflict" };
87
+ }
88
+
89
+ const choices = context.participants.filter((candidate) => candidate.action_id === actionId);
90
+ let participantContext: string | undefined;
91
+ if (requestedContext !== undefined) {
92
+ if (!choices.some((choice) => choice.context_id === requestedContext)) {
93
+ return { status: "unknown_participant_context", participant_context: requestedContext };
94
+ }
95
+ participantContext = requestedContext;
96
+ } else if (choices.length === 1) {
97
+ participantContext = choices[0]?.context_id;
98
+ } else if (choices.length > 1) {
99
+ return {
100
+ status: "participant_context_required",
101
+ action_id: actionId,
102
+ choices: choices.map((choice) => choice.context_id),
103
+ };
104
+ }
105
+
106
+ if (participantContext !== undefined) {
107
+ delete args.value.expectedParticipants;
108
+ delete args.value.expected_participants;
109
+ delete args.value.participantContext;
110
+ delete args.value.participant_context;
111
+ args.value.participant_context = participantContext;
112
+ }
113
+ // ADR-0142 D-3 wire fold-in, the same shape `participant_context` above
114
+ // uses: an explicit caller-supplied `semantic_context` replaces whatever
115
+ // (if anything) `args_json` already carried under that key. This composer
116
+ // never derives it from `context.prompts` itself (D-7: "clients rank;
117
+ // nothing becomes eligible client-side").
118
+ if (input.semantic_context !== undefined) {
119
+ args.value.semantic_context = {
120
+ source_ref: input.semantic_context.source_ref,
121
+ occurrence_id: input.semantic_context.occurrence_id,
122
+ };
123
+ }
124
+ return {
125
+ status: "not_assessed",
126
+ action_id: actionId,
127
+ target_ref: targetRef,
128
+ args_json: JSON.stringify(args.value),
129
+ ...(participantContext === undefined ? {} : { participant_context: participantContext }),
130
+ ...(input.semantic_context === undefined ? {} : { semantic_context: input.semantic_context }),
131
+ };
132
+ }
133
+
134
+ function parseArgs(json: string): { value: Record<string, unknown> } | { reason: string } {
135
+ try {
136
+ const parsed = JSON.parse(json.trim() === "" ? "{}" : json) as unknown;
137
+ if (!isRecord(parsed)) return { reason: "manipulation args must be a JSON object" };
138
+ // Validate the wire fields with the same parser r_manipulate uses. The
139
+ // original object remains intact so forward-compatible authored fields
140
+ // are not erased by this generic composer.
141
+ manipulationArgsFromJson(JSON.stringify(parsed));
142
+ return { value: { ...parsed } };
143
+ } catch (error) {
144
+ return { reason: error instanceof Error ? error.message : "malformed manipulation args" };
145
+ }
146
+ }
147
+
148
+ function stringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {
149
+ for (const key of keys) {
150
+ const value = record[key];
151
+ if (value !== undefined && value !== null) return String(value);
152
+ }
153
+ return undefined;
154
+ }
155
+
156
+ function isRecord(value: unknown): value is Record<string, unknown> {
157
+ return typeof value === "object" && value !== null && !Array.isArray(value);
158
+ }
@@ -0,0 +1,60 @@
1
+ // Distinct id meanings the SDK historically collapsed onto one `string`.
2
+ //
3
+ // A brand on a return type enumerates nothing: these types are still
4
+ // assignable TO `string`. The compiler only speaks when a parameter is branded.
5
+
6
+ declare const ACTOR_ID: unique symbol;
7
+ declare const ENTITY_REF: unique symbol;
8
+ declare const ENTITY_ID: unique symbol;
9
+
10
+ /**
11
+ * The steering principal (`Actor.actor_id`).
12
+ *
13
+ * Produced by `readActorIdentityBindings`, `readActorPrincipals`, `readSeats`,
14
+ * and `readActorBodySwapEvents` (minted via {@link asActorId}). Consumed at
15
+ * `packages/spellkave-srd-cc/scripts/stage-adventure.ts:166` as the first
16
+ * positional argument to `r_bind_actor_identity`.
17
+ */
18
+ export type ActorId = string & { readonly [ACTOR_ID]: true };
19
+
20
+ /**
21
+ * What an author or a tool caller writes: a bare numeric id (`42`),
22
+ * `entity:42`, `item:42`, or a manifest key (`core/player`).
23
+ */
24
+ export type EntityRef = string & { readonly [ENTITY_REF]: true };
25
+
26
+ /**
27
+ * A resolved body entity (`Actor.current_body`, `actor_spatial_location.entity_id`).
28
+ * A subtype of {@link EntityRef}: a resolved id is itself a valid ref.
29
+ */
30
+ export type EntityId = EntityRef & { readonly [ENTITY_ID]: true };
31
+
32
+ type Assert<T extends true> = T;
33
+ type _EntityIdExtendsRef = Assert<EntityId extends EntityRef ? true : false>;
34
+ type _RefIsNotId = Assert<EntityRef extends EntityId ? false : true>;
35
+
36
+ /**
37
+ * Brand an untrusted string as an {@link EntityRef} as it enters the SDK
38
+ * (profile values, tool parameters, test fixtures). This is the only door a
39
+ * plain `string` may pass through to become a ref — not scattered `as` casts
40
+ * at every `resolveEntityId` call.
41
+ */
42
+ export function asEntityRef(value: string): EntityRef {
43
+ return value as EntityRef;
44
+ }
45
+
46
+ /**
47
+ * Mint a resolved {@link EntityId} after a numeric parse (e.g. `resolveActor`).
48
+ * Not an entry door for untrusted refs — use {@link asEntityRef} for those.
49
+ */
50
+ export function asEntityId(value: string): EntityId {
51
+ return value as EntityId;
52
+ }
53
+
54
+ /**
55
+ * Mint a steering principal {@link ActorId}. The door a principal enters the
56
+ * SDK through (identity bindings, principals, seats, body-swap events).
57
+ */
58
+ export function asActorId(value: string): ActorId {
59
+ return value as ActorId;
60
+ }
@@ -0,0 +1,15 @@
1
+ // Deterministic key-sorted JSON shaping, shared by `attemptFingerprint` and
2
+ // `inputValuesToText`. Object key order carries no author meaning and must
3
+ // not affect identity; array order does carry meaning (it is a sequence, not
4
+ // a set) and is always preserved.
5
+
6
+ export function sortKeysDeep(value: unknown): unknown {
7
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
8
+ if (value !== null && typeof value === "object") {
9
+ const record = value as Record<string, unknown>;
10
+ const sorted: Record<string, unknown> = {};
11
+ for (const key of Object.keys(record).sort()) sorted[key] = sortKeysDeep(record[key]);
12
+ return sorted;
13
+ }
14
+ return value;
15
+ }