@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
@@ -1,277 +1,19 @@
1
- import type {
2
- BehaviorDecision,
3
- BehaviorInput,
4
- BehaviorReadApi,
5
- ClawclawBehavior,
6
- } from '../../../../sdk/behavior-plugin/index.js';
1
+ import { StrategyScriptRunner, type StrategyScriptRunnerOptions } from '@myclaw163/game-agent-runtime/strategy/strategy-script-runner.js';
2
+ import type { BehaviorInput, BehaviorDecision, BehaviorReadApi } from '../../../../sdk/behavior-plugin/index.js';
7
3
  import { normalizeBehaviorDecision } from '../../behavior-decision.js';
8
4
  import { createBehaviorReadApi } from '../../behavior-read-api.js';
9
5
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
10
- import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contracts.js';
6
+ import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
11
7
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
12
- import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
13
- import { DetailCapture } from '../../../observability/detail-capture.js';
14
- import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
15
-
16
- export interface ClawclawBehaviorRunnerOptions {
17
- readonly snapshotStore?: BehaviorSnapshotStore;
18
- readonly behaviorId: string;
19
- readonly activationId: string;
20
- readonly instanceGeneration: number;
21
- readonly prepared: PreparedClawclawBehavior;
22
- readonly diagnostic?: (
23
- name: string,
24
- attributes?: Readonly<Record<string, unknown>>,
25
- severity?: RuntimeDiagnosticSeverity,
26
- ) => void;
27
- readonly isActive: () => boolean;
28
- readonly diagnosticsEnabled?: boolean;
29
- }
30
-
31
- function errorCode(error: unknown): string {
32
- const message = error instanceof Error ? error.message : String(error);
33
- return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message)
34
- ? message
35
- : 'BEHAVIOR_DECIDE_FAILED';
36
- }
37
-
38
- function abortError(signal: AbortSignal): Error {
39
- return signal.reason instanceof Error
40
- ? signal.reason
41
- : new Error('behavior_decide_aborted');
42
- }
43
-
44
- /**
45
- * One Activation-generation runner. Serial uses one owner-thread instance;
46
- * parallel creates an isolated module instance for every computation.
47
- */
48
- export class ClawclawBehaviorRunner {
49
- readonly behaviorId: string;
50
- readonly activationId: string;
51
- readonly instanceGeneration: number;
52
- readonly prepared: PreparedClawclawBehavior;
53
-
54
- private serialModule?: ClawclawBehavior;
55
- private serialTail = Promise.resolve();
56
- private readonly parallelLifecycle = new AbortController();
57
- private parallelExecutor?: ThreadBehaviorExecutor;
58
- private parallelReady?: Promise<void>;
59
- private parallelStop?: Promise<void>;
60
- private stopped = false;
61
- private readonly capture: DetailCapture;
62
-
63
- constructor(private readonly options: ClawclawBehaviorRunnerOptions) {
64
- this.behaviorId = options.behaviorId;
65
- this.activationId = options.activationId;
66
- this.instanceGeneration = options.instanceGeneration;
67
- this.prepared = options.prepared;
68
- this.serialModule = options.prepared.module;
69
- this.capture = new DetailCapture('behavior_io', options.diagnostic);
70
- }
71
-
72
- get execution(): 'parallel' | 'serial' {
73
- return this.prepared.manifest.execution ?? 'parallel';
74
- }
75
-
76
- /** Start/import Workers at activation, outside per-decision computation deadlines. */
77
- async prepare(): Promise<void> {
78
- if (!this.prepared.source) return;
79
- this.ensureThreadExecutor();
80
- await this.parallelReady;
81
- }
82
-
83
- get everyTicks(): number {
84
- return this.prepared.manifest.everyTicks ?? 1;
85
- }
86
-
87
- diagnosticSnapshot(): Readonly<Record<string, unknown>> {
88
- const pool = this.parallelExecutor?.snapshot();
89
- return Object.freeze({
90
- execution: this.execution,
91
- every_ticks: this.everyTicks,
92
- stopped: this.stopped,
93
- worker_pool: pool
94
- ? {
95
- state: pool.state,
96
- worker_count: pool.workerCount,
97
- idle_worker_count: pool.idleWorkerCount,
98
- busy_worker_count: pool.busyWorkerCount,
99
- queued_request_count: pool.queuedRequestCount,
100
- in_flight_request_count: pool.inFlightRequestCount,
101
- started_worker_count: pool.startedWorkerCount,
102
- retired_worker_count: pool.retiredWorkerCount,
103
- worker_heap_used_bytes: pool.workerHeapUsedBytes,
104
- peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes,
105
- }
106
- : null,
107
- });
108
- }
109
-
110
- decideSerial(
111
- input: Readonly<BehaviorInput>,
112
- signal: AbortSignal,
113
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
114
- ): Promise<BehaviorDecision> {
115
- return this.traceDecision(input, observationSnapshot, signal, () => this.decideSerialInternal(input, signal, observationSnapshot));
116
- }
117
-
118
- private decideSerialInternal(input: Readonly<BehaviorInput>, signal: AbortSignal,
119
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>): Promise<BehaviorDecision> {
120
- if (this.prepared.source) {
121
- return this.enqueue(() => this.invokeThread(input, signal, observationSnapshot));
122
- }
123
- const module = this.serialModule;
124
- if (!module) return Promise.reject(new Error('behavior_serial_module_missing'));
125
- return this.enqueue(() => this.invoke(module, input, signal, observationSnapshot));
126
- }
127
-
128
- decideParallel(
129
- input: Readonly<BehaviorInput>,
130
- signal: AbortSignal,
131
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
132
- ): Promise<BehaviorDecision> {
133
- return this.traceDecision(input, observationSnapshot, signal, () => this.invokeThread(input, signal, observationSnapshot));
134
- }
135
-
136
- private traceDecision(input: Readonly<BehaviorInput>, observationSnapshot: Readonly<ClawclawBehaviorObservationSnapshot> | undefined,
137
- signal: AbortSignal, invoke: () => Promise<BehaviorDecision>): Promise<BehaviorDecision> {
138
- if (!this.capture.enabled) return invoke();
139
- return this.capture.run('decide', {
140
- behavior_id: this.behaviorId, activation_id: this.activationId, instance_generation: this.instanceGeneration,
141
- epoch_id: input.epochId, tick: input.gameState.tick, game_id: input.gameState.game_id,
142
- session_id: input.scope.sessionId, segment_id: input.scope.segmentId, execution: this.execution,
143
- }, { frame: input, observation: observationSnapshot }, invoke, signal);
144
- }
145
-
146
- stop(reason: 'switched' | 'scope_ended' | 'shutdown' = 'switched'): Promise<void> {
147
- if (this.parallelStop) return this.parallelStop;
148
- this.stopped = true;
149
- this.parallelLifecycle.abort(new Error(`behavior_runner_stopped:${reason}`));
150
- const executor = this.parallelExecutor;
151
- this.parallelExecutor = undefined;
152
- this.parallelReady = undefined;
153
- this.parallelStop = executor?.stop(reason) ?? Promise.resolve();
154
- return this.parallelStop;
155
- }
156
-
157
- private async invokeThread(
158
- input: Readonly<BehaviorInput>,
159
- signal: AbortSignal,
160
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
161
- ): Promise<BehaviorDecision> {
162
- if (this.stopped) throw new Error('behavior_runner_stopped');
163
- if (signal.aborted) throw abortError(signal);
164
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
165
- const executor = this.ensureThreadExecutor();
166
- await this.parallelReady;
167
- if (this.stopped) throw new Error('behavior_runner_stopped');
168
- if (signal.aborted) throw abortError(signal);
169
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
170
- const decision = await executor.update(input, signal, observationSnapshot);
171
- if (signal.aborted) throw abortError(signal);
172
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
173
- return decision;
174
- }
175
-
176
- private ensureThreadExecutor(): ThreadBehaviorExecutor {
177
- if (this.parallelExecutor) return this.parallelExecutor;
178
- const source = this.prepared.source;
179
- if (!source) throw new Error('behavior_thread_source_missing');
180
- if (source.id !== this.behaviorId || source.execution !== this.execution) {
181
- throw new Error('behavior_thread_source_invalid');
182
- }
183
- const executor = new ThreadBehaviorExecutor({
184
- fixedWorkers: true,
185
- snapshotStore: this.options.snapshotStore,
186
- source,
187
- diagnostic: this.options.diagnostic,
188
- diagnosticsEnabled: this.options.diagnosticsEnabled,
189
- });
190
- this.parallelExecutor = executor;
191
- this.parallelReady = executor.start(this.parallelLifecycle.signal);
192
- return executor;
193
- }
194
-
195
- private async invoke(
196
- module: ClawclawBehavior,
197
- input: Readonly<BehaviorInput>,
198
- signal: AbortSignal,
199
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
200
- ): Promise<BehaviorDecision> {
201
- if (this.stopped) throw new Error('behavior_runner_stopped');
202
- if (signal.aborted) throw abortError(signal);
203
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
204
- const startedAt = performance.now();
205
- let invocationActive = true;
206
- let queryCount = 0;
207
- const api: BehaviorReadApi = createBehaviorReadApi(input, {
208
- isActive: () => invocationActive
209
- && !signal.aborted
210
- && !this.stopped
211
- && this.options.isActive(),
212
- onQuery: () => { queryCount += 1; },
213
- ...(observationSnapshot === undefined ? {} : { observationSnapshot }),
214
- });
215
- this.diagnostic('behavior.decide.started', {
216
- behavior_id: this.behaviorId,
217
- activation_id: this.activationId,
218
- instance_generation: this.instanceGeneration,
219
- epoch_id: input.epochId,
220
- execution: this.execution,
221
- }, 'debug');
222
- try {
223
- const decision = normalizeBehaviorDecision(await module.decide(input, api)) as BehaviorDecision;
224
- if (signal.aborted) throw abortError(signal);
225
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
226
- this.diagnostic('behavior.decide.completed', {
227
- behavior_id: this.behaviorId,
228
- activation_id: this.activationId,
229
- instance_generation: this.instanceGeneration,
230
- epoch_id: input.epochId,
231
- tick: input.gameState.tick,
232
- duration_ms: Math.round(performance.now() - startedAt),
233
- read_query_count: queryCount,
234
- action_count: decision.actions?.length ?? 0,
235
- action_kinds: (decision.actions ?? []).map((action) => action.action),
236
- empty_decision: (decision.actions?.length ?? 0) === 0,
237
- event_count: decision.events?.length ?? 0,
238
- finished: decision.finish !== undefined,
239
- execution: this.execution,
240
- }, 'debug');
241
- return decision;
242
- } catch (error) {
243
- this.diagnostic('behavior.decide.failed', {
244
- behavior_id: this.behaviorId,
245
- activation_id: this.activationId,
246
- instance_generation: this.instanceGeneration,
247
- epoch_id: input.epochId,
248
- tick: input.gameState.tick,
249
- duration_ms: Math.round(performance.now() - startedAt),
250
- read_query_count: queryCount,
251
- error_code: errorCode(error),
252
- execution: this.execution,
253
- }, signal.aborted ? 'debug' : 'error');
254
- throw error;
255
- } finally {
256
- invocationActive = false;
257
- }
258
- }
259
-
260
- private diagnostic(
261
- name: string,
262
- attributes?: Readonly<Record<string, unknown>>,
263
- severity?: RuntimeDiagnosticSeverity,
264
- ): void {
265
- try {
266
- this.options.diagnostic?.(name, attributes, severity);
267
- } catch {
268
- // Diagnostics are observational and never alter module execution.
269
- }
270
- }
271
-
272
- private enqueue<T>(operation: () => Promise<T>): Promise<T> {
273
- const pending = this.serialTail.then(operation, operation);
274
- this.serialTail = pending.then(() => undefined, () => undefined);
275
- return pending;
8
+ import { resolveDetailCapture } from '../../../observability/detail-capture.js';
9
+ import { CLAWCLAW_STRATEGY_WORKER_BRIDGE } from './behavior-worker-bridge.js';
10
+ export interface ClawclawBehaviorRunnerOptions extends Omit<StrategyScriptRunnerOptions<BehaviorInput,BehaviorDecision,BehaviorReadApi,ResolvedClawclawBehaviorSource,ClawclawBehaviorObservationSnapshot>, 'bridge'|'createApi'|'normalize'|'inputMetadata'|'captureConfig'|'prepared'> { readonly prepared: PreparedClawclawBehavior }
11
+ /** Only game read APIs, decision normalization and diagnostics are adapted here. */
12
+ export class ClawclawBehaviorRunner extends StrategyScriptRunner<BehaviorInput,BehaviorDecision,BehaviorReadApi,ResolvedClawclawBehaviorSource,ClawclawBehaviorObservationSnapshot> {
13
+ declare readonly prepared:PreparedClawclawBehavior;
14
+ constructor(options:ClawclawBehaviorRunnerOptions) {
15
+ super({...options,bridge:CLAWCLAW_STRATEGY_WORKER_BRIDGE,createApi:createBehaviorReadApi,
16
+ normalize:value=>normalizeBehaviorDecision(value) as BehaviorDecision,captureConfig:resolveDetailCapture(),
17
+ inputMetadata:input=>({tick:input.gameState.tick,game_id:input.gameState.game_id})});
276
18
  }
277
19
  }
@@ -27,8 +27,8 @@ import {
27
27
 
28
28
  const MAX_BEHAVIOR_FILES = 512;
29
29
  const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
30
- const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/behavior-plugin["']/;
31
- const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawBehavior(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
30
+ const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/;
31
+ const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
32
32
  const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/;
33
33
  const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
34
34
  const MANIFEST_FIELDS = new Set([
@@ -0,0 +1,8 @@
1
+ import type { StrategyThreadBridge } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
2
+ import { behaviorSourceUrl, behaviorThreadLoaderConfig, pinBehaviorSource, resolveBehaviorSource } from './behavior-module-loader.js';
3
+ import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
4
+ /** Game SDK and source validation; pool scheduling belongs to the framework. */
5
+ export const CLAWCLAW_STRATEGY_WORKER_BRIDGE: StrategyThreadBridge<ResolvedClawclawBehaviorSource> = {
6
+ hostUrl: new URL('./behavior-analysis-thread-host.ts', import.meta.url).href,
7
+ pin: pinBehaviorSource, resolve: resolveBehaviorSource, sourceUrl: behaviorSourceUrl, loader: behaviorThreadLoaderConfig,
8
+ };
@@ -1,180 +1,3 @@
1
- import {
2
- actionControllerId,
3
- behaviorControllerSpec,
4
- type BehaviorActionCaller,
5
- } from '../../../framework/capability-registry.js';
6
- import type { ScopeRef } from '../../../framework/contracts.js';
7
- import type { Runtime } from '../../../framework/runtime.js';
8
- import type { BehaviorActivationSnapshot } from './activation-manager.js';
9
-
10
- // Behavior modules may emit physical and communication GameActions. Meeting
11
- // votes remain direct Agent/User commands and therefore are not reserved by a
12
- // Behavior activation.
13
- const BEHAVIOR_CONTROL_DOMAINS = ['physical', 'communication'] as const;
14
-
15
- export interface ClawclawBehaviorControlHandle {
16
- readonly caller: BehaviorActionCaller;
17
- readonly scope: ScopeRef;
18
- readonly controllerId: string;
19
- /** Reads current scheduler state, so a held activation can later become active. */
20
- isAuthorized(): boolean;
21
- release(reason: string): void;
22
- }
23
-
24
- export interface ClawclawBehaviorControlDriver {
25
- acquire(
26
- activation: BehaviorActivationSnapshot,
27
- expectedScope: ScopeRef,
28
- ): ClawclawBehaviorControlHandle;
29
- }
30
-
31
- function sameScope(left: ScopeRef, right: ScopeRef): boolean {
32
- return left.adapterId === right.adapterId
33
- && left.accountId === right.accountId
34
- && left.sessionId === right.sessionId
35
- && left.segmentId === right.segmentId;
36
- }
37
-
38
- function isLiveController(
39
- runtime: Pick<Runtime<any>, 'actions'>,
40
- controllerId: string,
41
- ): boolean {
42
- const controller = runtime.actions.controls.snapshot().controllers.find(
43
- candidate => candidate.controllerId === controllerId,
44
- );
45
- return controller !== undefined
46
- && controller.state !== 'released'
47
- && controller.state !== 'expired';
48
- }
49
-
50
- function directHandoffCaller(
51
- activation: BehaviorActivationSnapshot,
52
- ): { kind: 'agent' | 'user' } | undefined {
53
- if (activation.source === 'agent') return { kind: 'agent' };
54
- if (activation.source === 'user') return { kind: 'user' };
55
- return undefined;
56
- }
57
-
58
- function validateActivation(activation: BehaviorActivationSnapshot): void {
59
- if (activation.state !== 'running') {
60
- throw new Error('behavior_control_activation_not_running');
61
- }
62
- if (
63
- (activation.layer === 'short' || activation.layer === 'reflex')
64
- && activation.maxRuntimeMs === undefined
65
- ) {
66
- throw new Error('behavior_control_runtime_required');
67
- }
68
- }
69
-
70
- /**
71
- * Narrow Behavior-Host facade over the Runtime control scheduler.
72
- *
73
- * The caller's fixed layer selects priority through behaviorControllerSpec;
74
- * Trigger reflexPriority is deliberately never read here.
75
- */
76
- export function createClawclawBehaviorControlDriver(
77
- runtime: Pick<Runtime<any>, 'actions' | 'scope'>,
78
- ): ClawclawBehaviorControlDriver {
79
- return {
80
- acquire: (
81
- activation,
82
- expectedScope,
83
- ): ClawclawBehaviorControlHandle => {
84
- validateActivation(activation);
85
- const scope = runtime.scope();
86
- if (!sameScope(scope, expectedScope)) {
87
- throw new Error('behavior_control_scope_changed');
88
- }
89
-
90
- const caller: BehaviorActionCaller = Object.freeze({
91
- kind: 'behavior',
92
- activationId: activation.activationId,
93
- layer: activation.layer,
94
- activationGeneration: activation.instanceGeneration,
95
- });
96
- const controllerId = actionControllerId(caller);
97
- const lifecycle = activation.layer === 'long'
98
- && activation.maxRuntimeMs === undefined
99
- ? 'persistent' as const
100
- : 'finite' as const;
101
- let registered = false;
102
-
103
- try {
104
- runtime.actions.controls.registerController(behaviorControllerSpec(caller, {
105
- scope,
106
- domains: [...BEHAVIOR_CONTROL_DOMAINS],
107
- lifecycle,
108
- ...(activation.maxRuntimeMs === undefined
109
- ? {}
110
- : { maxRuntimeMs: activation.maxRuntimeMs }),
111
- ready: false,
112
- holdMode: 'all_or_nothing',
113
- metadata: {
114
- owner: 'clawclaw.behavior',
115
- behaviorId: activation.behaviorId,
116
- behaviorSource: activation.source,
117
- },
118
- }));
119
- registered = true;
120
-
121
- const handoffCaller = directHandoffCaller(activation);
122
- const handoffControllerId = handoffCaller
123
- ? actionControllerId(handoffCaller, scope)
124
- : undefined;
125
- let handedOff = false;
126
- if (handoffControllerId && isLiveController(runtime, handoffControllerId)) {
127
- try {
128
- runtime.actions.controls.handoff({
129
- fromControllerId: handoffControllerId,
130
- toControllerId: controllerId,
131
- domains: [...BEHAVIOR_CONTROL_DOMAINS],
132
- });
133
- handedOff = true;
134
- } catch (error) {
135
- // A source may disappear between the snapshot and handoff. A real
136
- // higher blocker leaves the Behavior ready-but-held so it may
137
- // become active later without recreating the runner.
138
- if (
139
- isLiveController(runtime, handoffControllerId)
140
- && (!(error instanceof Error) || error.message !== 'control_handoff_target_held')
141
- ) throw error;
142
- }
143
- }
144
- if (!handedOff) runtime.actions.controls.setReady(controllerId, true);
145
- } catch (error) {
146
- if (registered) {
147
- runtime.actions.controls.release(controllerId, {
148
- reason: 'behavior_control_acquire_failed',
149
- });
150
- }
151
- throw error;
152
- }
153
-
154
- let released = false;
155
- return Object.freeze({
156
- caller,
157
- scope: Object.freeze({ ...scope }),
158
- controllerId,
159
- isAuthorized: (): boolean => {
160
- if (released || !sameScope(runtime.scope(), scope)) return false;
161
- const controller = runtime.actions.controls.snapshot().controllers.find(
162
- candidate => candidate.controllerId === controllerId,
163
- );
164
- return controller !== undefined
165
- && controller.ready
166
- && controller.state !== 'released'
167
- && controller.state !== 'expired'
168
- && BEHAVIOR_CONTROL_DOMAINS.every(
169
- domain => controller.grantedDomains.includes(domain),
170
- );
171
- },
172
- release: (reason: string): void => {
173
- if (released) return;
174
- released = true;
175
- runtime.actions.controls.release(controllerId, { reason });
176
- },
177
- });
178
- },
179
- };
180
- }
1
+ import { createStrategyControlDriver } from '@myclaw163/game-agent-runtime/strategy/control-driver.js';
2
+ export type { StrategyControlDriver as ClawclawBehaviorControlDriver, StrategyControlHandle as ClawclawBehaviorControlHandle } from '@myclaw163/game-agent-runtime/strategy/control-driver.js';
3
+ export const createClawclawBehaviorControlDriver = (runtime: Parameters<typeof createStrategyControlDriver>[0]) => createStrategyControlDriver(runtime, { domains: ['physical', 'communication'], owner: 'clawclaw.behavior' });