@myclaw163/clawclaw-cli 0.9.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -1,282 +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
- import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
16
-
17
- export interface ClawclawBehaviorRunnerOptions {
18
- readonly memory?: (input: Readonly<BehaviorInput>, isActive: () => boolean) => StrategyMemory;
19
- readonly snapshotStore?: BehaviorSnapshotStore;
20
- readonly behaviorId: string;
21
- readonly activationId: string;
22
- readonly instanceGeneration: number;
23
- readonly prepared: PreparedClawclawBehavior;
24
- readonly diagnostic?: (
25
- name: string,
26
- attributes?: Readonly<Record<string, unknown>>,
27
- severity?: RuntimeDiagnosticSeverity,
28
- ) => void;
29
- readonly isActive: () => boolean;
30
- readonly diagnosticsEnabled?: boolean;
31
- }
32
-
33
- function errorCode(error: unknown): string {
34
- const message = error instanceof Error ? error.message : String(error);
35
- return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message)
36
- ? message
37
- : 'BEHAVIOR_DECIDE_FAILED';
38
- }
39
-
40
- function abortError(signal: AbortSignal): Error {
41
- return signal.reason instanceof Error
42
- ? signal.reason
43
- : new Error('behavior_decide_aborted');
44
- }
45
-
46
- /**
47
- * One Activation-generation runner. Serial retains one instance; parallel
48
- * creates an isolated instance per computation. Source modules run in Workers.
49
- */
50
- export class ClawclawBehaviorRunner {
51
- readonly behaviorId: string;
52
- readonly activationId: string;
53
- readonly instanceGeneration: number;
54
- readonly prepared: PreparedClawclawBehavior;
55
-
56
- private serialModule?: ClawclawBehavior;
57
- private serialTail = Promise.resolve();
58
- private readonly parallelLifecycle = new AbortController();
59
- private parallelExecutor?: ThreadBehaviorExecutor;
60
- private parallelReady?: Promise<void>;
61
- private parallelStop?: Promise<void>;
62
- private stopped = false;
63
- private readonly capture: DetailCapture;
64
-
65
- constructor(private readonly options: ClawclawBehaviorRunnerOptions) {
66
- this.behaviorId = options.behaviorId;
67
- this.activationId = options.activationId;
68
- this.instanceGeneration = options.instanceGeneration;
69
- this.prepared = options.prepared;
70
- this.serialModule = options.prepared.module;
71
- this.capture = new DetailCapture('behavior_io', options.diagnostic);
72
- }
73
-
74
- get execution(): 'parallel' | 'serial' {
75
- return this.prepared.manifest.execution ?? 'parallel';
76
- }
77
-
78
- /** Start/import Workers at activation, outside per-decision computation deadlines. */
79
- async prepare(): Promise<void> {
80
- if (!this.prepared.source) return;
81
- this.ensureThreadExecutor();
82
- await this.parallelReady;
83
- }
84
-
85
- get everyTicks(): number {
86
- return this.prepared.manifest.everyTicks ?? 1;
87
- }
88
-
89
- diagnosticSnapshot(): Readonly<Record<string, unknown>> {
90
- const pool = this.parallelExecutor?.snapshot();
91
- return Object.freeze({
92
- execution: this.execution,
93
- every_ticks: this.everyTicks,
94
- stopped: this.stopped,
95
- worker_pool: pool
96
- ? {
97
- state: pool.state,
98
- worker_count: pool.workerCount,
99
- idle_worker_count: pool.idleWorkerCount,
100
- busy_worker_count: pool.busyWorkerCount,
101
- queued_request_count: pool.queuedRequestCount,
102
- in_flight_request_count: pool.inFlightRequestCount,
103
- started_worker_count: pool.startedWorkerCount,
104
- retired_worker_count: pool.retiredWorkerCount,
105
- worker_heap_used_bytes: pool.workerHeapUsedBytes,
106
- peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes,
107
- }
108
- : null,
109
- });
110
- }
111
-
112
- decideSerial(
113
- input: Readonly<BehaviorInput>,
114
- signal: AbortSignal,
115
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
116
- ): Promise<BehaviorDecision> {
117
- return this.traceDecision(input, observationSnapshot, signal, () => this.decideSerialInternal(input, signal, observationSnapshot));
118
- }
119
-
120
- private decideSerialInternal(input: Readonly<BehaviorInput>, signal: AbortSignal,
121
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>): Promise<BehaviorDecision> {
122
- if (this.prepared.source) {
123
- return this.enqueue(() => this.invokeThread(input, signal, observationSnapshot));
124
- }
125
- const module = this.serialModule;
126
- if (!module) return Promise.reject(new Error('behavior_serial_module_missing'));
127
- return this.enqueue(() => this.invoke(module, input, signal, observationSnapshot));
128
- }
129
-
130
- decideParallel(
131
- input: Readonly<BehaviorInput>,
132
- signal: AbortSignal,
133
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
134
- ): Promise<BehaviorDecision> {
135
- return this.traceDecision(input, observationSnapshot, signal, () => this.invokeThread(input, signal, observationSnapshot));
136
- }
137
-
138
- private traceDecision(input: Readonly<BehaviorInput>, observationSnapshot: Readonly<ClawclawBehaviorObservationSnapshot> | undefined,
139
- signal: AbortSignal, invoke: () => Promise<BehaviorDecision>): Promise<BehaviorDecision> {
140
- if (!this.capture.enabled) return invoke();
141
- return this.capture.run('decide', {
142
- behavior_id: this.behaviorId, activation_id: this.activationId, instance_generation: this.instanceGeneration,
143
- epoch_id: input.epochId, tick: input.gameState.tick, game_id: input.gameState.game_id,
144
- session_id: input.scope.sessionId, segment_id: input.scope.segmentId, execution: this.execution,
145
- }, { frame: input, observation: observationSnapshot }, invoke, signal);
146
- }
147
-
148
- stop(reason: 'switched' | 'scope_ended' | 'shutdown' = 'switched'): Promise<void> {
149
- if (this.parallelStop) return this.parallelStop;
150
- this.stopped = true;
151
- this.parallelLifecycle.abort(new Error(`behavior_runner_stopped:${reason}`));
152
- const executor = this.parallelExecutor;
153
- this.parallelExecutor = undefined;
154
- this.parallelReady = undefined;
155
- this.parallelStop = executor?.stop(reason) ?? Promise.resolve();
156
- return this.parallelStop;
157
- }
158
-
159
- private async invokeThread(
160
- input: Readonly<BehaviorInput>,
161
- signal: AbortSignal,
162
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
163
- ): Promise<BehaviorDecision> {
164
- if (this.stopped) throw new Error('behavior_runner_stopped');
165
- if (signal.aborted) throw abortError(signal);
166
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
167
- const executor = this.ensureThreadExecutor();
168
- await this.parallelReady;
169
- if (this.stopped) throw new Error('behavior_runner_stopped');
170
- if (signal.aborted) throw abortError(signal);
171
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
172
- const decision = await executor.update(input, signal, observationSnapshot);
173
- if (signal.aborted) throw abortError(signal);
174
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
175
- return decision;
176
- }
177
-
178
- private ensureThreadExecutor(): ThreadBehaviorExecutor {
179
- if (this.parallelExecutor) return this.parallelExecutor;
180
- const source = this.prepared.source;
181
- if (!source) throw new Error('behavior_thread_source_missing');
182
- if (source.id !== this.behaviorId || source.execution !== this.execution) {
183
- throw new Error('behavior_thread_source_invalid');
184
- }
185
- const executor = new ThreadBehaviorExecutor({
186
- memory: this.options.memory && ((frame, active) => this.options.memory!(frame,
187
- () => active() && !this.stopped && this.options.isActive())),
188
- fixedWorkers: true,
189
- snapshotStore: this.options.snapshotStore,
190
- source,
191
- diagnostic: this.options.diagnostic,
192
- diagnosticsEnabled: this.options.diagnosticsEnabled,
193
- });
194
- this.parallelExecutor = executor;
195
- this.parallelReady = executor.start(this.parallelLifecycle.signal);
196
- return executor;
197
- }
198
-
199
- private async invoke(
200
- module: ClawclawBehavior,
201
- input: Readonly<BehaviorInput>,
202
- signal: AbortSignal,
203
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
204
- ): Promise<BehaviorDecision> {
205
- if (this.stopped) throw new Error('behavior_runner_stopped');
206
- if (signal.aborted) throw abortError(signal);
207
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
208
- const startedAt = performance.now();
209
- let invocationActive = true;
210
- let queryCount = 0;
211
- const api: BehaviorReadApi = createBehaviorReadApi(input, {
212
- memory: this.options.memory?.(input, () => invocationActive && !signal.aborted && !this.stopped && this.options.isActive()),
213
- isActive: () => invocationActive
214
- && !signal.aborted
215
- && !this.stopped
216
- && this.options.isActive(),
217
- onQuery: () => { queryCount += 1; },
218
- ...(observationSnapshot === undefined ? {} : { observationSnapshot }),
219
- });
220
- this.diagnostic('behavior.decide.started', {
221
- behavior_id: this.behaviorId,
222
- activation_id: this.activationId,
223
- instance_generation: this.instanceGeneration,
224
- epoch_id: input.epochId,
225
- execution: this.execution,
226
- }, 'debug');
227
- try {
228
- const decision = normalizeBehaviorDecision(await module.decide(input, api)) as BehaviorDecision;
229
- if (signal.aborted) throw abortError(signal);
230
- if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
231
- this.diagnostic('behavior.decide.completed', {
232
- behavior_id: this.behaviorId,
233
- activation_id: this.activationId,
234
- instance_generation: this.instanceGeneration,
235
- epoch_id: input.epochId,
236
- tick: input.gameState.tick,
237
- duration_ms: Math.round(performance.now() - startedAt),
238
- read_query_count: queryCount,
239
- action_count: decision.actions?.length ?? 0,
240
- action_kinds: (decision.actions ?? []).map((action) => action.action),
241
- empty_decision: (decision.actions?.length ?? 0) === 0,
242
- event_count: decision.events?.length ?? 0,
243
- finished: decision.finish !== undefined,
244
- execution: this.execution,
245
- }, 'debug');
246
- return decision;
247
- } catch (error) {
248
- this.diagnostic('behavior.decide.failed', {
249
- behavior_id: this.behaviorId,
250
- activation_id: this.activationId,
251
- instance_generation: this.instanceGeneration,
252
- epoch_id: input.epochId,
253
- tick: input.gameState.tick,
254
- duration_ms: Math.round(performance.now() - startedAt),
255
- read_query_count: queryCount,
256
- error_code: errorCode(error),
257
- execution: this.execution,
258
- }, signal.aborted ? 'debug' : 'error');
259
- throw error;
260
- } finally {
261
- invocationActive = false;
262
- }
263
- }
264
-
265
- private diagnostic(
266
- name: string,
267
- attributes?: Readonly<Record<string, unknown>>,
268
- severity?: RuntimeDiagnosticSeverity,
269
- ): void {
270
- try {
271
- this.options.diagnostic?.(name, attributes, severity);
272
- } catch {
273
- // Diagnostics are observational and never alter module execution.
274
- }
275
- }
276
-
277
- private enqueue<T>(operation: () => Promise<T>): Promise<T> {
278
- const pending = this.serialTail.then(operation, operation);
279
- this.serialTail = pending.then(() => undefined, () => undefined);
280
- 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})});
281
18
  }
282
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' });