@spellkave/sdk 0.0.0-bootstrap

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 +156 -0
  3. package/package.json +65 -0
  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,62 @@
1
+ // Actor body-entity resolution from `profile.identity.in_world_self`.
2
+ //
3
+ // The shared SDK accepts an exact runtime `entity_id` or an exact authored
4
+ // manifest alias. It never performs nickname, role, or fuzzy lookup.
5
+ //
6
+ // World-model note: the server has no monolithic `actor` table — actors are
7
+ // component-shaped. For the first-slice movement loop, an actor exists in
8
+ // gameplay terms iff it has a row in `actor_spatial_location` (which both
9
+ // asserts presence and pins the current place node, since `r_move` requires
10
+ // a from-node). If no such row matches, we fail closed.
11
+ //
12
+ // `LiveActorReader` is a one-method seam so the live SpacetimeDB SDK and
13
+ // unit tests can both feed it.
14
+
15
+ import { asEntityId, type EntityId } from "./ids";
16
+ import { parseEntityIdRef } from "./readers/_helpers";
17
+
18
+ export interface ActorSpatialLocationRow {
19
+ entity_id: EntityId;
20
+ aliases?: string[];
21
+ /** Current place node id. The generated table makes this non-nullable, but
22
+ * we accept undefined/empty defensively (e.g. mid-tick where a row could
23
+ * carry an empty string until the next reducer settles). */
24
+ node_id?: string;
25
+ }
26
+
27
+ export interface LiveActorReader {
28
+ /** All `actor_spatial_location` rows currently in the SDK cache. */
29
+ locations(): Iterable<ActorSpatialLocationRow>;
30
+ }
31
+
32
+ export interface ResolvedActor {
33
+ /** Body entity id from `actor_spatial_location.entity_id` — not `Actor.actor_id`. */
34
+ body_entity_id: EntityId;
35
+ /** Always defined for a successfully resolved actor — `r_move` requires
36
+ * a from-node, and presence in `actor_spatial_location` is what defines
37
+ * "exists" for this slice. May still be reported as undefined to callers
38
+ * if the row's `node_id` is empty, in which case movement validation
39
+ * fails closed at the next layer. */
40
+ current_node_id: string | undefined;
41
+ }
42
+
43
+ /**
44
+ * Resolve the active actor by looking up the configured `in_world_self` in
45
+ * the live `actor_spatial_location` cache. Throws when no row matches —
46
+ * never invents a fallback actor, never substitutes a sibling, never calls
47
+ * an authoring/placement reducer.
48
+ */
49
+ export function resolveActor(inWorldSelf: string, reader: LiveActorReader): ResolvedActor {
50
+ if (inWorldSelf.trim().length === 0) {
51
+ throw new Error("profile identity.in_world_self is empty");
52
+ }
53
+ const wanted = parseEntityIdRef(inWorldSelf);
54
+ for (const loc of reader.locations()) {
55
+ const entityId = parseEntityIdRef(loc.entity_id);
56
+ if (entityId !== undefined && (entityId === wanted || loc.aliases?.includes(inWorldSelf))) {
57
+ const nodeId = loc.node_id && loc.node_id.length > 0 ? loc.node_id : undefined;
58
+ return { body_entity_id: asEntityId(String(entityId)), current_node_id: nodeId };
59
+ }
60
+ }
61
+ throw new Error(`actor '${inWorldSelf}' not found in live actor_spatial_location — fail closed`);
62
+ }
@@ -0,0 +1,193 @@
1
+ import type { SnapshotDb, SpellkaveSession } from "../connection";
2
+ import { resolveActor } from "./actor";
3
+ import { createActorClientQueryMethods } from "./actor_control_query_methods";
4
+ import { createActorClientReactionMethods } from "./actor_control_reaction_methods";
5
+ import { createActorClientSenseMethods } from "./actor_control_sense_methods";
6
+ import { type ActorClientSource, actorReaders, toConnDb } from "./actor_control_source";
7
+ import { createActorSessionMethods } from "./actor_session_methods";
8
+ import { freezeDriverReducers } from "./driver_control";
9
+ import { parseEntityIdRef } from "./readers/_helpers";
10
+ import { readActorIdentityBindings, readActorPrincipals } from "./readers/actors_and_bodies";
11
+ import { readWorldStatus } from "./readers/world_status";
12
+ import type { TickIntervalEstimator } from "./tick_cadence";
13
+
14
+ export type {
15
+ ActorClientReducers,
16
+ ActorClientSource,
17
+ RActorWakeUpFn,
18
+ RAdvanceTurnFn,
19
+ RInscribeTraceFn,
20
+ RManipulateFn,
21
+ RMoveFn,
22
+ RReactFn,
23
+ RReleaseClaimFn,
24
+ RSenseFn,
25
+ RSessionCloseFn,
26
+ RSessionMoveFn,
27
+ RSessionOpenFn,
28
+ } from "./actor_control_source";
29
+ export type {
30
+ ActorAttemptStatus,
31
+ ActorClient,
32
+ ActorClientOptions,
33
+ ActorManipulateRejected,
34
+ ActorManipulateResult,
35
+ ActorManipulateSuccess,
36
+ ActorManipulateUnobservedNoProvenance,
37
+ ActorManipulateUnobservedTimeout,
38
+ ActorMoveCall,
39
+ ActorMoveRejected,
40
+ ActorMoveResult,
41
+ ActorMoveSuccess,
42
+ ActorMoveUnobservedNoProvenance,
43
+ ActorMoveUnobservedTimeout,
44
+ ActorReactResult,
45
+ ActorReleaseClaimResult,
46
+ ActorSenseRejected,
47
+ ActorSenseResult,
48
+ ActorSenseSuccess,
49
+ ActorSenseUnobservedNoProvenance,
50
+ ActorSenseUnobservedTimeout,
51
+ ActorWakeUpResult,
52
+ AdjacentMove,
53
+ AdvanceTurnResult,
54
+ InscribeTraceResult,
55
+ SessionCloseResult,
56
+ SessionMoveResult,
57
+ SessionOpenResult,
58
+ VisibilityClass,
59
+ } from "./types";
60
+
61
+ import type { ActorClient, ActorClientOptions } from "./types";
62
+
63
+ /** Default bounded-observation timeout and snapshot-host fallback poll (`observeReducerAttempt`'s own
64
+ * shape, `provenance.ts`) — exported (sk-0m4.73) so a caller outside this
65
+ * module can reuse the SAME default a fresh `ActorClient` would compute,
66
+ * instead of hand-rolling a second hard-coded latency. */
67
+ export const DEFAULT_OBSERVATION_TIMEOUT_MS = 2_000;
68
+ export const DEFAULT_OBSERVATION_POLL_MS = 40;
69
+ const TIMEOUT_MULTIPLIER = 2;
70
+ const TIMEOUT_MIN_MS = 200;
71
+
72
+ /**
73
+ * The exact timeout `createActorClient` would compute for `estimator`/
74
+ * `overrideMs` — factored out (sk-0m4.73) so a host that wants "the same
75
+ * default this actor's ActorClient uses" (e.g. the shared tool runtime reply
76
+ * window) can call this instead of re-deriving the tick-scaling formula.
77
+ *
78
+ * `overrideMs` wins when supplied (clamped to >=1ms). Otherwise a *measured*
79
+ * estimator cadence (five tick deltas) tick-scales (`2 × estimateMs()`,
80
+ * floored at `TIMEOUT_MIN_MS`). A cold estimator reports its 200ms floor,
81
+ * which is worse than having no estimator — treat it as unknown. When the
82
+ * world has published `config.tick_interval_secs`, that authored cadence
83
+ * scales the same way and beats the no-estimator default. Otherwise
84
+ * {@link DEFAULT_OBSERVATION_TIMEOUT_MS}.
85
+ */
86
+ export function resolveObservationTimeoutMs(
87
+ estimator?: TickIntervalEstimator,
88
+ overrideMs?: number,
89
+ authoredTickIntervalMs?: number,
90
+ ): number {
91
+ if (overrideMs !== undefined) return Math.max(1, overrideMs);
92
+ const measured = measuredCadenceMs(estimator);
93
+ if (measured !== undefined) {
94
+ return Math.max(TIMEOUT_MULTIPLIER * measured, TIMEOUT_MIN_MS);
95
+ }
96
+ if (
97
+ authoredTickIntervalMs !== undefined &&
98
+ Number.isFinite(authoredTickIntervalMs) &&
99
+ authoredTickIntervalMs > 0
100
+ ) {
101
+ return Math.max(TIMEOUT_MULTIPLIER * authoredTickIntervalMs, DEFAULT_OBSERVATION_TIMEOUT_MS);
102
+ }
103
+ return DEFAULT_OBSERVATION_TIMEOUT_MS;
104
+ }
105
+
106
+ function measuredCadenceMs(estimator?: TickIntervalEstimator): number | undefined {
107
+ if (estimator === undefined) return undefined;
108
+ // Duck-typed test doubles may only implement `estimateMs`. A missing
109
+ // `hasMeasuredCadence` means the caller already supplied a cadence.
110
+ if (typeof estimator.hasMeasuredCadence === "function" && !estimator.hasMeasuredCadence()) {
111
+ return undefined;
112
+ }
113
+ return estimator.estimateMs();
114
+ }
115
+
116
+ function authoredTickIntervalMs(db: SnapshotDb): number | undefined {
117
+ const secs = readWorldStatus(db)?.tickIntervalSecs;
118
+ if (secs === undefined || !Number.isFinite(secs) || secs <= 0) return undefined;
119
+ return secs * 1000;
120
+ }
121
+
122
+ export function createActorClient(
123
+ source: ActorClientSource,
124
+ actorId: string,
125
+ options?: ActorClientOptions,
126
+ ): ActorClient {
127
+ const src = toConnDb(source);
128
+ const frozenOptions = options ? freezeDriverReducers(options, options.driverToken) : options;
129
+ const snapshotDb = () => src.db;
130
+ const estimator =
131
+ options?.tickEstimator ??
132
+ ("estimator" in source
133
+ ? (source as { estimator?: TickIntervalEstimator }).estimator
134
+ : undefined);
135
+ const provenanceBuffer =
136
+ "conn" in source ? (source as SpellkaveSession).provenanceBuffer : undefined;
137
+ const pollMs =
138
+ options?.observationPollMs !== undefined
139
+ ? Math.max(1, options.observationPollMs)
140
+ : DEFAULT_OBSERVATION_POLL_MS;
141
+ const resolvedActorId = () =>
142
+ resolveActor(actorId, actorReaders(snapshotDb()).actors).body_entity_id;
143
+ const resolvedManipulationActorId = () => {
144
+ const wanted = parseEntityIdRef(actorId);
145
+ const owned = new Set(
146
+ readActorIdentityBindings(snapshotDb())
147
+ .filter((row) => row.role !== "co-pilot")
148
+ .map((row) => row.actor_id),
149
+ );
150
+ const principal = readActorPrincipals(snapshotDb()).find(
151
+ (row) =>
152
+ wanted !== undefined &&
153
+ String(row.current_body) === String(wanted) &&
154
+ owned.has(row.actor_id),
155
+ );
156
+ // A caller-owned placeless presence can act; movement keeps its spatial resolver.
157
+ return principal?.current_body ?? resolvedActorId();
158
+ };
159
+
160
+ const context = {
161
+ reducers: src.reducers ? freezeDriverReducers(src.reducers, options?.driverToken) : undefined,
162
+ options: frozenOptions,
163
+ actorId,
164
+ resolvedActorId,
165
+ resolvedManipulationActorId,
166
+ snapshotDb,
167
+ get timeoutMs() {
168
+ // Recompute per attempt: a cold estimator at connect must not freeze
169
+ // a 400ms window for the life of the client, and config.tick_interval_secs
170
+ // is already in the snapshot at session.ready.
171
+ return resolveObservationTimeoutMs(
172
+ estimator,
173
+ options?.observationTimeoutMs,
174
+ authoredTickIntervalMs(snapshotDb()),
175
+ );
176
+ },
177
+ pollMs,
178
+ estimator,
179
+ provenanceBuffer,
180
+ };
181
+
182
+ return {
183
+ withDriverToken: (token) =>
184
+ createActorClient(source, actorId, { ...options, driverToken: token }),
185
+ actorId,
186
+ ...createActorClientQueryMethods(context),
187
+ ...createActorSessionMethods(context),
188
+ ...createActorClientSenseMethods(context),
189
+ ...createActorClientReactionMethods(context),
190
+ };
191
+ }
192
+
193
+ export type { ControlReducerPort, DriverToken } from "./driver_control";
@@ -0,0 +1,101 @@
1
+ import type { SnapshotDb } from "../connection";
2
+ import { resolveActor } from "./actor";
3
+ import { type ActorClientReducers, actorReaders } from "./actor_control_source";
4
+ import type { EntityId } from "./ids";
5
+ import { listAdjacentMoves } from "./movement";
6
+ import type { ProvenanceRingBuffer } from "./provenance_buffer";
7
+ import { readActorSnapshot } from "./readers/actor_snapshot";
8
+ import { readLocationSnapshot } from "./readers/location_snapshot";
9
+ import { suggestNextAction } from "./readers/suggest_next_action";
10
+ import { rManipulateWrapper } from "./reducers/r_manipulate";
11
+ import { rMoveWrapper } from "./reducers/r_move";
12
+ import type { TickIntervalEstimator } from "./tick_cadence";
13
+ import type { ActorClientOptions, ActorManipulateResult, ActorMoveResult } from "./types";
14
+
15
+ /** Shared plumbing for the read/query + move/manipulate half of ActorClient. */
16
+ export interface ActorQueryMethodContext {
17
+ reducers?: ActorClientReducers;
18
+ options?: ActorClientOptions;
19
+ actorId: string;
20
+ resolvedActorId: () => EntityId;
21
+ resolvedManipulationActorId: () => EntityId;
22
+ snapshotDb: () => SnapshotDb;
23
+ timeoutMs: number;
24
+ pollMs: number;
25
+ estimator?: TickIntervalEstimator;
26
+ provenanceBuffer?: ProvenanceRingBuffer;
27
+ }
28
+
29
+ export function createActorClientQueryMethods(context: ActorQueryMethodContext) {
30
+ const rMove =
31
+ context.options?.rMove ??
32
+ context.reducers?.rMove ??
33
+ (async () => {
34
+ throw new Error("rMove reducer is not configured");
35
+ });
36
+ const rManipulate =
37
+ context.options?.rManipulate ??
38
+ context.reducers?.rManipulate ??
39
+ (async () => {
40
+ throw new Error("rManipulate reducer is not configured");
41
+ });
42
+
43
+ return {
44
+ actorSnapshot() {
45
+ const snap = readActorSnapshot(context.snapshotDb(), context.resolvedActorId());
46
+ if (!snap)
47
+ throw new Error(
48
+ `actor '${context.actorId}' not found in live actor_spatial_location — fail closed`,
49
+ );
50
+ return snap;
51
+ },
52
+ locationSnapshot() {
53
+ const a = resolveActor(context.actorId, actorReaders(context.snapshotDb()).actors);
54
+ return a.current_node_id
55
+ ? readLocationSnapshot(context.snapshotDb(), a.current_node_id)
56
+ : null;
57
+ },
58
+ adjacentMoves() {
59
+ const s = actorReaders(context.snapshotDb());
60
+ return listAdjacentMoves(resolveActor(context.actorId, s.actors), s.movement);
61
+ },
62
+ suggestNextAction() {
63
+ return suggestNextAction(context.snapshotDb(), context.resolvedActorId());
64
+ },
65
+ move: (edgeId: string): Promise<ActorMoveResult> =>
66
+ rMoveWrapper(
67
+ context.resolvedActorId(),
68
+ edgeId,
69
+ context.snapshotDb,
70
+ rMove,
71
+ context.timeoutMs,
72
+ context.pollMs,
73
+ context.estimator,
74
+ context.provenanceBuffer,
75
+ ),
76
+ manipulate<T>(
77
+ targetId: string,
78
+ actionId: string,
79
+ argsJson: string,
80
+ sp: (db: SnapshotDb) => boolean,
81
+ cs: (db: SnapshotDb) => T | null,
82
+ ): Promise<ActorManipulateResult<T>> {
83
+ return rManipulateWrapper(
84
+ context.resolvedManipulationActorId(),
85
+ targetId,
86
+ actionId,
87
+ argsJson,
88
+ context.snapshotDb,
89
+ rManipulate,
90
+ sp,
91
+ cs,
92
+ context.timeoutMs,
93
+ context.pollMs,
94
+ context.estimator,
95
+ context.provenanceBuffer,
96
+ context.options?.successOnProvenance ?? false,
97
+ context.options?.reducerAttemptTelemetry,
98
+ );
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,79 @@
1
+ import type { SnapshotDb } from "../connection";
2
+ import type { ActorClientReducers } from "./actor_control_source";
3
+ import type { EntityId } from "./ids";
4
+ import type { ProvenanceRingBuffer } from "./provenance_buffer";
5
+ import { rActorWakeUpWrapper } from "./reducers/r_actor_wake_up";
6
+ import { type RReactFn, rReactWrapper } from "./reducers/r_react";
7
+ import { rReleaseClaimWrapper } from "./reducers/r_release_claim";
8
+ import type { TickIntervalEstimator } from "./tick_cadence";
9
+ import type { ActorClientOptions, ActorReactResult } from "./types";
10
+
11
+ /** Shared plumbing for the react/releaseClaim/wakeUp half of ActorClient. */
12
+ export interface ActorReactionMethodContext {
13
+ reducers?: ActorClientReducers;
14
+ options?: ActorClientOptions;
15
+ resolvedActorId: () => EntityId;
16
+ resolvedManipulationActorId: () => EntityId;
17
+ snapshotDb: () => SnapshotDb;
18
+ timeoutMs: number;
19
+ pollMs: number;
20
+ estimator?: TickIntervalEstimator;
21
+ provenanceBuffer?: ProvenanceRingBuffer;
22
+ }
23
+
24
+ export function createActorClientReactionMethods(context: ActorReactionMethodContext) {
25
+ const rReact: RReactFn =
26
+ context.options?.rReact ??
27
+ context.reducers?.rReact ??
28
+ (async () => {
29
+ throw new Error("rReact reducer is not configured");
30
+ });
31
+ const rReleaseClaim =
32
+ context.options?.rReleaseClaim ??
33
+ context.reducers?.rReleaseClaim ??
34
+ (async () => {
35
+ throw new Error("rReleaseClaim reducer is not configured");
36
+ });
37
+ const rActorWakeUp =
38
+ context.options?.rActorWakeUp ??
39
+ context.reducers?.rActorWakeUp ??
40
+ (async () => {
41
+ throw new Error("rActorWakeUp reducer is not configured");
42
+ });
43
+
44
+ return {
45
+ react(
46
+ pendingId: bigint,
47
+ responseIntent: string,
48
+ selectedDrawIndex?: number,
49
+ ): Promise<ActorReactResult> {
50
+ return rReactWrapper(
51
+ context.resolvedActorId(),
52
+ pendingId,
53
+ responseIntent,
54
+ context.snapshotDb,
55
+ rReact,
56
+ context.timeoutMs,
57
+ context.pollMs,
58
+ context.estimator,
59
+ context.provenanceBuffer,
60
+ selectedDrawIndex,
61
+ );
62
+ },
63
+ releaseClaim(targetId: string) {
64
+ return rReleaseClaimWrapper(
65
+ context.resolvedManipulationActorId(),
66
+ targetId,
67
+ context.snapshotDb,
68
+ rReleaseClaim,
69
+ context.timeoutMs,
70
+ context.pollMs,
71
+ context.estimator,
72
+ context.provenanceBuffer,
73
+ );
74
+ },
75
+ wakeUp() {
76
+ return rActorWakeUpWrapper(context.resolvedActorId(), rActorWakeUp);
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,81 @@
1
+ import type { SnapshotDb } from "../connection";
2
+ import type { ActorClientReducers } from "./actor_control_source";
3
+ import type { EntityId } from "./ids";
4
+ import type { ProvenanceRingBuffer } from "./provenance_buffer";
5
+ import {
6
+ type RInscribeTraceFn,
7
+ rInscribeTraceWrapper,
8
+ type VisibilityClass,
9
+ } from "./reducers/r_inscribe_trace";
10
+ import { type RSenseFn, rSenseWrapper } from "./reducers/r_sense";
11
+ import type { TickIntervalEstimator } from "./tick_cadence";
12
+ import type { ActorClientOptions, ActorSenseResult, InscribeTraceResult } from "./types";
13
+
14
+ /** Shared plumbing for the sense + inscribeTrace half of ActorClient. */
15
+ export interface ActorSenseMethodContext {
16
+ reducers?: ActorClientReducers;
17
+ options?: ActorClientOptions;
18
+ resolvedActorId: () => EntityId;
19
+ snapshotDb: () => SnapshotDb;
20
+ timeoutMs: number;
21
+ pollMs: number;
22
+ estimator?: TickIntervalEstimator;
23
+ provenanceBuffer?: ProvenanceRingBuffer;
24
+ }
25
+
26
+ export function createActorClientSenseMethods(context: ActorSenseMethodContext) {
27
+ const rSense: RSenseFn =
28
+ context.options?.rSense ??
29
+ context.reducers?.rSense ??
30
+ (async () => {
31
+ throw new Error("rSense reducer is not configured");
32
+ });
33
+ const rInscribeTrace: RInscribeTraceFn =
34
+ context.options?.rInscribeTrace ??
35
+ context.reducers?.rInscribeTrace ??
36
+ (async () => {
37
+ throw new Error("rInscribeTrace reducer is not configured");
38
+ });
39
+
40
+ return {
41
+ sense(queryKind: string, visibilityClass: string): Promise<ActorSenseResult> {
42
+ return rSenseWrapper(
43
+ context.resolvedActorId(),
44
+ queryKind,
45
+ visibilityClass,
46
+ context.snapshotDb,
47
+ rSense,
48
+ context.timeoutMs,
49
+ context.pollMs,
50
+ context.estimator,
51
+ context.provenanceBuffer,
52
+ );
53
+ },
54
+ inscribeTrace(
55
+ kind: string,
56
+ locationKind: string,
57
+ locationRef: string,
58
+ payloadJson: string,
59
+ visibility: VisibilityClass,
60
+ bundleId: string,
61
+ expiresAtTick?: bigint,
62
+ ): Promise<InscribeTraceResult> {
63
+ return rInscribeTraceWrapper(
64
+ context.resolvedActorId(),
65
+ kind,
66
+ locationKind,
67
+ locationRef,
68
+ payloadJson,
69
+ expiresAtTick,
70
+ visibility,
71
+ bundleId,
72
+ context.snapshotDb,
73
+ rInscribeTrace,
74
+ context.timeoutMs,
75
+ context.pollMs,
76
+ context.estimator,
77
+ context.provenanceBuffer,
78
+ );
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,57 @@
1
+ import type { DbConnection } from "@spellkave/bindings";
2
+ import type { SnapshotDb, SpellkaveSession } from "../connection";
3
+ import { snapshotFromDb } from "../connection";
4
+
5
+ export type ActorClientSource = SpellkaveSession | DbConnection | SnapshotDb;
6
+ export type RMoveFn = DbConnection["reducers"]["rMove"];
7
+ export type RManipulateFn = DbConnection["reducers"]["rManipulate"];
8
+ export type RSessionCloseFn = DbConnection["reducers"]["rSessionClose"];
9
+ export type RSessionMoveFn = DbConnection["reducers"]["rSessionMove"];
10
+ export type RSessionOpenFn = DbConnection["reducers"]["rSessionOpen"];
11
+ export type RSenseFn = DbConnection["reducers"]["rSense"];
12
+ export type RInscribeTraceFn = DbConnection["reducers"]["rInscribeTrace"];
13
+ export type RReactFn = DbConnection["reducers"]["rReact"];
14
+ export type RReleaseClaimFn = DbConnection["reducers"]["rReleaseClaim"];
15
+ export type RActorWakeUpFn = DbConnection["reducers"]["rActorWakeUp"];
16
+ export type RAdvanceTurnFn = DbConnection["reducers"]["rAdvanceTurn"];
17
+
18
+ export interface ActorClientReducers {
19
+ rMove?: RMoveFn;
20
+ rManipulate?: RManipulateFn;
21
+ rSessionClose?: RSessionCloseFn;
22
+ rSessionMove?: RSessionMoveFn;
23
+ rSessionOpen?: RSessionOpenFn;
24
+ rSense?: RSenseFn;
25
+ rInscribeTrace?: RInscribeTraceFn;
26
+ rReact?: RReactFn;
27
+ rReleaseClaim?: RReleaseClaimFn;
28
+ rActorWakeUp?: RActorWakeUpFn;
29
+ rAdvanceTurn?: RAdvanceTurnFn;
30
+ }
31
+
32
+ export function toConnDb(source: ActorClientSource): {
33
+ db: SnapshotDb;
34
+ reducers?: ActorClientReducers;
35
+ } {
36
+ const conn = ("conn" in source ? source.conn : source) as Record<string, unknown>;
37
+ if (typeof conn !== "object" || conn === null)
38
+ throw new Error("actor client source is not an object");
39
+ if ("db" in conn && conn.db && typeof conn.db === "object") {
40
+ return {
41
+ db: conn.db as SnapshotDb,
42
+ reducers: (conn as { reducers?: ActorClientReducers }).reducers,
43
+ };
44
+ }
45
+ return { db: conn as SnapshotDb, reducers: undefined };
46
+ }
47
+
48
+ export function actorReaders(db: SnapshotDb) {
49
+ const s = snapshotFromDb(db);
50
+ return {
51
+ actors: { locations: () => Array.from(s.actors.locations()) },
52
+ movement: {
53
+ edges: () => Array.from(s.movement.edges()),
54
+ nodes: () => Array.from(s.movement.nodes()),
55
+ },
56
+ };
57
+ }