@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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 (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -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' });