@myclaw163/game-agent-runtime 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 (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +242 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +56 -0
  127. package/dist/mailbox/mailbox-plugin.js +111 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +336 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # Game Agent Runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 通用游戏 Agent 运行框架,简称 **GAR**。它负责接收输入、按本地周期运行感知与策略、执行受控动作,并把通知交付给 Agent 宿主。
4
+
5
+ GAR 不包含具体游戏规则、地图、账号或后端协议。龙虾杀客户端 CCL 是一个接入实现;其他游戏可以独立使用 GAR,无须安装 CCL。
6
+
7
+ ## 安装
8
+
9
+ 需要 Node.js **24.12.0 或更高版本**,建议使用 Node.js 24。
10
+
11
+ ```sh
12
+ npm install @myclaw163/game-agent-runtime
13
+ ```
14
+
15
+ 如果只是玩龙虾杀,安装 `@myclaw163/clawclaw-cli` 即可,npm 会自动安装 GAR。
16
+
17
+ ## 框架与游戏的分工
18
+
19
+ | GAR 提供 | 游戏接入方提供 |
20
+ |---|---|
21
+ | Source 生命周期、输入存储与本地周期调度 | 后端连接、协议转换、State 和 Event 内容 |
22
+ | 并行感知、模块状态与通知接纳 | 观察投影、感知脚本和通知内容 |
23
+ | 长期/短期/反射控制、暂停恢复与局中改参 | 策略脚本、输入校验和游戏执行条件 |
24
+ | Action/Query 能力接口与控制权校验 | 实际动作提交和只读查询 |
25
+ | Worker、共享记忆、历史与日志 | 游戏 SDK 映射、Worker 桥接和运行配置 |
26
+ | Mailbox 分批交付、重试和交接确认 | 宿主端点、消息协议和接收端集成 |
27
+
28
+ 本地计算周期可配置,不要求每个后端 tick 计算一次。每轮使用最新 State 和待处理事件;实际接收时间与本地计算时间保持区分。
29
+
30
+ 已装配的感知与策略之间,有效反射绑定默认开启。局中关闭自动激活不会停止感知观察、通知和记忆。
31
+
32
+ ## 运行一个独立示例
33
+
34
+ 在安装目录运行:
35
+
36
+ ```sh
37
+ node node_modules/@myclaw163/game-agent-runtime/examples/run-grid-game.mjs
38
+ ```
39
+
40
+ 棋盘示例会启动真实感知和策略 Worker,把棋子从第 0 列移动到第 3 列,打印动作、通知与 Worker 结果,然后正常退出。无需游戏账号、模型 key 或 CCL;这是本地模拟,不会连接线上游戏。
41
+
42
+ 示例中的 `grid-game.mjs` 展示完整装配,`grid-strategy.mjs` 与 `grid-perception.mjs` 展示独立脚本。也可以从自己的程序导入工厂函数:
43
+
44
+ ```js
45
+ import { createGridGame } from '@myclaw163/game-agent-runtime/examples/grid-game.mjs';
46
+ ```
47
+
48
+ ## 接入自己的游戏
49
+
50
+ 1. 用 Source 接入权威 State 和 Event,并保留输入时间及来源。
51
+ 2. 实现感知/策略适配器:整理脚本输入、游戏执行条件和 SDK。
52
+ 3. 注册 Action 和只读 Query,连接游戏后端。
53
+ 4. 装配 Mailbox 输出,与 Agent 宿主交换通知和控制指令。
54
+
55
+ 常用公开入口:
56
+
57
+ | 导入路径 | 用途 |
58
+ |---|---|
59
+ | 包根入口 | Runtime、存储、Source/周期插件、Action/Query 契约 |
60
+ | `strategy/strategy-host.js`、`strategy/contracts.js` | 策略控制与适配契约 |
61
+ | `perception/perception-host.js`、`perception/contracts.js` | 感知执行与适配契约 |
62
+ | `sdk/strategy.js`、`sdk/perception.js` | 脚本作者基类 |
63
+ | `memory/strategy-memory.js` | 当前运行作用域内的授权共享记忆 |
64
+ | `mailbox/`、`mailbox/adapters/` | 通知交付与宿主连接 |
65
+
66
+ 上述路径均以 `@myclaw163/game-agent-runtime/` 为前缀。包内同时提供 JavaScript 和 TypeScript 类型声明。
67
+
68
+ Worker 用于隔离执行和管理生命周期,不是执行不可信代码的安全沙箱。交接确认表示程序接收了消息,不等于模型已经阅读或完成处理;跨进程恢复也不属于当前共享记忆接口的保证。
@@ -0,0 +1,11 @@
1
+ import type { ActionResult } from './contracts.js';
2
+ export interface ActionErrorDiagnosticSummary {
3
+ readonly code?: string;
4
+ readonly httpStatus?: number;
5
+ readonly messagePresent: boolean;
6
+ readonly messageLength?: number;
7
+ }
8
+ /** Extract only machine-readable Action failure metadata; never copy the response body. */
9
+ export declare function summarizeActionError(error: unknown): ActionErrorDiagnosticSummary;
10
+ /** Unknown, transport, protocol, auth and server failures stay error-level. */
11
+ export declare function actionFailureDiagnosticSeverity(result: Pick<ActionResult, 'source' | 'actionOutcome' | 'error'>, rejectionCodes?: ReadonlySet<string>): 'warn' | 'error';
@@ -0,0 +1,67 @@
1
+ const CLIENT_REJECTION_HTTP_STATUSES = new Set([400, 409, 422]);
2
+ function record(value) {
3
+ return value && typeof value === 'object' && !Array.isArray(value)
4
+ ? value
5
+ : null;
6
+ }
7
+ function machineCode(value) {
8
+ if (typeof value !== 'string')
9
+ return undefined;
10
+ const code = value.trim();
11
+ return /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code) ? code : undefined;
12
+ }
13
+ function machineErrorCode(value) {
14
+ const exact = machineCode(value);
15
+ if (exact)
16
+ return exact;
17
+ if (typeof value !== 'string')
18
+ return undefined;
19
+ return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?=\s*[:,])/.exec(value.trim())?.[1];
20
+ }
21
+ function httpStatus(value) {
22
+ const status = Number(value);
23
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
24
+ }
25
+ /** Extract only machine-readable Action failure metadata; never copy the response body. */
26
+ export function summarizeActionError(error) {
27
+ const root = record(error);
28
+ const nested = record(root?.error);
29
+ const message = error instanceof Error
30
+ ? error.message
31
+ : typeof root?.message === 'string'
32
+ ? root.message
33
+ : typeof nested?.message === 'string'
34
+ ? nested.message
35
+ : typeof root?.error === 'string'
36
+ ? root.error
37
+ : typeof error === 'string' ? error : undefined;
38
+ const code = machineCode(root?.code)
39
+ ?? machineCode(nested?.code)
40
+ ?? machineErrorCode(root?.error);
41
+ const status = httpStatus(root?.http_status) ?? httpStatus(nested?.http_status);
42
+ return {
43
+ ...(code ? { code } : {}),
44
+ ...(status ? { httpStatus: status } : {}),
45
+ messagePresent: !!message,
46
+ ...(message ? { messageLength: message.length } : {}),
47
+ };
48
+ }
49
+ function explicitGameplayRejection(summary, codes) {
50
+ const code = summary.code?.toLowerCase();
51
+ const statusFromCode = code && /^http_(\d{3})$/.exec(code)?.[1];
52
+ const status = summary.httpStatus ?? (statusFromCode ? Number(statusFromCode) : undefined);
53
+ if (status !== undefined && status >= 500)
54
+ return false;
55
+ if (code && codes.has(code))
56
+ return true;
57
+ return status !== undefined && CLIENT_REJECTION_HTTP_STATUSES.has(status);
58
+ }
59
+ /** Unknown, transport, protocol, auth and server failures stay error-level. */
60
+ export function actionFailureDiagnosticSeverity(result, rejectionCodes = new Set()) {
61
+ const knownBoundary = (result.source === 'backend'
62
+ && (result.actionOutcome === 'confirmed' || result.actionOutcome === 'not_submitted')) || (result.source === 'local'
63
+ && result.actionOutcome === 'not_submitted');
64
+ return knownBoundary && explicitGameplayRejection(summarizeActionError(result.error), rejectionCodes)
65
+ ? 'warn'
66
+ : 'error';
67
+ }
@@ -0,0 +1,58 @@
1
+ import type { ActionCaller, ActionResult, ActionService, LatestAcceptedRuntimeState, ObservationProvider, ObservationQueryContext, ObservationResult, ScopeRef } from './contracts.js';
2
+ import { ControlCoordinator, type ControllerSpec } from './control-coordinator.js';
3
+ export interface ActionAdmissionOptions {
4
+ /** Revalidated immediately before ActionService is called. */
5
+ isAuthorized?: () => boolean;
6
+ /** Runtime-owned raw State view used by adapter-specific safety admission. */
7
+ latestAcceptedState?: () => LatestAcceptedRuntimeState | null;
8
+ }
9
+ /** Stable owner-local identity used by Action callers and lifecycle supervisors. */
10
+ export declare function actionControllerId(caller: ActionCaller, scope?: ScopeRef): string;
11
+ export type BehaviorActionCaller = Extract<ActionCaller, {
12
+ kind: 'behavior';
13
+ }>;
14
+ /**
15
+ * Builds the explicit controller reservation owned by the unified Behavior Host.
16
+ * Action callers cannot supply or raise control priority through an Action.
17
+ */
18
+ export declare function behaviorControllerSpec(caller: BehaviorActionCaller, spec: Omit<ControllerSpec, 'controllerId' | 'kind' | 'priority'>): ControllerSpec;
19
+ export declare class CapabilityConflictError extends Error {
20
+ constructor(capability: string);
21
+ }
22
+ /** Registry for pull-only information that does not need a pushed Event. */
23
+ export declare class ObservationRegistry {
24
+ private readonly providers;
25
+ register<Q, R>(provider: ObservationProvider<Q, R>): () => void;
26
+ capabilities(): string[];
27
+ query<Q, R>(capability: string, request: Q, scope: ScopeRef, context?: ObservationQueryContext): Promise<ObservationResult<R>>;
28
+ }
29
+ export interface RegisteredActionService<A = unknown, R = unknown> extends ActionService<A, R> {
30
+ readonly capability: string;
31
+ }
32
+ /** Shared action boundary for direct Agent calls and automated controllers. */
33
+ export declare class ActionRegistry {
34
+ private readonly services;
35
+ /** Public lifecycle facade used by the unified Behavior Host. */
36
+ readonly controls: ControlCoordinator;
37
+ private readonly abortController;
38
+ private readonly scopeControllers;
39
+ private readonly inFlight;
40
+ /** Provider-owned settlements no longer hold a control domain, but shutdown still drains them. */
41
+ private readonly detachedSettlements;
42
+ private stopping;
43
+ register<A, R>(service: RegisteredActionService<A, R>): () => void;
44
+ capabilities(): string[];
45
+ /** Revoke old-scope controllers; already-submitted providers remain a handoff barrier. */
46
+ activateScope(scope: ScopeRef): void;
47
+ private scopeController;
48
+ /** Fence this scope permanently; a subsequent game/room scope gets its own signal. */
49
+ closeScope(scope: ScopeRef, reason: string): void;
50
+ private closedScopeResult;
51
+ releaseController(controllerId: string, reason?: string): void;
52
+ releaseCaller(caller: ActionCaller, reason?: string, scope?: ScopeRef): void;
53
+ perform<A, R>(capability: string, action: A, scope: ScopeRef, caller: ActionCaller, options?: ActionAdmissionOptions): Promise<ActionResult<R>>;
54
+ /** Revoke new Action admission and abort every admitted provider request. */
55
+ beginStopping(reason?: string): void;
56
+ /** Wait until providers have observed cancellation and actually returned. */
57
+ waitForIdle(): Promise<void>;
58
+ }
@@ -0,0 +1,325 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { ControlCoordinator, WILDCARD_DOMAIN, } from './control-coordinator.js';
3
+ import { BEHAVIOR_CONTROLLER_PRIORITY } from './control/types.js';
4
+ const DEFAULT_IMPLICIT_SYSTEM_LEASE_MS = 1_000;
5
+ function isActionDispatch(value) {
6
+ return !!value
7
+ && typeof value === 'object'
8
+ && 'receipt' in value
9
+ && 'settled' in value
10
+ && value.settled instanceof Promise;
11
+ }
12
+ function scopedCallerId(kind, id, scope) {
13
+ return `${kind}:${encodeURIComponent(id ?? 'default')}`
14
+ + `@${encodeURIComponent(scope.sessionId)}/${encodeURIComponent(scope.segmentId)}`;
15
+ }
16
+ /** Stable owner-local identity used by Action callers and lifecycle supervisors. */
17
+ export function actionControllerId(caller, scope) {
18
+ if (caller.kind === 'agent' || caller.kind === 'user') {
19
+ if (!scope)
20
+ throw new Error(`${caller.kind} controller identity requires a runtime scope.`);
21
+ return scopedCallerId(caller.kind, caller.id, scope);
22
+ }
23
+ if (caller.kind === 'behavior') {
24
+ if (!caller.activationId.trim())
25
+ throw new Error('Behavior activation id must not be empty.');
26
+ if (!Number.isSafeInteger(caller.activationGeneration) || caller.activationGeneration <= 0) {
27
+ throw new Error('Behavior activation generation must be a positive safe integer.');
28
+ }
29
+ if (!['long', 'short', 'reflex'].includes(caller.layer)) {
30
+ throw new Error('Behavior control layer is invalid.');
31
+ }
32
+ return `behavior:${encodeURIComponent(caller.activationId)}`
33
+ + `@generation-${caller.activationGeneration}`;
34
+ }
35
+ return `${caller.kind}:${encodeURIComponent(caller.id)}`;
36
+ }
37
+ /**
38
+ * Builds the explicit controller reservation owned by the unified Behavior Host.
39
+ * Action callers cannot supply or raise control priority through an Action.
40
+ */
41
+ export function behaviorControllerSpec(caller, spec) {
42
+ const controllerId = actionControllerId(caller);
43
+ return {
44
+ ...spec,
45
+ controllerId,
46
+ kind: 'behavior',
47
+ priority: BEHAVIOR_CONTROLLER_PRIORITY[caller.layer],
48
+ metadata: {
49
+ ...spec.metadata,
50
+ behaviorActivationId: caller.activationId,
51
+ behaviorLayer: caller.layer,
52
+ behaviorActivationGeneration: caller.activationGeneration,
53
+ },
54
+ };
55
+ }
56
+ function deferredMessage(code) {
57
+ switch (code) {
58
+ case 'CONTROL_HELD': return 'The action is temporarily held by another local controller.';
59
+ case 'CONTROL_BUSY': return 'A conflicting action is already being submitted; recompute from fresh state and retry.';
60
+ case 'CONTROL_SCOPE_CHANGED': return 'The game scope changed before this action could be submitted.';
61
+ case 'CONTROL_NOT_READY': return 'The controller is not ready to submit actions.';
62
+ case 'CONTROL_STOPPING': return 'The local game runtime is stopping.';
63
+ case 'CONTROL_AUTHORITY_REVOKED': return 'The worker lost authority before this action reached the game provider.';
64
+ default: return 'The local control scheduler deferred this action.';
65
+ }
66
+ }
67
+ function deferredActionResult(scope, deferred) {
68
+ return {
69
+ scope,
70
+ actionId: randomUUID(),
71
+ status: 'deferred',
72
+ source: 'local',
73
+ actionOutcome: 'not_submitted',
74
+ error: {
75
+ code: deferred.code,
76
+ message: deferredMessage(deferred.code),
77
+ details: {
78
+ phase: 'control',
79
+ // Reversible preparation (for example an upload) may already have
80
+ // happened, but the actual gameplay Action endpoint was not called.
81
+ action_endpoint_called: false,
82
+ domains: [...deferred.domains],
83
+ reason: deferred.reason,
84
+ retryable: deferred.retryable,
85
+ },
86
+ },
87
+ };
88
+ }
89
+ export class CapabilityConflictError extends Error {
90
+ constructor(capability) {
91
+ super(`Capability already registered: ${capability}`);
92
+ this.name = 'CapabilityConflictError';
93
+ }
94
+ }
95
+ /** Registry for pull-only information that does not need a pushed Event. */
96
+ export class ObservationRegistry {
97
+ providers = new Map();
98
+ register(provider) {
99
+ if (this.providers.has(provider.capability)) {
100
+ throw new CapabilityConflictError(provider.capability);
101
+ }
102
+ this.providers.set(provider.capability, provider);
103
+ return () => {
104
+ if (this.providers.get(provider.capability) === provider) {
105
+ this.providers.delete(provider.capability);
106
+ }
107
+ };
108
+ }
109
+ capabilities() {
110
+ return [...this.providers.keys()].sort();
111
+ }
112
+ async query(capability, request, scope, context = {}) {
113
+ const provider = this.providers.get(capability);
114
+ if (!provider)
115
+ throw new Error(`Observation capability is not available: ${capability}`);
116
+ return provider.query(request, scope, context);
117
+ }
118
+ }
119
+ /** Shared action boundary for direct Agent calls and automated controllers. */
120
+ export class ActionRegistry {
121
+ services = new Map();
122
+ /** Public lifecycle facade used by the unified Behavior Host. */
123
+ controls = new ControlCoordinator();
124
+ abortController = new AbortController();
125
+ scopeControllers = new Map();
126
+ inFlight = new Set();
127
+ /** Provider-owned settlements no longer hold a control domain, but shutdown still drains them. */
128
+ detachedSettlements = new Set();
129
+ stopping = false;
130
+ register(service) {
131
+ if (this.services.has(service.capability)) {
132
+ throw new CapabilityConflictError(service.capability);
133
+ }
134
+ this.services.set(service.capability, service);
135
+ return () => {
136
+ if (this.services.get(service.capability) === service) {
137
+ this.services.delete(service.capability);
138
+ }
139
+ };
140
+ }
141
+ capabilities() {
142
+ return [...this.services.keys()].sort();
143
+ }
144
+ /** Revoke old-scope controllers; already-submitted providers remain a handoff barrier. */
145
+ activateScope(scope) {
146
+ this.controls.activateScope(scope);
147
+ }
148
+ scopeController(scope) {
149
+ const key = JSON.stringify([scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId]);
150
+ let controller = this.scopeControllers.get(key);
151
+ if (!controller) {
152
+ controller = new AbortController();
153
+ this.scopeControllers.set(key, controller);
154
+ }
155
+ return controller;
156
+ }
157
+ /** Fence this scope permanently; a subsequent game/room scope gets its own signal. */
158
+ closeScope(scope, reason) {
159
+ this.scopeController(scope).abort(new Error(reason));
160
+ }
161
+ closedScopeResult(scope) {
162
+ const signal = this.scopeController(scope).signal;
163
+ if (!signal.aborted)
164
+ return undefined;
165
+ return {
166
+ scope, actionId: randomUUID(), status: 'failure', source: 'local',
167
+ actionOutcome: 'not_submitted',
168
+ error: { code: signal.reason.message, message: 'This scope has ended; the Action was not submitted.' },
169
+ };
170
+ }
171
+ releaseController(controllerId, reason = 'released') {
172
+ this.controls.release(controllerId, { reason });
173
+ }
174
+ releaseCaller(caller, reason = 'released', scope) {
175
+ this.releaseController(actionControllerId(caller, scope), reason);
176
+ }
177
+ async perform(capability, action, scope, caller, options = {}) {
178
+ if (this.stopping)
179
+ throw new Error('Action registry is stopping.');
180
+ const closed = this.closedScopeResult(scope);
181
+ if (closed)
182
+ return closed;
183
+ const service = this.services.get(capability);
184
+ if (!service)
185
+ throw new Error(`Action capability is not available: ${capability}`);
186
+ const descriptor = service.describeControl?.(action, scope, caller);
187
+ const domains = descriptor?.domains === undefined
188
+ ? [WILDCARD_DOMAIN]
189
+ : [...descriptor.domains];
190
+ const controllerId = actionControllerId(caller, scope);
191
+ if (options.isAuthorized && !options.isAuthorized()) {
192
+ return deferredActionResult(scope, {
193
+ code: 'CONTROL_AUTHORITY_REVOKED',
194
+ domains,
195
+ reason: 'worker_authority_revoked',
196
+ retryable: false,
197
+ });
198
+ }
199
+ const existing = this.controls.snapshot().controllers.find((controller) => controller.controllerId === controllerId);
200
+ const terminal = existing?.state === 'released' || existing?.state === 'expired';
201
+ const mayReplaceTerminal = caller.kind === 'agent'
202
+ || caller.kind === 'user'
203
+ || caller.kind === 'system';
204
+ // Behavior controllers are never synthesized from their first Action.
205
+ // Their Host must reserve the full claim and establish precedence before
206
+ // any provider may see work.
207
+ if (caller.kind !== 'behavior' && (!existing || (terminal && mayReplaceTerminal))) {
208
+ const activity = caller.kind === 'agent' || caller.kind === 'user' || caller.kind === 'system';
209
+ const spec = {
210
+ controllerId,
211
+ kind: caller.kind,
212
+ scope,
213
+ // Activity controllers declare wildcard authority but claim only the
214
+ // domains they actually touch. Capability workers may start with a
215
+ // conservative wildcard controller and narrow it later.
216
+ domains: [WILDCARD_DOMAIN],
217
+ ready: true,
218
+ holdMode: 'all_or_nothing',
219
+ ...(activity
220
+ ? {
221
+ lifecycle: 'activity_lease',
222
+ activityLeaseMs: caller.kind === 'system'
223
+ ? DEFAULT_IMPLICIT_SYSTEM_LEASE_MS
224
+ : descriptor?.agentLeaseMs,
225
+ }
226
+ : { lifecycle: 'persistent', metadata: { implicit: true } }),
227
+ };
228
+ this.controls.registerController(spec);
229
+ }
230
+ let receiptResolved = false;
231
+ let resolveReceipt;
232
+ let rejectReceipt;
233
+ const receipt = new Promise((resolve, reject) => {
234
+ resolveReceipt = (result) => {
235
+ if (receiptResolved)
236
+ return;
237
+ receiptResolved = true;
238
+ resolve(result);
239
+ };
240
+ rejectReceipt = (error) => {
241
+ if (receiptResolved)
242
+ return;
243
+ receiptResolved = true;
244
+ reject(error);
245
+ };
246
+ });
247
+ const operation = this.controls.runAction({
248
+ controllerId,
249
+ scope,
250
+ domains,
251
+ handoffWaitMs: descriptor?.handoffTimeoutMs,
252
+ execute: async (controlContext) => {
253
+ const revalidate = () => {
254
+ const closed = this.closedScopeResult(scope);
255
+ if (closed)
256
+ return { status: 'deferred', result: closed };
257
+ if (options.isAuthorized && !options.isAuthorized()) {
258
+ this.controls.release(controllerId, { reason: 'worker_authority_revoked' });
259
+ return {
260
+ status: 'deferred',
261
+ result: deferredActionResult(scope, {
262
+ code: 'CONTROL_AUTHORITY_REVOKED',
263
+ domains,
264
+ reason: 'worker_authority_revoked',
265
+ retryable: false,
266
+ }),
267
+ };
268
+ }
269
+ const deferred = controlContext.revalidate();
270
+ return deferred
271
+ ? { status: 'deferred', result: deferredActionResult(scope, deferred) }
272
+ : { status: 'authorized' };
273
+ };
274
+ const authority = revalidate();
275
+ if (authority.status === 'deferred')
276
+ return authority.result;
277
+ const providerResult = await service.perform(action, scope, caller, {
278
+ signal: AbortSignal.any([this.abortController.signal, this.scopeController(scope).signal]),
279
+ revalidate,
280
+ latestAcceptedState: options.latestAcceptedState ?? (() => null),
281
+ });
282
+ if (isActionDispatch(providerResult)) {
283
+ resolveReceipt(providerResult.receipt);
284
+ const settlement = providerResult.settled;
285
+ this.detachedSettlements.add(settlement);
286
+ void settlement.catch(() => { }).finally(() => {
287
+ this.detachedSettlements.delete(settlement);
288
+ });
289
+ // Dispatch transfers the accepted submission to the provider. The
290
+ // controller may enqueue its next physical Action immediately;
291
+ // provider-owned FIFO still controls endpoint start order. Only
292
+ // Runtime shutdown continues to own the real provider settlement.
293
+ return providerResult.receipt;
294
+ }
295
+ return providerResult;
296
+ },
297
+ });
298
+ this.inFlight.add(operation);
299
+ void operation.then((controlled) => resolveReceipt(controlled.status === 'executed'
300
+ ? controlled.value
301
+ : deferredActionResult(scope, controlled)), rejectReceipt).finally(() => {
302
+ this.inFlight.delete(operation);
303
+ });
304
+ // Attach a rejection observer immediately. Detached provider settlement
305
+ // can fail after its caller has already received a receipt.
306
+ void operation.catch(() => { });
307
+ return receipt;
308
+ }
309
+ /** Revoke new Action admission and abort every admitted provider request. */
310
+ beginStopping(reason = 'runtime_stopping') {
311
+ if (this.stopping)
312
+ return;
313
+ this.stopping = true;
314
+ this.controls.beginStopping();
315
+ this.abortController.abort(new Error(reason));
316
+ }
317
+ /** Wait until providers have observed cancellation and actually returned. */
318
+ async waitForIdle() {
319
+ while (this.inFlight.size > 0 || this.detachedSettlements.size > 0) {
320
+ await Promise.allSettled([...this.inFlight]);
321
+ await Promise.allSettled([...this.detachedSettlements]);
322
+ }
323
+ await this.controls.waitForIdle();
324
+ }
325
+ }
@@ -0,0 +1,121 @@
1
+ /** Transport-neutral capability contracts for the game-neutral Runtime. */
2
+ import type { StoredStateFrame } from './state/history/contracts.js';
3
+ export interface ScopeRef {
4
+ adapterId: string;
5
+ accountId: string;
6
+ sessionId: string;
7
+ segmentId: string;
8
+ }
9
+ export interface ObservationResult<T> {
10
+ scope: ScopeRef;
11
+ capability: string;
12
+ observedAt?: string;
13
+ receivedAt: string;
14
+ freshness: 'fresh' | 'stale' | 'unknown';
15
+ value: T;
16
+ provenance?: Record<string, unknown>;
17
+ }
18
+ export interface ObservationQueryContext {
19
+ /** Present when one Epoch Plugin calls another capability while processing E. */
20
+ epochSeq?: number;
21
+ /** Exact accepted Runtime State frame for E; never a later mutable provider snapshot. */
22
+ stateFrame?: Readonly<StoredStateFrame<Record<string, unknown>>>;
23
+ }
24
+ /** Runtime-owned control layer for one unified Behavior activation. */
25
+ export type BehaviorControlLayer = 'long' | 'short' | 'reflex';
26
+ /**
27
+ * Pull-only information such as a full map, inventory, object detail, or a
28
+ * bounded history page. Querying a provider does not implicitly create an
29
+ * Event.
30
+ */
31
+ export interface ObservationProvider<Q = unknown, R = unknown> {
32
+ readonly capability: string;
33
+ query(request: Q, scope: ScopeRef, context: ObservationQueryContext): Promise<ObservationResult<R>>;
34
+ }
35
+ export type ActionCaller = {
36
+ kind: 'agent';
37
+ id?: string;
38
+ } | {
39
+ kind: 'behavior';
40
+ /** Unique logical activation; module ids are deliberately not controller ids. */
41
+ activationId: string;
42
+ layer: BehaviorControlLayer;
43
+ /** Fresh module instance created when a suspended activation restarts. */
44
+ activationGeneration: number;
45
+ } | {
46
+ kind: 'user';
47
+ id?: string;
48
+ } | {
49
+ kind: 'system';
50
+ id: string;
51
+ };
52
+ /**
53
+ * Logical control domains required atomically by an Action. Actions in
54
+ * unrelated domains can be controlled independently. `*` is a real wildcard;
55
+ * services that omit a descriptor are conservatively treated as `*`.
56
+ */
57
+ export interface ActionControlDescriptor {
58
+ domains: string[];
59
+ /** Adapter policy for a direct Agent's inactivity hold on these domains. */
60
+ agentLeaseMs?: number;
61
+ /** Maximum time a takeover may wait for an already-submitted lower action. */
62
+ handoffTimeoutMs?: number;
63
+ }
64
+ export interface ActionResult<T = unknown> {
65
+ scope: ScopeRef;
66
+ actionId: string;
67
+ /** `deferred` is local control scheduling, never a backend rejection. */
68
+ status: 'success' | 'partial' | 'deferred' | 'failure';
69
+ /** Which boundary produced this result; backend payloads remain unwrapped in `error`. */
70
+ source?: 'backend' | 'transport' | 'protocol' | 'local';
71
+ /** Whether the gameplay Action endpoint definitely handled this attempt. */
72
+ actionOutcome?: 'confirmed' | 'not_submitted' | 'unknown';
73
+ value?: T;
74
+ error?: unknown;
75
+ effects?: Array<Record<string, unknown>>;
76
+ }
77
+ /**
78
+ * A provider-owned asynchronous Action submission.
79
+ *
80
+ * `receipt` transfers ownership to the provider without claiming that the
81
+ * gameplay endpoint has acknowledged the Action. `settled` retains the real
82
+ * HTTP/ACK result inside the provider boundary. The Runtime releases the
83
+ * controller's submission fence at `receipt`; providers that accept ordered
84
+ * automated Decisions must preserve their endpoint-start FIFO internally.
85
+ * Runtime keeps shutdown drain ownership until `settled` completes.
86
+ */
87
+ export interface ActionDispatch<T = unknown> {
88
+ receipt: ActionResult<T>;
89
+ settled: Promise<ActionResult<T>>;
90
+ }
91
+ export type ActionServiceResult<T = unknown> = ActionResult<T> | ActionDispatch<T>;
92
+ export type ActionExecutionRevalidation = {
93
+ status: 'authorized';
94
+ } | {
95
+ status: 'deferred';
96
+ /** Registry-owned local result; it is never a rewritten backend error. */
97
+ result: ActionResult<never>;
98
+ };
99
+ export interface LatestAcceptedRuntimeState {
100
+ readonly epochSeq: number;
101
+ readonly state: Readonly<Record<string, unknown>>;
102
+ }
103
+ export interface ActionExecutionContext {
104
+ /** Aborted when the owning runtime is stopping. */
105
+ signal: AbortSignal;
106
+ /**
107
+ * Recheck the exact admitted worker/controller/scope after asynchronous,
108
+ * reversible preparation and immediately before an irreversible game call.
109
+ */
110
+ revalidate(): ActionExecutionRevalidation;
111
+ /**
112
+ * Latest raw State accepted for this scope, independent of plugin progress.
113
+ * Adapter Action providers use it only for final local safety admission.
114
+ */
115
+ latestAcceptedState(): LatestAcceptedRuntimeState | null;
116
+ }
117
+ /** Behavior automation, legacy automation, and direct Agent tools share this boundary. */
118
+ export interface ActionService<A = unknown, R = unknown> {
119
+ describeControl?(action: A, scope: ScopeRef, caller: ActionCaller): ActionControlDescriptor;
120
+ perform(action: A, scope: ScopeRef, caller: ActionCaller, context: ActionExecutionContext): ActionServiceResult<R> | Promise<ActionServiceResult<R>>;
121
+ }
@@ -0,0 +1,2 @@
1
+ /** Transport-neutral capability contracts for the game-neutral Runtime. */
2
+ export {};