@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
@@ -0,0 +1,36 @@
1
+ import type { EventStoreCompatibility } from '@myclaw163/game-agent-runtime/framework/events/store-compatibility.js';
2
+ export const CLAWCLAW_STORE_COMPATIBILITY: EventStoreCompatibility = {
3
+ "legacyConsumer": "local-agent",
4
+ "monitorConsumer": "local-agent:monitor",
5
+ "detailsConsumer": "local-agent:ccl-events",
6
+ "desktopConsumer": "local-agent:desktop",
7
+ "channelConsumer": "local-agent:claude-channel",
8
+ "detailEvidence": [
9
+ "ccl_events",
10
+ "ccl_events_backlog",
11
+ "stdout_full"
12
+ ],
13
+ "desktopEvidence": [
14
+ "mailbox_full",
15
+ "desktop_ipc"
16
+ ],
17
+ "channelEvidence": [
18
+ "claude_channel"
19
+ ],
20
+ "desktopVia": "desktop_ipc",
21
+ "channelVia": "claude_channel",
22
+ "legacyDeliveryVias": [
23
+ "stdout_full",
24
+ "mailbox_full",
25
+ "desktop_ipc",
26
+ "claude_channel",
27
+ "ccl_events",
28
+ "ccl_events_backlog"
29
+ ],
30
+ "initialDeliveryVias": [
31
+ "stdout_full",
32
+ "mailbox_full",
33
+ "ccl_events",
34
+ "ccl_events_backlog"
35
+ ]
36
+ };
@@ -315,7 +315,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
315
315
  if (isClawclawRuntimeState(input.epoch.state)) {
316
316
  this.stage = input.epoch.state.stage;
317
317
  this.connection = input.epoch.state.connection;
318
- if (input.epoch.state.game_snapshot.status === 'fresh') {
318
+ if ((input.epoch.state.game_snapshot.status === 'fresh' || input.epoch.state.game_snapshot.status === 'cached')) {
319
319
  this.rememberTaskGameState(input.epoch.scope, input.epoch.epochSeq, input.epoch.state.game_snapshot.state);
320
320
  }
321
321
  }
@@ -355,7 +355,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
355
355
  const runtimeState = latest?.state;
356
356
  let game: Record<string, any> | undefined;
357
357
  if (isClawclawRuntimeState(runtimeState)) {
358
- if (runtimeState.game_snapshot.status === 'fresh') {
358
+ if ((runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')) {
359
359
  game = runtimeState.game_snapshot.state;
360
360
  this.rememberTaskGameState(scope, latest!.epochSeq, game);
361
361
  } else if (runtimeState.game_snapshot.status === 'not_updated'
@@ -508,7 +508,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
508
508
  && state.connection === 'connected'
509
509
  && state.stage === 'game'
510
510
  && (
511
- state.game_snapshot.status !== 'fresh'
511
+ (state.game_snapshot.status !== 'fresh' && state.game_snapshot.status !== 'cached')
512
512
  || (
513
513
  state.game_snapshot.state.phase === 'wandering'
514
514
  && state.game_snapshot.state.you?.is_alive !== false
@@ -15,10 +15,8 @@ import {
15
15
  ClawclawBehaviorPlugin,
16
16
  type ClawclawRoleFallbackBehaviors,
17
17
  } from './behavior/index.js';
18
- import {
19
- CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
20
- ClawclawDerivedEventPlugin,
21
- } from './derived-event/index.js';
18
+ import { createSystemPerceptions } from './system-perception/system-perceptions.js';
19
+ import { BUILTIN_PERCEPTION_PREFIX } from '../notification-policy.js';
22
20
  import {
23
21
  CLAWCLAW_GAME_QUERY_PLUGIN_ID,
24
22
  ClawclawGameQueryPlugin,
@@ -69,6 +67,9 @@ export function assembleClawclawPlugins(
69
67
  ): ClawclawPluginAssembly {
70
68
  const plugins = [...(options.epochPlugins ?? [])];
71
69
  for (const plugin of plugins) {
70
+ if (plugin.id.startsWith(BUILTIN_PERCEPTION_PREFIX) || plugin.id === 'clawclaw.derived-event') {
71
+ throw new Error(`Builtin perceptions are mandatory and cannot be replaced: ${plugin.id}`);
72
+ }
72
73
  const failureMode = typeof plugin.failurePolicy === 'string'
73
74
  ? plugin.failurePolicy
74
75
  : plugin.failurePolicy?.mode;
@@ -87,9 +88,7 @@ export function assembleClawclawPlugins(
87
88
  ?? new ClawclawActionPlugin(client);
88
89
  if (!configuredAction) plugins.push(action);
89
90
 
90
- if (!plugins.some((plugin) => plugin.id === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID)) {
91
- plugins.push(new ClawclawDerivedEventPlugin());
92
- }
91
+ plugins.push(...createSystemPerceptions(options.behaviorEventTypes));
93
92
  const configuredReminders = plugins.find(plugin => plugin.id === CLAWCLAW_REMINDER_PLUGIN_ID);
94
93
  if (configuredReminders && !(configuredReminders instanceof ClawclawReminderPlugin)) {
95
94
  throw new Error(`Runtime Plugin ${CLAWCLAW_REMINDER_PLUGIN_ID} is not a ClawclawReminderPlugin.`);
@@ -134,7 +133,7 @@ export function assembleClawclawPlugins(
134
133
  if (!configuredTrigger) plugins.push(trigger);
135
134
 
136
135
  const modules = moduleSources.length ? new ClawclawPerceptionModulePlugin({ sources: moduleSources,
137
- after: [CLAWCLAW_DERIVED_EVENT_PLUGIN_ID],
136
+ after: [],
138
137
  behaviors: () => options.behaviorCatalog?.list?.() ?? [],
139
138
  }) : undefined;
140
139
  if (modules) plugins.push(modules);
@@ -149,7 +148,6 @@ export function assembleClawclawPlugins(
149
148
  fallbackBehaviors: options.fallbackBehaviors,
150
149
  after: [
151
150
  CLAWCLAW_ACTION_PLUGIN_ID,
152
- CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
153
151
  CLAWCLAW_REMINDER_PLUGIN_ID,
154
152
  CLAWCLAW_GAME_QUERY_PLUGIN_ID,
155
153
  CLAWCLAW_PERCEPTION_PLUGIN_ID,
@@ -1,495 +1 @@
1
- import type { BehaviorActivationLayer } from '../../../../sdk/behavior-plugin/index.js';
2
-
3
- export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'perception' | 'behavior' | 'system';
4
- export type BehaviorActivationState = 'running' | 'suspended';
5
-
6
- export interface BehaviorActivationSpec {
7
- readonly activationId: string;
8
- readonly behaviorId: string;
9
- readonly layer: BehaviorActivationLayer;
10
- readonly source: BehaviorActivationSource;
11
- readonly input: Readonly<Record<string, unknown>>;
12
- readonly requestedAt: number;
13
- readonly maxRuntimeMs?: number;
14
- readonly deadlineOutcome?: 'completed' | 'failed';
15
- readonly triggerId?: string;
16
- readonly reflexPriority?: number;
17
- }
18
-
19
- export interface BehaviorFallbackBinding {
20
- readonly behaviorId: string;
21
- readonly input: Readonly<Record<string, unknown>>;
22
- }
23
-
24
- export interface BehaviorActivationSnapshot extends BehaviorActivationSpec {
25
- readonly state: BehaviorActivationState;
26
- readonly instanceGeneration: number;
27
- readonly startedAt?: number;
28
- readonly deadlineAt?: number;
29
- }
30
-
31
- export type BehaviorActivationTransitionType =
32
- | 'started'
33
- | 'suspended'
34
- | 'restarted'
35
- | 'completed'
36
- | 'failed'
37
- | 'cancelled'
38
- | 'replaced'
39
- | 'ignored';
40
-
41
- export interface BehaviorActivationTransition {
42
- readonly type: BehaviorActivationTransitionType;
43
- readonly activationId: string;
44
- readonly behaviorId: string;
45
- readonly layer: BehaviorActivationLayer;
46
- readonly at: number;
47
- readonly reason: string;
48
- readonly instanceGeneration: number;
49
- readonly replacedByActivationId?: string;
50
- }
51
-
52
- export interface BehaviorActivationManagerOptions {
53
- readonly idleMs?: number;
54
- readonly createActivationId?: () => string;
55
- }
56
-
57
- interface MutableActivation {
58
- spec: BehaviorActivationSpec;
59
- state: BehaviorActivationState;
60
- instanceGeneration: number;
61
- startedAt?: number;
62
- deadlineAt?: number;
63
- }
64
-
65
- const DEFAULT_IDLE_MS = 500;
66
-
67
- function cloneInput(input: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>> {
68
- return Object.freeze(structuredClone(input));
69
- }
70
-
71
- function validateIdleMs(value: number): number {
72
- if (!Number.isSafeInteger(value) || value < 0 || value > 60_000) {
73
- throw new Error('behavior_idle_ms_invalid');
74
- }
75
- return value;
76
- }
77
-
78
- function validateSpec(spec: BehaviorActivationSpec): BehaviorActivationSpec {
79
- if (!spec.activationId.trim()) throw new Error('behavior_activation_id_invalid');
80
- if (!spec.behaviorId.trim()) throw new Error('behavior_id_invalid');
81
- if (!['long', 'short', 'reflex'].includes(spec.layer)) {
82
- throw new Error('behavior_activation_layer_invalid');
83
- }
84
- if (!Number.isFinite(spec.requestedAt)) throw new Error('behavior_activation_time_invalid');
85
- if (
86
- spec.maxRuntimeMs !== undefined
87
- && (!Number.isSafeInteger(spec.maxRuntimeMs) || spec.maxRuntimeMs <= 0)
88
- ) throw new Error('behavior_activation_runtime_invalid');
89
- if (
90
- spec.deadlineOutcome !== undefined
91
- && spec.deadlineOutcome !== 'completed'
92
- && spec.deadlineOutcome !== 'failed'
93
- ) throw new Error('behavior_activation_deadline_outcome_invalid');
94
- if (spec.deadlineOutcome !== undefined && spec.maxRuntimeMs === undefined) {
95
- throw new Error('behavior_activation_deadline_outcome_without_runtime');
96
- }
97
- if (spec.layer === 'reflex') {
98
- if (!spec.triggerId?.trim()) throw new Error('behavior_reflex_trigger_id_invalid');
99
- if (!Number.isSafeInteger(spec.reflexPriority)) {
100
- throw new Error('behavior_reflex_priority_invalid');
101
- }
102
- } else if (spec.triggerId !== undefined || spec.reflexPriority !== undefined) {
103
- throw new Error('behavior_reflex_fields_not_allowed');
104
- }
105
- return Object.freeze({
106
- ...spec,
107
- input: cloneInput(spec.input),
108
- });
109
- }
110
-
111
- /**
112
- * Owns the bounded physical-control stack: one long, one short, one reflex.
113
- * It never imports modules or submits Actions; Behavior Host applies transitions.
114
- */
115
- export class BehaviorActivationManager {
116
- private idleMs: number;
117
- private readonly createActivationId: () => string;
118
- private fallback?: BehaviorFallbackBinding;
119
- private long?: MutableActivation;
120
- private short?: MutableActivation;
121
- private reflex?: MutableActivation;
122
- private longEligibleAt?: number;
123
- private boundaryActive = false;
124
- private idleGeneration = 0;
125
- private fallbackStartedGeneration = -1;
126
- private sequence = 0;
127
-
128
- constructor(options: BehaviorActivationManagerOptions = {}) {
129
- this.idleMs = validateIdleMs(options.idleMs ?? DEFAULT_IDLE_MS);
130
- this.createActivationId = options.createActivationId
131
- ?? (() => `behavior-${++this.sequence}`);
132
- }
133
-
134
- setIdleMs(idleMs: number, now: number): readonly BehaviorActivationTransition[] {
135
- this.idleMs = validateIdleMs(idleMs);
136
- if (!this.short && !this.reflex && (!this.long || this.long.state === 'suspended')) {
137
- this.longEligibleAt = now + this.idleMs;
138
- }
139
- return this.advance(now);
140
- }
141
-
142
- idleDelayMs(): number {
143
- return this.idleMs;
144
- }
145
-
146
- bindFallback(
147
- binding: BehaviorFallbackBinding | undefined,
148
- now: number,
149
- startImmediately = false,
150
- ): readonly BehaviorActivationTransition[] {
151
- this.fallback = binding
152
- ? Object.freeze({ behaviorId: binding.behaviorId, input: cloneInput(binding.input) })
153
- : undefined;
154
- this.idleGeneration += 1;
155
- this.fallbackStartedGeneration = -1;
156
- if (!this.short && !this.reflex && !this.long) {
157
- this.longEligibleAt = startImmediately ? now : now + this.idleMs;
158
- }
159
- return this.advance(now);
160
- }
161
-
162
- noteAgentActivity(now: number): readonly BehaviorActivationTransition[] {
163
- this.idleGeneration += 1;
164
- this.fallbackStartedGeneration = -1;
165
- this.longEligibleAt = now + this.idleMs;
166
- if (this.long?.spec.source !== 'idle') return [];
167
- const transitions = [this.transition(this.long, 'cancelled', now, 'agent_activity')];
168
- this.long = undefined;
169
- return transitions;
170
- }
171
-
172
- /**
173
- * Enter a game boundary where wandering Behaviors cannot keep authority.
174
- * Finite foreground work is cancelled; an explicit/fallback long Activation
175
- * is retained as configuration but must later restart from a fresh runner.
176
- */
177
- enterBoundary(reason: string, now: number): readonly BehaviorActivationTransition[] {
178
- this.boundaryActive = true;
179
- const transitions: BehaviorActivationTransition[] = [];
180
- if (this.reflex) {
181
- transitions.push(this.transition(this.reflex, 'cancelled', now, reason));
182
- this.reflex = undefined;
183
- }
184
- if (this.short) {
185
- transitions.push(this.transition(this.short, 'cancelled', now, reason));
186
- this.short = undefined;
187
- }
188
- if (this.long?.state === 'running') {
189
- this.long.state = 'suspended';
190
- transitions.push(this.transition(this.long, 'suspended', now, reason));
191
- }
192
- this.longEligibleAt = undefined;
193
- return transitions;
194
- }
195
-
196
- /** Starts the one shared hand-back delay after a meeting/loading boundary. */
197
- leaveBoundary(now: number): readonly BehaviorActivationTransition[] {
198
- this.boundaryActive = false;
199
- if (this.reflex || this.short) return [];
200
- if (this.long?.state === 'suspended' || (!this.long && this.fallback)) {
201
- this.longEligibleAt = now + this.idleMs;
202
- }
203
- return this.advance(now);
204
- }
205
-
206
- /** Ends every Activation in the current game scope while retaining policy bindings. */
207
- clearScope(reason: string, now: number): readonly BehaviorActivationTransition[] {
208
- this.boundaryActive = true;
209
- const transitions: BehaviorActivationTransition[] = [];
210
- for (const layer of ['reflex', 'short', 'long'] as const) {
211
- const activation = this[layer];
212
- if (!activation) continue;
213
- transitions.push(this.transition(activation, 'cancelled', now, reason));
214
- this[layer] = undefined;
215
- }
216
- this.idleGeneration += 1;
217
- this.fallbackStartedGeneration = -1;
218
- this.longEligibleAt = undefined;
219
- return transitions;
220
- }
221
-
222
- startLong(
223
- spec: Omit<BehaviorActivationSpec, 'layer'> & { readonly layer?: 'long' },
224
- now: number,
225
- ): readonly BehaviorActivationTransition[] {
226
- const next = this.activation({ ...spec, layer: 'long' }, now);
227
- const transitions: BehaviorActivationTransition[] = [];
228
- if (this.long) {
229
- transitions.push(this.transition(this.long, 'replaced', now, 'long_replaced', next.spec.activationId));
230
- }
231
- this.long = next;
232
- this.longEligibleAt = undefined;
233
- if (this.boundaryActive || this.short || this.reflex) {
234
- next.state = 'suspended';
235
- transitions.push(this.transition(next, 'suspended', now,
236
- this.boundaryActive ? 'phase_boundary' : 'higher_layer_active'));
237
- } else {
238
- transitions.push(this.transition(next, 'started', now, 'explicit_long_started'));
239
- }
240
- return transitions;
241
- }
242
-
243
- startShort(
244
- spec: Omit<BehaviorActivationSpec, 'layer'> & { readonly layer?: 'short' },
245
- now: number,
246
- ): readonly BehaviorActivationTransition[] {
247
- const next = this.activation({ ...spec, layer: 'short' }, now);
248
- const transitions: BehaviorActivationTransition[] = [];
249
- if (this.short) {
250
- transitions.push(this.transition(this.short, 'replaced', now, 'short_replaced', next.spec.activationId));
251
- }
252
- this.short = next;
253
- if (this.long?.state === 'running') {
254
- this.long.state = 'suspended';
255
- transitions.push(this.transition(this.long, 'suspended', now, 'short_started'));
256
- }
257
- if (this.reflex) {
258
- next.state = 'suspended';
259
- transitions.push(this.transition(next, 'suspended', now, 'reflex_active'));
260
- } else {
261
- transitions.push(this.transition(next, 'started', now, 'short_started'));
262
- }
263
- return transitions;
264
- }
265
-
266
- requestReflex(
267
- spec: Omit<BehaviorActivationSpec, 'layer' | 'source'> & {
268
- readonly layer?: 'reflex';
269
- readonly source?: 'trigger' | 'perception';
270
- },
271
- now: number,
272
- ): readonly BehaviorActivationTransition[] {
273
- const candidate = this.activation({ ...spec, layer: 'reflex', source: spec.source ?? 'trigger' }, now);
274
- const active = this.reflex;
275
- if (active) {
276
- const sameTrigger = active.spec.triggerId === candidate.spec.triggerId;
277
- const higher = (candidate.spec.reflexPriority as number) > (active.spec.reflexPriority as number);
278
- if (sameTrigger || !higher) {
279
- return [this.transition(
280
- candidate,
281
- 'ignored',
282
- now,
283
- sameTrigger ? 'reflex_trigger_already_active' : 'reflex_priority_not_higher',
284
- )];
285
- }
286
- }
287
-
288
- const transitions: BehaviorActivationTransition[] = [];
289
- if (active) {
290
- transitions.push(this.transition(active, 'replaced', now, 'higher_priority_reflex', candidate.spec.activationId));
291
- }
292
- this.reflex = candidate;
293
- if (this.short?.state === 'running') {
294
- this.short.state = 'suspended';
295
- transitions.push(this.transition(this.short, 'suspended', now, 'reflex_started'));
296
- }
297
- if (this.long?.state === 'running') {
298
- this.long.state = 'suspended';
299
- transitions.push(this.transition(this.long, 'suspended', now, 'reflex_started'));
300
- }
301
- transitions.push(this.transition(candidate, 'started', now, 'reflex_started'));
302
- return transitions;
303
- }
304
-
305
- finish(
306
- activationId: string,
307
- outcome: 'completed' | 'failed',
308
- reason: string,
309
- now: number,
310
- ): readonly BehaviorActivationTransition[] {
311
- return this.remove(activationId, outcome, reason, now);
312
- }
313
-
314
- cancel(activationId: string, reason: string, now: number): readonly BehaviorActivationTransition[] {
315
- return this.remove(activationId, 'cancelled', reason, now);
316
- }
317
-
318
- advance(now: number): readonly BehaviorActivationTransition[] {
319
- const transitions: BehaviorActivationTransition[] = [];
320
- for (const activation of [this.reflex, this.short, this.long]) {
321
- if (activation?.deadlineAt !== undefined && now >= activation.deadlineAt) {
322
- const outcome = activation.spec.deadlineOutcome ?? 'failed';
323
- transitions.push(...this.remove(
324
- activation.spec.activationId,
325
- outcome,
326
- outcome === 'completed' ? 'duration_elapsed' : 'deadline_elapsed',
327
- now,
328
- ));
329
- }
330
- }
331
- if (this.reflex || this.short) return transitions;
332
- // Direct Agent Actions may rearm the idle delay during a meeting. Keep the
333
- // deadline checks above, but never hand long control back inside a boundary.
334
- if (this.boundaryActive) return transitions;
335
-
336
- if (this.long?.state === 'suspended') {
337
- if (this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
338
- this.longEligibleAt = undefined;
339
- transitions.push(this.restart(this.long, now, 'idle_delay_elapsed'));
340
- }
341
- return transitions;
342
- }
343
-
344
- if (!this.long && this.fallback && this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
345
- if (this.fallbackStartedGeneration === this.idleGeneration) return transitions;
346
- this.fallbackStartedGeneration = this.idleGeneration;
347
- this.longEligibleAt = undefined;
348
- const activation = this.activation({
349
- activationId: this.createActivationId(),
350
- behaviorId: this.fallback.behaviorId,
351
- input: this.fallback.input,
352
- layer: 'long',
353
- source: 'idle',
354
- requestedAt: now,
355
- }, now);
356
- this.long = activation;
357
- transitions.push(this.transition(activation, 'started', now, 'idle_fallback_started'));
358
- }
359
- return transitions;
360
- }
361
-
362
- current(): BehaviorActivationSnapshot | undefined {
363
- return this.snapshotActivation(
364
- this.reflex ?? this.short ?? (this.long?.state === 'running' ? this.long : undefined),
365
- );
366
- }
367
-
368
- /** New immutable input, same activation and deadline; old decision generations expire. */
369
- updateInput(activationId: string, input: Readonly<Record<string, unknown>>, now: number): readonly BehaviorActivationTransition[] {
370
- const active = [this.long, this.short, this.reflex].find(entry => entry?.spec.activationId === activationId);
371
- if (!active) throw new Error('behavior_activation_not_found');
372
- active.spec = { ...active.spec, input: cloneInput(input) };
373
- active.instanceGeneration += 1;
374
- return [this.transition(active, active.state === 'running' ? 'restarted' : 'suspended', now, 'behavior_input_updated')];
375
- }
376
-
377
- updateFallbackInput(behaviorId: string, input: Readonly<Record<string, unknown>>): void {
378
- if (this.fallback?.behaviorId === behaviorId) this.fallback = { behaviorId, input: cloneInput(input) };
379
- }
380
-
381
- snapshot(): Readonly<{
382
- long?: BehaviorActivationSnapshot;
383
- short?: BehaviorActivationSnapshot;
384
- reflex?: BehaviorActivationSnapshot;
385
- fallback?: BehaviorFallbackBinding;
386
- idleMs: number;
387
- longEligibleAt?: number;
388
- }> {
389
- return Object.freeze({
390
- ...(this.long ? { long: this.snapshotActivation(this.long) } : {}),
391
- ...(this.short ? { short: this.snapshotActivation(this.short) } : {}),
392
- ...(this.reflex ? { reflex: this.snapshotActivation(this.reflex) } : {}),
393
- ...(this.fallback ? { fallback: structuredClone(this.fallback) } : {}),
394
- idleMs: this.idleMs,
395
- ...(this.longEligibleAt !== undefined ? { longEligibleAt: this.longEligibleAt } : {}),
396
- });
397
- }
398
-
399
- isCurrent(activationId: string, instanceGeneration: number): boolean {
400
- const current = this.current();
401
- return current?.activationId === activationId
402
- && current.instanceGeneration === instanceGeneration
403
- && current.state === 'running';
404
- }
405
-
406
- private remove(
407
- activationId: string,
408
- outcome: 'completed' | 'failed' | 'cancelled',
409
- reason: string,
410
- now: number,
411
- ): BehaviorActivationTransition[] {
412
- const layer = this.findLayer(activationId);
413
- if (!layer) return [];
414
- const activation = this[layer] as MutableActivation;
415
- const transitions: BehaviorActivationTransition[] = [
416
- this.transition(activation, outcome, now, reason),
417
- ];
418
- this[layer] = undefined;
419
-
420
- if (layer === 'reflex') {
421
- if (this.short) transitions.push(this.restart(this.short, now, 'reflex_ended'));
422
- else this.longEligibleAt = now + this.idleMs;
423
- } else if (layer === 'short') {
424
- if (!this.reflex) this.longEligibleAt = now + this.idleMs;
425
- } else if (!this.short && !this.reflex) {
426
- this.longEligibleAt = now + this.idleMs;
427
- }
428
- return transitions;
429
- }
430
-
431
- private findLayer(activationId: string): BehaviorActivationLayer | undefined {
432
- if (this.reflex?.spec.activationId === activationId) return 'reflex';
433
- if (this.short?.spec.activationId === activationId) return 'short';
434
- if (this.long?.spec.activationId === activationId) return 'long';
435
- return undefined;
436
- }
437
-
438
- private activation(spec: BehaviorActivationSpec, now: number): MutableActivation {
439
- const validated = validateSpec(spec);
440
- return {
441
- spec: validated,
442
- state: 'running',
443
- instanceGeneration: 1,
444
- startedAt: now,
445
- ...(validated.maxRuntimeMs !== undefined
446
- ? { deadlineAt: now + validated.maxRuntimeMs }
447
- : {}),
448
- };
449
- }
450
-
451
- private restart(activation: MutableActivation, now: number, reason: string): BehaviorActivationTransition {
452
- activation.state = 'running';
453
- activation.instanceGeneration += 1;
454
- activation.startedAt = now;
455
- if (activation.spec.maxRuntimeMs !== undefined) {
456
- // A suspended activation keeps its original deadline. Fresh restart is
457
- // about module state and input, not extending its authority lease.
458
- activation.deadlineAt ??= activation.spec.requestedAt + activation.spec.maxRuntimeMs;
459
- }
460
- return this.transition(activation, 'restarted', now, reason);
461
- }
462
-
463
- private transition(
464
- activation: MutableActivation,
465
- type: BehaviorActivationTransitionType,
466
- at: number,
467
- reason: string,
468
- replacedByActivationId?: string,
469
- ): BehaviorActivationTransition {
470
- return Object.freeze({
471
- type,
472
- activationId: activation.spec.activationId,
473
- behaviorId: activation.spec.behaviorId,
474
- layer: activation.spec.layer,
475
- at,
476
- reason,
477
- instanceGeneration: activation.instanceGeneration,
478
- ...(replacedByActivationId ? { replacedByActivationId } : {}),
479
- });
480
- }
481
-
482
- private snapshotActivation(
483
- activation: MutableActivation | undefined,
484
- ): BehaviorActivationSnapshot | undefined {
485
- if (!activation) return undefined;
486
- return Object.freeze({
487
- ...activation.spec,
488
- input: cloneInput(activation.spec.input),
489
- state: activation.state,
490
- instanceGeneration: activation.instanceGeneration,
491
- ...(activation.startedAt !== undefined ? { startedAt: activation.startedAt } : {}),
492
- ...(activation.deadlineAt !== undefined ? { deadlineAt: activation.deadlineAt } : {}),
493
- });
494
- }
495
- }
1
+ export * from '@myclaw163/game-agent-runtime/strategy/activation-manager.js';