@myclaw163/clawclaw-cli 0.9.1 → 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 (216) 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 +27 -40
  7. package/docs/custom-modules/api-reference.md +132 -273
  8. package/docs/custom-modules/behavior.md +185 -75
  9. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +46 -806
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +18 -19
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +54 -48
  19. package/docs/runtime/components-and-boundaries.md +87 -137
  20. package/docs/runtime/events-and-state.md +52 -17
  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 +12 -9
  26. package/docs/user-guide/api-reference.md +132 -180
  27. package/docs/user-guide/behavior.md +175 -65
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +46 -789
  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 +9 -14
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +50 -48
  37. package/skills/clawclaw/references/BEHAVIORS.md +45 -65
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +65 -87
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
  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 +49 -104
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +18 -25
  53. package/src/commands/module-runtime-control.ts +113 -0
  54. package/src/commands/perception.ts +23 -4
  55. package/src/commands/strategy.ts +2 -0
  56. package/src/commands/trigger.ts +1 -1
  57. package/src/lib/capability-load-diagnostics.ts +3 -3
  58. package/src/lib/perception-config.ts +18 -6
  59. package/src/lib/runtime-cadence-config.ts +16 -0
  60. package/src/lib/workspace-runtime-lock.ts +3 -46
  61. package/src/pipeline/canonical-event-presentation.ts +23 -124
  62. package/src/pipeline/event-format.ts +12 -21
  63. package/src/pipeline/event-hints.ts +6 -6
  64. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  65. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  66. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  67. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  68. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  69. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  70. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  71. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  72. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  73. package/src/runtime/clawclaw/owner.ts +67 -8
  74. package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
  75. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  76. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  77. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  78. package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
  79. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  82. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  83. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  84. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
  85. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
  86. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  87. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  88. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  89. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
  90. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
  91. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
  92. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  93. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  94. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  95. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
  96. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  97. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  98. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  99. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  100. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  101. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  102. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  103. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  104. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  105. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  106. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  107. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
  108. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
  109. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
  110. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
  111. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
  112. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  113. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
  114. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  115. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  116. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  117. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  118. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
  119. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  120. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  121. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  122. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  123. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  124. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  125. package/src/runtime/clawclaw/runtime-state.ts +12 -1
  126. package/src/runtime/clawclaw/runtime.ts +11 -3
  127. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
  128. package/src/runtime/clawclaw/strategy-memory.ts +1 -0
  129. package/src/runtime/clawclaw-event-catalog.ts +17 -17
  130. package/src/runtime/framework/action-diagnostics.ts +3 -83
  131. package/src/runtime/framework/capability-registry.ts +2 -395
  132. package/src/runtime/framework/contracts.ts +2 -144
  133. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  134. package/src/runtime/framework/control/domain-set.ts +2 -81
  135. package/src/runtime/framework/control/index.ts +1 -3
  136. package/src/runtime/framework/control/types.ts +2 -191
  137. package/src/runtime/framework/control-coordinator.ts +2 -11
  138. package/src/runtime/framework/events/event-catalog.ts +2 -74
  139. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  140. package/src/runtime/framework/events/event-ingress.ts +2 -99
  141. package/src/runtime/framework/events/event-repository.ts +2 -82
  142. package/src/runtime/framework/events/index.ts +2 -7
  143. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  144. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  145. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  146. package/src/runtime/framework/events/test-helpers.ts +1 -1
  147. package/src/runtime/framework/events/types.ts +2 -312
  148. package/src/runtime/framework/index.ts +3 -7
  149. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  150. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  151. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  152. package/src/runtime/framework/mailbox/identity.ts +2 -38
  153. package/src/runtime/framework/mailbox/index.ts +1 -7
  154. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  155. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  156. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  157. package/src/runtime/framework/mailbox/types.ts +2 -145
  158. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  159. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  160. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  161. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  162. package/src/runtime/framework/participation-manager.ts +2 -253
  163. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  164. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  165. package/src/runtime/framework/plugins/contracts.ts +2 -388
  166. package/src/runtime/framework/plugins/index.ts +1 -4
  167. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  168. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  169. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
  170. package/src/runtime/framework/runtime.ts +5 -1843
  171. package/src/runtime/framework/serial-task-queue.ts +2 -14
  172. package/src/runtime/framework/state/contracts.ts +2 -49
  173. package/src/runtime/framework/state/current-state-store.ts +2 -184
  174. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  175. package/src/runtime/framework/state/freshness.ts +2 -72
  176. package/src/runtime/framework/state/history/contracts.ts +2 -158
  177. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  178. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  179. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  180. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  181. package/src/runtime/framework/state/index.ts +1 -13
  182. package/src/runtime/framework/state/state-ingress.ts +2 -95
  183. package/src/runtime/framework/state/state-provider.ts +2 -62
  184. package/src/runtime/framework/state/types.ts +2 -155
  185. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  186. package/src/runtime/mailbox-host-relay.ts +1 -326
  187. package/src/runtime/observability/detail-capture.ts +4 -108
  188. package/src/runtime/observability/process-timing.ts +2 -59
  189. package/src/runtime/observability/recorder.ts +2 -238
  190. package/src/runtime/observability/redaction.ts +2 -181
  191. package/src/runtime/observability/reporter.ts +2 -154
  192. package/src/runtime/observability/sinks.ts +2 -135
  193. package/src/runtime/observability/types.ts +2 -92
  194. package/src/runtime/owner-control.ts +45 -315
  195. package/src/runtime/parent-process-watch.ts +1 -51
  196. package/src/runtime/process-identity.ts +1 -72
  197. package/src/sdk/behavior-plugin/index.ts +13 -4
  198. package/src/sdk/index.ts +44 -3
  199. package/src/sdk/module-input/index.ts +5 -0
  200. package/src/sdk/perception-plugin/index.ts +9 -5
  201. package/src/sdk/perception-plugin/module.ts +25 -6
  202. package/src/sdk/perception-plugin/reaction.ts +1 -1
  203. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  204. package/src/sdk/perception-plugin/reminder.ts +2 -1
  205. package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
  206. package/src/sdk/strategy-memory.ts +1 -0
  207. package/src/sdk/strategy-plugin/index.ts +36 -0
  208. package/src/sdk/trigger-plugin/index.ts +4 -3
  209. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  210. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  211. package/docs/custom-modules/trigger.md +0 -295
  212. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  213. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
  214. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
  215. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  216. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -26,18 +26,20 @@ export const CLAWCLAW_VISUAL_EVENT_TYPES = [
26
26
  ] as const;
27
27
 
28
28
  export type ClawclawVisualEventType = typeof CLAWCLAW_VISUAL_EVENT_TYPES[number];
29
+ export type ClawclawEventDelivery = EventDeliveryClass
30
+ | Readonly<Pick<EventCatalogEntry, 'deliveryClass' | 'wakeAgent'>>;
29
31
  export type ClawclawVisualEventDelivery = EventDeliveryClass
30
- | Readonly<Partial<Record<string, EventDeliveryClass>>>;
32
+ | Readonly<Partial<Record<string, ClawclawEventDelivery>>>;
31
33
 
32
34
  export interface ClawclawEventCatalogOptions {
33
- /** Defaults to monitor_and_events so visual facts wake the default Agent surface. */
35
+ /** Defaults to visible notifications while preserving the producer's wakeAgent choice. */
34
36
  visualEventDelivery?: ClawclawVisualEventDelivery;
35
37
  /** Additional visual Event types declared by selected user perception modules. */
36
38
  visualEventTypes?: readonly string[];
37
39
  /** Events declared by the enabled Intent and Strategy manifests at startup. */
38
40
  behaviorEventTypes?: readonly string[];
39
- /** Own notification types from equipped reaction perceptions. */
40
- reactionEventTypes?: readonly string[];
41
+ /** Own notification types from equipped unified perceptions. */
42
+ perceptionEventTypes?: readonly string[];
41
43
  }
42
44
 
43
45
  /**
@@ -183,8 +185,8 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
183
185
  'players_changed',
184
186
  'reminder.task',
185
187
  'reminder.speech',
188
+ 'perception.module_failed',
186
189
  'perception.behavior_unavailable',
187
- 'perception.reaction_failed',
188
190
  'emergency_countdown_warning',
189
191
  'ability.ready',
190
192
  'ability.remaining_uses_changed',
@@ -241,21 +243,19 @@ export const CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES = new Set<string>([
241
243
  ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES,
242
244
  ]);
243
245
 
244
- /** Intentionally empty for the current ClawClaw Agent contract. */
245
- export const CLAWCLAW_EVENTS_ONLY_EVENT_TYPES = new Set<string>();
246
-
247
246
  function visualDelivery(
248
247
  config: ClawclawVisualEventDelivery | undefined,
249
248
  type: string,
250
- ): EventDeliveryClass {
251
- if (typeof config === 'string') return config;
252
- return config?.[type] ?? 'monitor_and_events';
249
+ ): Pick<EventCatalogEntry, 'deliveryClass' | 'wakeAgent'> {
250
+ const configured = typeof config === 'string' ? config : config?.[type];
251
+ return typeof configured === 'object' ? { ...configured }
252
+ : { deliveryClass: configured ?? 'monitor_and_events' };
253
253
  }
254
254
 
255
255
  function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[] {
256
- const perceptionOutputTypes = new Set(options.reactionEventTypes ?? []);
256
+ const perceptionOutputTypes = new Set(options.perceptionEventTypes ?? []);
257
257
  const ownOutputDelivery = (type: string) => perceptionOutputTypes.has(type)
258
- ? visualDelivery(options.visualEventDelivery, type) : 'monitor_and_events' as const;
258
+ ? visualDelivery(options.visualEventDelivery, type) : { deliveryClass: 'monitor_and_events' as const };
259
259
  const visualEventTypes = [...new Set([
260
260
  ...CLAWCLAW_VISUAL_EVENT_TYPES,
261
261
  ...(options.visualEventTypes ?? []),
@@ -264,7 +264,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
264
264
  ...CLAWCLAW_FIXED_EVENT_TYPES,
265
265
  ...visualEventTypes,
266
266
  ]);
267
- const behaviorEventTypes = [...new Set([...(options.behaviorEventTypes ?? []), ...(options.reactionEventTypes ?? [])])]
267
+ const behaviorEventTypes = [...new Set([...(options.behaviorEventTypes ?? []), ...(options.perceptionEventTypes ?? [])])]
268
268
  .filter((type) => !fixedAndVisualTypes.has(type))
269
269
  .sort();
270
270
  return [
@@ -276,7 +276,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
276
276
  ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.map((type) => ({
277
277
  type,
278
278
  producer: 'local_synth' as const,
279
- deliveryClass: ownOutputDelivery(type),
279
+ ...ownOutputDelivery(type),
280
280
  })),
281
281
  ...CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES.map((type) => ({
282
282
  type,
@@ -291,12 +291,12 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
291
291
  ...visualEventTypes.map((type) => ({
292
292
  type,
293
293
  producer: 'local_synth' as const,
294
- deliveryClass: visualDelivery(options.visualEventDelivery, type),
294
+ ...visualDelivery(options.visualEventDelivery, type),
295
295
  })),
296
296
  ...behaviorEventTypes.map((type) => ({
297
297
  type,
298
298
  producer: 'local_synth' as const,
299
- deliveryClass: ownOutputDelivery(type),
299
+ ...ownOutputDelivery(type),
300
300
  })),
301
301
  ];
302
302
  }
@@ -1,12 +1,6 @@
1
+ import { actionFailureDiagnosticSeverity as classify } from '@myclaw163/game-agent-runtime/framework/action-diagnostics.js';
1
2
  import type { ActionResult } from './contracts.js';
2
-
3
- export interface ActionErrorDiagnosticSummary {
4
- readonly code?: string;
5
- readonly httpStatus?: number;
6
- readonly messagePresent: boolean;
7
- readonly messageLength?: number;
8
- }
9
-
3
+ export { summarizeActionError, type ActionErrorDiagnosticSummary } from '@myclaw163/game-agent-runtime/framework/action-diagnostics.js';
10
4
  const EXPLICIT_GAMEPLAY_REJECTIONS = new Set([
11
5
  'action_failed',
12
6
  'already_spoke',
@@ -70,78 +64,4 @@ const EXPLICIT_GAMEPLAY_REJECTIONS = new Set([
70
64
  'you_are_dead',
71
65
  ]);
72
66
 
73
- const CLIENT_REJECTION_HTTP_STATUSES = new Set([400, 409, 422]);
74
-
75
- function record(value: unknown): Record<string, unknown> | null {
76
- return value && typeof value === 'object' && !Array.isArray(value)
77
- ? value as Record<string, unknown>
78
- : null;
79
- }
80
-
81
- function machineCode(value: unknown): string | undefined {
82
- if (typeof value !== 'string') return undefined;
83
- const code = value.trim();
84
- return /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code) ? code : undefined;
85
- }
86
-
87
- function machineErrorCode(value: unknown): string | undefined {
88
- const exact = machineCode(value);
89
- if (exact) return exact;
90
- if (typeof value !== 'string') return undefined;
91
- return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?=\s*[:,])/.exec(value.trim())?.[1];
92
- }
93
-
94
- function httpStatus(value: unknown): number | undefined {
95
- const status = Number(value);
96
- return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
97
- }
98
-
99
- /** Extract only machine-readable Action failure metadata; never copy the response body. */
100
- export function summarizeActionError(error: unknown): ActionErrorDiagnosticSummary {
101
- const root = record(error);
102
- const nested = record(root?.error);
103
- const message = error instanceof Error
104
- ? error.message
105
- : typeof root?.message === 'string'
106
- ? root.message
107
- : typeof nested?.message === 'string'
108
- ? nested.message
109
- : typeof root?.error === 'string'
110
- ? root.error
111
- : typeof error === 'string' ? error : undefined;
112
- const code = machineCode(root?.code)
113
- ?? machineCode(nested?.code)
114
- ?? machineErrorCode(root?.error);
115
- const status = httpStatus(root?.http_status) ?? httpStatus(nested?.http_status);
116
- return {
117
- ...(code ? { code } : {}),
118
- ...(status ? { httpStatus: status } : {}),
119
- messagePresent: !!message,
120
- ...(message ? { messageLength: message.length } : {}),
121
- };
122
- }
123
-
124
- function explicitGameplayRejection(summary: ActionErrorDiagnosticSummary): boolean {
125
- const code = summary.code?.toLowerCase();
126
- const statusFromCode = code && /^http_(\d{3})$/.exec(code)?.[1];
127
- const status = summary.httpStatus ?? (statusFromCode ? Number(statusFromCode) : undefined);
128
- if (status !== undefined && status >= 500) return false;
129
- if (code && EXPLICIT_GAMEPLAY_REJECTIONS.has(code)) return true;
130
- return status !== undefined && CLIENT_REJECTION_HTTP_STATUSES.has(status);
131
- }
132
-
133
- /** Unknown, transport, protocol, auth and server failures stay error-level. */
134
- export function actionFailureDiagnosticSeverity(
135
- result: Pick<ActionResult, 'source' | 'actionOutcome' | 'error'>,
136
- ): 'warn' | 'error' {
137
- const knownBoundary = (
138
- result.source === 'backend'
139
- && (result.actionOutcome === 'confirmed' || result.actionOutcome === 'not_submitted')
140
- ) || (
141
- result.source === 'local'
142
- && result.actionOutcome === 'not_submitted'
143
- );
144
- return knownBoundary && explicitGameplayRejection(summarizeActionError(result.error))
145
- ? 'warn'
146
- : 'error';
147
- }
67
+ export const actionFailureDiagnosticSeverity = (result: Pick<ActionResult, 'source' | 'actionOutcome' | 'error'>) => classify(result, EXPLICIT_GAMEPLAY_REJECTIONS);
@@ -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';