@myclaw163/clawclaw-cli 0.9.2 → 0.10.1

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 (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -1,395 +1,2 @@
1
- import { randomUUID } from 'crypto';
2
- import type {
3
- ActionCaller,
4
- ActionDispatch,
5
- ActionExecutionRevalidation,
6
- ActionResult,
7
- ActionService,
8
- LatestAcceptedRuntimeState,
9
- ObservationProvider,
10
- ObservationQueryContext,
11
- ObservationResult,
12
- ScopeRef,
13
- } from './contracts.js';
14
- import {
15
- ControlCoordinator,
16
- WILDCARD_DOMAIN,
17
- type ControlDeferred,
18
- type ControllerSpec,
19
- } from './control-coordinator.js';
20
- import { BEHAVIOR_CONTROLLER_PRIORITY } from './control/types.js';
21
-
22
- const DEFAULT_IMPLICIT_SYSTEM_LEASE_MS = 1_000;
23
-
24
- function isActionDispatch<R>(value: ActionResult<R> | ActionDispatch<R>): value is ActionDispatch<R> {
25
- return !!value
26
- && typeof value === 'object'
27
- && 'receipt' in value
28
- && 'settled' in value
29
- && value.settled instanceof Promise;
30
- }
31
-
32
- export interface ActionAdmissionOptions {
33
- /** Revalidated immediately before ActionService is called. */
34
- isAuthorized?: () => boolean;
35
- /** Runtime-owned raw State view used by adapter-specific safety admission. */
36
- latestAcceptedState?: () => LatestAcceptedRuntimeState | null;
37
- }
38
-
39
- function scopedCallerId(kind: 'agent' | 'user', id: string | undefined, scope: ScopeRef): string {
40
- return `${kind}:${encodeURIComponent(id ?? 'default')}`
41
- + `@${encodeURIComponent(scope.sessionId)}/${encodeURIComponent(scope.segmentId)}`;
42
- }
43
-
44
- /** Stable owner-local identity used by Action callers and lifecycle supervisors. */
45
- export function actionControllerId(caller: ActionCaller, scope?: ScopeRef): string {
46
- if (caller.kind === 'agent' || caller.kind === 'user') {
47
- if (!scope) throw new Error(`${caller.kind} controller identity requires a runtime scope.`);
48
- return scopedCallerId(caller.kind, caller.id, scope);
49
- }
50
- if (caller.kind === 'behavior') {
51
- if (!caller.activationId.trim()) throw new Error('Behavior activation id must not be empty.');
52
- if (!Number.isSafeInteger(caller.activationGeneration) || caller.activationGeneration <= 0) {
53
- throw new Error('Behavior activation generation must be a positive safe integer.');
54
- }
55
- if (!['long', 'short', 'reflex'].includes(caller.layer)) {
56
- throw new Error('Behavior control layer is invalid.');
57
- }
58
- return `behavior:${encodeURIComponent(caller.activationId)}`
59
- + `@generation-${caller.activationGeneration}`;
60
- }
61
- return `${caller.kind}:${encodeURIComponent(caller.id)}`;
62
- }
63
-
64
- export type BehaviorActionCaller = Extract<ActionCaller, { kind: 'behavior' }>;
65
-
66
- /**
67
- * Builds the explicit controller reservation owned by the unified Behavior Host.
68
- * Action callers cannot supply or raise control priority through an Action.
69
- */
70
- export function behaviorControllerSpec(
71
- caller: BehaviorActionCaller,
72
- spec: Omit<ControllerSpec, 'controllerId' | 'kind' | 'priority'>,
73
- ): ControllerSpec {
74
- const controllerId = actionControllerId(caller);
75
- return {
76
- ...spec,
77
- controllerId,
78
- kind: 'behavior',
79
- priority: BEHAVIOR_CONTROLLER_PRIORITY[caller.layer],
80
- metadata: {
81
- ...spec.metadata,
82
- behaviorActivationId: caller.activationId,
83
- behaviorLayer: caller.layer,
84
- behaviorActivationGeneration: caller.activationGeneration,
85
- },
86
- };
87
- }
88
-
89
- function deferredMessage(code: string): string {
90
- switch (code) {
91
- case 'CONTROL_HELD': return 'The action is temporarily held by another local controller.';
92
- case 'CONTROL_BUSY': return 'A conflicting action is already being submitted; recompute from fresh state and retry.';
93
- case 'CONTROL_SCOPE_CHANGED': return 'The game scope changed before this action could be submitted.';
94
- case 'CONTROL_NOT_READY': return 'The controller is not ready to submit actions.';
95
- case 'CONTROL_STOPPING': return 'The local game runtime is stopping.';
96
- case 'CONTROL_AUTHORITY_REVOKED': return 'The worker lost authority before this action reached the game provider.';
97
- default: return 'The local control scheduler deferred this action.';
98
- }
99
- }
100
-
101
- function deferredActionResult<R>(
102
- scope: ScopeRef,
103
- deferred: Pick<ControlDeferred, 'code' | 'domains' | 'reason' | 'retryable'>,
104
- ): ActionResult<R> {
105
- return {
106
- scope,
107
- actionId: randomUUID(),
108
- status: 'deferred',
109
- source: 'local',
110
- actionOutcome: 'not_submitted',
111
- error: {
112
- code: deferred.code,
113
- message: deferredMessage(deferred.code),
114
- details: {
115
- phase: 'control',
116
- // Reversible preparation (for example an upload) may already have
117
- // happened, but the actual gameplay Action endpoint was not called.
118
- action_endpoint_called: false,
119
- domains: [...deferred.domains],
120
- reason: deferred.reason,
121
- retryable: deferred.retryable,
122
- },
123
- },
124
- };
125
- }
126
-
127
- export class CapabilityConflictError extends Error {
128
- constructor(capability: string) {
129
- super(`Capability already registered: ${capability}`);
130
- this.name = 'CapabilityConflictError';
131
- }
132
- }
133
-
134
- /** Registry for pull-only information that does not need a pushed Event. */
135
- export class ObservationRegistry {
136
- private readonly providers = new Map<string, ObservationProvider<any, any>>();
137
-
138
- register<Q, R>(provider: ObservationProvider<Q, R>): () => void {
139
- if (this.providers.has(provider.capability)) {
140
- throw new CapabilityConflictError(provider.capability);
141
- }
142
- this.providers.set(provider.capability, provider);
143
- return () => {
144
- if (this.providers.get(provider.capability) === provider) {
145
- this.providers.delete(provider.capability);
146
- }
147
- };
148
- }
149
-
150
- capabilities(): string[] {
151
- return [...this.providers.keys()].sort();
152
- }
153
-
154
- async query<Q, R>(
155
- capability: string,
156
- request: Q,
157
- scope: ScopeRef,
158
- context: ObservationQueryContext = {},
159
- ): Promise<ObservationResult<R>> {
160
- const provider = this.providers.get(capability);
161
- if (!provider) throw new Error(`Observation capability is not available: ${capability}`);
162
- return provider.query(request, scope, context) as Promise<ObservationResult<R>>;
163
- }
164
- }
165
-
166
- export interface RegisteredActionService<A = unknown, R = unknown> extends ActionService<A, R> {
167
- readonly capability: string;
168
- }
169
-
170
- /** Shared action boundary for direct Agent calls and automated controllers. */
171
- export class ActionRegistry {
172
- private readonly services = new Map<string, RegisteredActionService<any, any>>();
173
- /** Public lifecycle facade used by the unified Behavior Host. */
174
- readonly controls = new ControlCoordinator();
175
- private readonly abortController = new AbortController();
176
- private readonly scopeControllers = new Map<string, AbortController>();
177
- private readonly inFlight = new Set<Promise<unknown>>();
178
- /** Provider-owned settlements no longer hold a control domain, but shutdown still drains them. */
179
- private readonly detachedSettlements = new Set<Promise<unknown>>();
180
- private stopping = false;
181
-
182
- register<A, R>(service: RegisteredActionService<A, R>): () => void {
183
- if (this.services.has(service.capability)) {
184
- throw new CapabilityConflictError(service.capability);
185
- }
186
- this.services.set(service.capability, service);
187
- return () => {
188
- if (this.services.get(service.capability) === service) {
189
- this.services.delete(service.capability);
190
- }
191
- };
192
- }
193
-
194
- capabilities(): string[] {
195
- return [...this.services.keys()].sort();
196
- }
197
-
198
- /** Revoke old-scope controllers; already-submitted providers remain a handoff barrier. */
199
- activateScope(scope: ScopeRef): void {
200
- this.controls.activateScope(scope);
201
- }
202
-
203
- private scopeController(scope: ScopeRef): AbortController {
204
- const key = JSON.stringify([scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId]);
205
- let controller = this.scopeControllers.get(key);
206
- if (!controller) {
207
- controller = new AbortController();
208
- this.scopeControllers.set(key, controller);
209
- }
210
- return controller;
211
- }
212
-
213
- /** Fence this scope permanently; a subsequent game/room scope gets its own signal. */
214
- closeScope(scope: ScopeRef, reason: string): void {
215
- this.scopeController(scope).abort(new Error(reason));
216
- }
217
-
218
- private closedScopeResult<R>(scope: ScopeRef): ActionResult<R> | undefined {
219
- const signal = this.scopeController(scope).signal;
220
- if (!signal.aborted) return undefined;
221
- return {
222
- scope, actionId: randomUUID(), status: 'failure', source: 'local',
223
- actionOutcome: 'not_submitted',
224
- error: { code: signal.reason.message, message: 'This scope has ended; the Action was not submitted.' },
225
- };
226
- }
227
-
228
- releaseController(controllerId: string, reason = 'released'): void {
229
- this.controls.release(controllerId, { reason });
230
- }
231
-
232
- releaseCaller(caller: ActionCaller, reason = 'released', scope?: ScopeRef): void {
233
- this.releaseController(actionControllerId(caller, scope), reason);
234
- }
235
-
236
- async perform<A, R>(
237
- capability: string,
238
- action: A,
239
- scope: ScopeRef,
240
- caller: ActionCaller,
241
- options: ActionAdmissionOptions = {},
242
- ): Promise<ActionResult<R>> {
243
- if (this.stopping) throw new Error('Action registry is stopping.');
244
- const closed = this.closedScopeResult<R>(scope);
245
- if (closed) return closed;
246
- const service = this.services.get(capability);
247
- if (!service) throw new Error(`Action capability is not available: ${capability}`);
248
- const descriptor = service.describeControl?.(action, scope, caller);
249
- const domains = descriptor?.domains === undefined
250
- ? [WILDCARD_DOMAIN]
251
- : [...descriptor.domains];
252
- const controllerId = actionControllerId(caller, scope);
253
- if (options.isAuthorized && !options.isAuthorized()) {
254
- return deferredActionResult<R>(scope, {
255
- code: 'CONTROL_AUTHORITY_REVOKED' as ControlDeferred['code'],
256
- domains,
257
- reason: 'worker_authority_revoked',
258
- retryable: false,
259
- });
260
- }
261
- const existing = this.controls.snapshot().controllers.find(
262
- (controller) => controller.controllerId === controllerId,
263
- );
264
- const terminal = existing?.state === 'released' || existing?.state === 'expired';
265
- const mayReplaceTerminal = caller.kind === 'agent'
266
- || caller.kind === 'user'
267
- || caller.kind === 'system';
268
- // Behavior controllers are never synthesized from their first Action.
269
- // Their Host must reserve the full claim and establish precedence before
270
- // any provider may see work.
271
- if (caller.kind !== 'behavior' && (!existing || (terminal && mayReplaceTerminal))) {
272
- const activity = caller.kind === 'agent' || caller.kind === 'user' || caller.kind === 'system';
273
- const spec: ControllerSpec = {
274
- controllerId,
275
- kind: caller.kind,
276
- scope,
277
- // Activity controllers declare wildcard authority but claim only the
278
- // domains they actually touch. Capability workers may start with a
279
- // conservative wildcard controller and narrow it later.
280
- domains: [WILDCARD_DOMAIN],
281
- ready: true,
282
- holdMode: 'all_or_nothing',
283
- ...(activity
284
- ? {
285
- lifecycle: 'activity_lease' as const,
286
- activityLeaseMs: caller.kind === 'system'
287
- ? DEFAULT_IMPLICIT_SYSTEM_LEASE_MS
288
- : descriptor?.agentLeaseMs,
289
- }
290
- : { lifecycle: 'persistent' as const, metadata: { implicit: true } }),
291
- };
292
- this.controls.registerController(spec);
293
- }
294
-
295
- let receiptResolved = false;
296
- let resolveReceipt!: (result: ActionResult<R>) => void;
297
- let rejectReceipt!: (error: unknown) => void;
298
- const receipt = new Promise<ActionResult<R>>((resolve, reject) => {
299
- resolveReceipt = (result) => {
300
- if (receiptResolved) return;
301
- receiptResolved = true;
302
- resolve(result);
303
- };
304
- rejectReceipt = (error) => {
305
- if (receiptResolved) return;
306
- receiptResolved = true;
307
- reject(error);
308
- };
309
- });
310
- const operation = this.controls.runAction<ActionResult<R>>({
311
- controllerId,
312
- scope,
313
- domains,
314
- handoffWaitMs: descriptor?.handoffTimeoutMs,
315
- execute: async (controlContext) => {
316
- const revalidate = (): ActionExecutionRevalidation => {
317
- const closed = this.closedScopeResult<never>(scope);
318
- if (closed) return { status: 'deferred', result: closed };
319
- if (options.isAuthorized && !options.isAuthorized()) {
320
- this.controls.release(controllerId, { reason: 'worker_authority_revoked' });
321
- return {
322
- status: 'deferred',
323
- result: deferredActionResult<never>(scope, {
324
- code: 'CONTROL_AUTHORITY_REVOKED' as ControlDeferred['code'],
325
- domains,
326
- reason: 'worker_authority_revoked',
327
- retryable: false,
328
- }),
329
- };
330
- }
331
- const deferred = controlContext.revalidate();
332
- return deferred
333
- ? { status: 'deferred', result: deferredActionResult<never>(scope, deferred) }
334
- : { status: 'authorized' };
335
- };
336
- const authority = revalidate();
337
- if (authority.status === 'deferred') return authority.result;
338
- const providerResult = await service.perform(
339
- action,
340
- scope,
341
- caller,
342
- {
343
- signal: AbortSignal.any([this.abortController.signal, this.scopeController(scope).signal]),
344
- revalidate,
345
- latestAcceptedState: options.latestAcceptedState ?? (() => null),
346
- },
347
- ) as ActionResult<R> | ActionDispatch<R>;
348
- if (isActionDispatch(providerResult)) {
349
- resolveReceipt(providerResult.receipt);
350
- const settlement = providerResult.settled;
351
- this.detachedSettlements.add(settlement);
352
- void settlement.catch(() => {}).finally(() => {
353
- this.detachedSettlements.delete(settlement);
354
- });
355
- // Dispatch transfers the accepted submission to the provider. The
356
- // controller may enqueue its next physical Action immediately;
357
- // provider-owned FIFO still controls endpoint start order. Only
358
- // Runtime shutdown continues to own the real provider settlement.
359
- return providerResult.receipt;
360
- }
361
- return providerResult;
362
- },
363
- });
364
- this.inFlight.add(operation);
365
- void operation.then(
366
- (controlled) => resolveReceipt(controlled.status === 'executed'
367
- ? controlled.value
368
- : deferredActionResult<R>(scope, controlled)),
369
- rejectReceipt,
370
- ).finally(() => {
371
- this.inFlight.delete(operation);
372
- });
373
- // Attach a rejection observer immediately. Detached provider settlement
374
- // can fail after its caller has already received a receipt.
375
- void operation.catch(() => {});
376
- return receipt;
377
- }
378
-
379
- /** Revoke new Action admission and abort every admitted provider request. */
380
- beginStopping(reason = 'runtime_stopping'): void {
381
- if (this.stopping) return;
382
- this.stopping = true;
383
- this.controls.beginStopping();
384
- this.abortController.abort(new Error(reason));
385
- }
386
-
387
- /** Wait until providers have observed cancellation and actually returned. */
388
- async waitForIdle(): Promise<void> {
389
- while (this.inFlight.size > 0 || this.detachedSettlements.size > 0) {
390
- await Promise.allSettled([...this.inFlight]);
391
- await Promise.allSettled([...this.detachedSettlements]);
392
- }
393
- await this.controls.waitForIdle();
394
- }
395
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/capability-registry.js';
@@ -1,144 +1,2 @@
1
- /** Transport-neutral capability contracts for the game-neutral Runtime. */
2
-
3
- import type { StoredStateFrame } from './state/history/contracts.js';
4
-
5
- export interface ScopeRef {
6
- adapterId: string;
7
- accountId: string;
8
- sessionId: string;
9
- segmentId: string;
10
- }
11
-
12
- export interface ObservationResult<T> {
13
- scope: ScopeRef;
14
- capability: string;
15
- observedAt?: string;
16
- receivedAt: string;
17
- freshness: 'fresh' | 'stale' | 'unknown';
18
- value: T;
19
- provenance?: Record<string, unknown>;
20
- }
21
-
22
- export interface ObservationQueryContext {
23
- /** Present when one Epoch Plugin calls another capability while processing E. */
24
- epochSeq?: number;
25
- /** Exact accepted Runtime State frame for E; never a later mutable provider snapshot. */
26
- stateFrame?: Readonly<StoredStateFrame<Record<string, unknown>>>;
27
- }
28
-
29
- /** Runtime-owned control layer for one unified Behavior activation. */
30
- export type BehaviorControlLayer = 'long' | 'short' | 'reflex';
31
-
32
- /**
33
- * Pull-only information such as a full map, inventory, object detail, or a
34
- * bounded history page. Querying a provider does not implicitly create an
35
- * Event.
36
- */
37
- export interface ObservationProvider<Q = unknown, R = unknown> {
38
- readonly capability: string;
39
- query(
40
- request: Q,
41
- scope: ScopeRef,
42
- context: ObservationQueryContext,
43
- ): Promise<ObservationResult<R>>;
44
- }
45
-
46
- export type ActionCaller =
47
- | { kind: 'agent'; id?: string }
48
- | {
49
- kind: 'behavior';
50
- /** Unique logical activation; module ids are deliberately not controller ids. */
51
- activationId: string;
52
- layer: BehaviorControlLayer;
53
- /** Fresh module instance created when a suspended activation restarts. */
54
- activationGeneration: number;
55
- }
56
- | { kind: 'user'; id?: string }
57
- | { kind: 'system'; id: string };
58
-
59
- /**
60
- * Logical control domains required atomically by an Action. Actions in
61
- * unrelated domains can be controlled independently. `*` is a real wildcard;
62
- * services that omit a descriptor are conservatively treated as `*`.
63
- */
64
- export interface ActionControlDescriptor {
65
- domains: string[];
66
- /** Adapter policy for a direct Agent's inactivity hold on these domains. */
67
- agentLeaseMs?: number;
68
- /** Maximum time a takeover may wait for an already-submitted lower action. */
69
- handoffTimeoutMs?: number;
70
- }
71
-
72
- export interface ActionResult<T = unknown> {
73
- scope: ScopeRef;
74
- actionId: string;
75
- /** `deferred` is local control scheduling, never a backend rejection. */
76
- status: 'success' | 'partial' | 'deferred' | 'failure';
77
- /** Which boundary produced this result; backend payloads remain unwrapped in `error`. */
78
- source?: 'backend' | 'transport' | 'protocol' | 'local';
79
- /** Whether the gameplay Action endpoint definitely handled this attempt. */
80
- actionOutcome?: 'confirmed' | 'not_submitted' | 'unknown';
81
- value?: T;
82
- error?: unknown;
83
- effects?: Array<Record<string, unknown>>;
84
- }
85
-
86
- /**
87
- * A provider-owned asynchronous Action submission.
88
- *
89
- * `receipt` transfers ownership to the provider without claiming that the
90
- * gameplay endpoint has acknowledged the Action. `settled` retains the real
91
- * HTTP/ACK result inside the provider boundary. The Runtime releases the
92
- * controller's submission fence at `receipt`; providers that accept ordered
93
- * automated Decisions must preserve their endpoint-start FIFO internally.
94
- * Runtime keeps shutdown drain ownership until `settled` completes.
95
- */
96
- export interface ActionDispatch<T = unknown> {
97
- receipt: ActionResult<T>;
98
- settled: Promise<ActionResult<T>>;
99
- }
100
-
101
- export type ActionServiceResult<T = unknown> = ActionResult<T> | ActionDispatch<T>;
102
-
103
- export type ActionExecutionRevalidation =
104
- | { status: 'authorized' }
105
- | {
106
- status: 'deferred';
107
- /** Registry-owned local result; it is never a rewritten backend error. */
108
- result: ActionResult<never>;
109
- };
110
-
111
- export interface LatestAcceptedRuntimeState {
112
- readonly epochSeq: number;
113
- readonly state: Readonly<Record<string, unknown>>;
114
- }
115
-
116
- export interface ActionExecutionContext {
117
- /** Aborted when the owning runtime is stopping. */
118
- signal: AbortSignal;
119
- /**
120
- * Recheck the exact admitted worker/controller/scope after asynchronous,
121
- * reversible preparation and immediately before an irreversible game call.
122
- */
123
- revalidate(): ActionExecutionRevalidation;
124
- /**
125
- * Latest raw State accepted for this scope, independent of plugin progress.
126
- * Adapter Action providers use it only for final local safety admission.
127
- */
128
- latestAcceptedState(): LatestAcceptedRuntimeState | null;
129
- }
130
-
131
- /** Behavior automation, legacy automation, and direct Agent tools share this boundary. */
132
- export interface ActionService<A = unknown, R = unknown> {
133
- describeControl?(
134
- action: A,
135
- scope: ScopeRef,
136
- caller: ActionCaller,
137
- ): ActionControlDescriptor;
138
- perform(
139
- action: A,
140
- scope: ScopeRef,
141
- caller: ActionCaller,
142
- context: ActionExecutionContext,
143
- ): ActionServiceResult<R> | Promise<ActionServiceResult<R>>;
144
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/contracts.js';