@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,580 +1,68 @@
1
- import { randomUUID } from 'node:crypto';
2
- import {
3
- DEFAULT_EVENT_CONSUMER_ID,
4
- type CanonicalEvent,
5
- type ConsumerLease,
6
- type DetailDeliveryVia,
7
- type EventRepository,
8
- validateDetailDeliveryVia,
9
- } from '../../../framework/events/index.js';
1
+ import { AgentMailboxCoordinator as CoreCoordinator, type AgentMailboxCoordinatorOptions } from '@myclaw163/game-agent-runtime/mailbox/agent-mailbox-coordinator.js';
10
2
  import type { RuntimeReadyView } from '../../../framework/runtime.js';
11
- import type { ClawclawMailboxAdapterDescriptor } from './mailbox-plugin.js';
12
-
13
- export const AGENT_MAILBOX_COALESCE_MS = 220;
14
- const AGENT_MAILBOX_LEASE_TTL_MS = 5 * 60_000;
15
- const AGENT_MAILBOX_PREPARE_WAIT_MS = 5_000;
16
- const READY_VIEW_RETRY_MS = 25;
17
-
18
- export type AgentMailboxDeliveryVia = DetailDeliveryVia;
19
-
20
- export interface AgentMailboxBatch {
21
- state: Record<string, unknown> | null;
22
- events: Array<Record<string, unknown> | string>;
23
- }
24
-
25
- export interface PreparedAgentMailboxBatch {
26
- batch: AgentMailboxBatch;
27
- deliveryToken?: string;
28
- readyEpochSeq: number;
29
- /** Earliest useful retry when the coalescing or Ready View boundary is pending. */
30
- nextAttemptAtMs?: number;
31
- }
32
-
33
- export interface PrepareAgentMailboxBatchOptions {
34
- readyView?: RuntimeReadyView;
35
- /** Pull adapters use an explicit query boundary and do not need push coalescing. */
36
- bypassDelay?: boolean;
37
- deliveryVia?: AgentMailboxDeliveryVia;
38
- ownerIdPrefix?: string;
39
- /** Adapter-specific lease lifetime; omitted adapters use the Mailbox default. */
40
- leaseTtlMs?: number;
41
- }
42
-
43
- export interface AgentMailboxCoordinatorOptions {
44
- repository: EventRepository;
45
- readyView: () => RuntimeReadyView;
46
- presentEvent: (
47
- event: CanonicalEvent,
48
- state: Record<string, any> | null | undefined,
49
- ) => Record<string, unknown> | string;
50
- compactState: (
51
- state: Record<string, any> | null | undefined,
52
- events?: Array<Record<string, any>>,
53
- ) => Record<string, any> | null;
54
- /** Best-effort observer after this consumer accepts a batch. */
55
- onDelivered?: (events: readonly CanonicalEvent[]) => void;
56
- /** Adapter-specific selection; omitted adapters receive every Agent-visible Event. */
57
- eventFilter?: (
58
- event: CanonicalEvent,
59
- state: Record<string, any> | null | undefined,
60
- ) => boolean;
61
- /**
62
- * Also pull Events deliberately delegated by a Monitor lane. This is used
63
- * when a bounded short-notification queue suppresses its overflow and tells
64
- * the Agent to read the durable remainder with `ccl events`.
65
- */
66
- delegatedMonitorConsumerId?: string;
67
- consumerId?: string;
68
- /** Declares this coordinator when it is itself a complete output adapter. */
69
- adapter?: ClawclawMailboxAdapterDescriptor;
70
- coalesceMs?: number;
71
- leaseTtlMs?: number;
72
- now?: () => number;
73
- diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
74
- }
75
-
76
- interface PreparedDelivery {
77
- lease: ConsumerLease;
78
- leaseTtlMs: number;
79
- eventIds: string[];
80
- readyEpochSeq: number;
81
- sessionId: string;
82
- segmentIds: string[];
83
- deliveryVia: AgentMailboxDeliveryVia;
84
- }
85
-
86
- interface AgentDelayWindow {
87
- sessionId: string;
88
- firstCommitSeq: number;
89
- deadlineMs: number;
90
- }
91
-
3
+ export type { AgentMailboxBatch, PreparedAgentMailboxBatch, PrepareAgentMailboxBatchOptions, AgentMailboxDeliveryVia, AgentMailboxCoordinatorOptions } from '@myclaw163/game-agent-runtime/mailbox/agent-mailbox-coordinator.js';
4
+ export { AGENT_MAILBOX_COALESCE_MS } from '@myclaw163/game-agent-runtime/mailbox/agent-mailbox-coordinator.js';
92
5
  function nonEmptyString(value: unknown): string | undefined {
93
- return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
6
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
94
7
  }
95
-
96
- function emptyBatch(state: Record<string, unknown> | null = null): AgentMailboxBatch {
97
- return { state, events: [] };
98
- }
99
-
100
8
  function compactBehaviorActivation(value: unknown): Record<string, unknown> | undefined {
101
- if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
102
- const activation = value as Record<string, unknown>;
103
- const id = nonEmptyString(activation.activationId);
104
- const behavior = nonEmptyString(activation.behaviorId);
105
- const layer = nonEmptyString(activation.layer);
106
- if (!id || !behavior || !layer) return undefined;
107
- return {
108
- id,
109
- behavior,
110
- layer,
111
- ...(nonEmptyString(activation.source) ? { source: nonEmptyString(activation.source) } : {}),
112
- ...(nonEmptyString(activation.state) ? { state: nonEmptyString(activation.state) } : {}),
113
- ...(Number.isSafeInteger(activation.instanceGeneration)
114
- ? { instance_generation: activation.instanceGeneration }
115
- : {}),
116
- };
117
- }
118
-
119
- function compactBehaviorStateForAgent(
120
- value: unknown,
121
- outcome: RuntimeReadyView['pluginOutcomes'][string] | undefined,
122
- ): Record<string, unknown> | null {
123
- const status = value && typeof value === 'object' && !Array.isArray(value)
124
- ? value as Record<string, unknown>
125
- : {};
126
- const stackValue = status.stack && typeof status.stack === 'object' && !Array.isArray(status.stack)
127
- ? status.stack as Record<string, unknown>
128
- : {};
129
- const stack = Object.fromEntries(
130
- (['long', 'short', 'reflex'] as const).flatMap((layer) => {
131
- const activation = compactBehaviorActivation(stackValue[layer]);
132
- return activation ? [[layer, activation]] : [];
133
- }),
134
- );
135
- const semantic = status.status && typeof status.status === 'object' && !Array.isArray(status.status)
136
- ? status.status as Record<string, unknown>
137
- : {};
138
- const currentId = nonEmptyString(status.activation_id);
139
- const behavior = nonEmptyString(status.behavior);
140
- const layer = nonEmptyString(status.layer);
141
- const result = {
142
- running: status.running === true,
143
- ...(currentId ? { id: currentId } : {}),
144
- ...(behavior ? { behavior } : {}),
145
- ...(layer ? { layer } : {}),
146
- ...(nonEmptyString(status.source) ? { source: nonEmptyString(status.source) } : {}),
147
- ...(Number.isSafeInteger(status.instance_generation)
148
- ? { instance_generation: status.instance_generation }
149
- : {}),
150
- ...(nonEmptyString(semantic.summary) ? { doing: nonEmptyString(semantic.summary) } : {}),
151
- ...(Object.keys(stack).length > 0 ? { stack } : {}),
152
- ...(outcome?.outcome === 'failed' ? { issue: outcome.reason } : {}),
153
- };
154
- return status.running === true || Object.keys(stack).length > 0 || outcome?.outcome === 'failed'
155
- ? result
156
- : null;
157
- }
158
-
159
- /**
160
- * Durable Agent communication core owned by the Mailbox Plugin.
161
- *
162
- * One instance owns exactly one output consumer: Ready View selection, full
163
- * Agent presentation, coalescing and its details lease. Desktop IPC, Claude
164
- * Channels and legacy pull commands use separate instances so every output
165
- * advances only its own ACK state.
166
- */
167
- export class AgentMailboxCoordinator {
168
- readonly adapter?: ClawclawMailboxAdapterDescriptor;
169
- private readonly onDelivered?: AgentMailboxCoordinatorOptions['onDelivered'];
170
- private readonly repository: EventRepository;
171
- private readonly readyView: () => RuntimeReadyView;
172
- private readonly presentEvent: AgentMailboxCoordinatorOptions['presentEvent'];
173
- private readonly compactState: AgentMailboxCoordinatorOptions['compactState'];
174
- private readonly eventFilter: NonNullable<AgentMailboxCoordinatorOptions['eventFilter']>;
175
- private readonly delegatedMonitorConsumerId?: string;
176
- private readonly consumerId: string;
177
- private readonly coalesceMs: number;
178
- private readonly leaseTtlMs: number;
179
- private readonly now: () => number;
180
- private readonly diagnostic?: AgentMailboxCoordinatorOptions['diagnostic'];
181
- private readonly prepared = new Map<string, PreparedDelivery>();
182
- private readonly preparedSlotWaiters = new Set<() => void>();
183
- private prepareTail: Promise<void> = Promise.resolve();
184
- private delayWindow?: AgentDelayWindow;
185
- private lastObservedReadyEpochSeq = 0;
186
- private stopped = false;
187
-
188
- constructor(options: AgentMailboxCoordinatorOptions) {
189
- this.onDelivered = options.onDelivered;
190
- this.repository = options.repository;
191
- this.readyView = options.readyView;
192
- this.presentEvent = options.presentEvent;
193
- this.compactState = options.compactState;
194
- this.eventFilter = options.eventFilter ?? (() => true);
195
- this.delegatedMonitorConsumerId = options.delegatedMonitorConsumerId;
196
- this.consumerId = options.consumerId ?? DEFAULT_EVENT_CONSUMER_ID;
197
- this.adapter = options.adapter;
198
- this.coalesceMs = options.coalesceMs ?? AGENT_MAILBOX_COALESCE_MS;
199
- this.leaseTtlMs = options.leaseTtlMs ?? AGENT_MAILBOX_LEASE_TTL_MS;
200
- this.now = options.now ?? Date.now;
201
- this.diagnostic = options.diagnostic;
202
- if (this.adapter?.acknowledgement === 'none') {
203
- throw new Error('A durable Agent Mailbox coordinator cannot use acknowledgement none.');
204
- }
205
- if (this.adapter && this.adapter.consumerId !== this.consumerId) {
206
- throw new Error(
207
- `Mailbox adapter '${this.adapter.id}' must use coordinator consumerId '${this.consumerId}'.`,
208
- );
209
- }
210
- if (!Number.isFinite(this.coalesceMs) || this.coalesceMs < 0) {
211
- throw new Error('Agent Mailbox coalesceMs must be non-negative.');
212
- }
213
- if (!Number.isFinite(this.leaseTtlMs) || this.leaseTtlMs <= 0) {
214
- throw new Error('Agent Mailbox leaseTtlMs must be positive.');
215
- }
216
- }
217
-
218
- prepare(options: PrepareAgentMailboxBatchOptions = {}): PreparedAgentMailboxBatch {
219
- return this.prepareEvents(options);
220
- }
221
-
222
- /** Selects and projects one durable Agent-facing Event batch. */
223
- prepareEvents(options: PrepareAgentMailboxBatchOptions = {}): PreparedAgentMailboxBatch {
224
- this.assertRunning();
225
- this.releaseExpiredPrepared();
226
- if (this.prepared.size > 0) throw new Error('agent_mailbox_delivery_busy');
227
-
228
- const ready = this.captureReadyView(options.readyView);
229
- if (ready.epochSeq <= 0) {
230
- return {
231
- batch: emptyBatch(),
232
- readyEpochSeq: 0,
233
- ...(this.delayWindow ? { nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS } : {}),
234
- };
235
- }
236
-
237
- const state = this.compactReadyState(ready);
238
- this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
239
- const pending = this.repository.listEvents({
240
- sessionId: ready.scope.sessionId,
241
- detailStates: ['pending', 'deferred'],
242
- maxCommitSeq: ready.eventWatermark,
243
- maxEpochSeq: ready.epochSeq,
244
- order: 'asc',
245
- }, this.consumerId, ['details']).filter((row) => (
246
- (options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
247
- && this.selectsEvent(row.event, ready.state.state)
248
- ));
249
- if (pending.length === 0) {
250
- const eventIsBeyondReadyBoundary = this.delayWindow?.sessionId === ready.scope.sessionId
251
- && this.delayWindow.firstCommitSeq > ready.eventWatermark;
252
- if (eventIsBeyondReadyBoundary) {
253
- return {
254
- batch: emptyBatch(state),
255
- readyEpochSeq: ready.epochSeq,
256
- nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS,
257
- };
258
- }
259
- this.delayWindow = undefined;
260
- return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
261
- }
262
-
263
- if (!options.bypassDelay && !pending.some(({ event }) => event.wakeAgent !== false)) {
264
- this.delayWindow = undefined;
265
- return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
266
- }
267
-
268
- if (this.delayWindow?.sessionId !== ready.scope.sessionId) {
269
- this.delayWindow = {
270
- sessionId: ready.scope.sessionId,
271
- firstCommitSeq: pending[0]!.event.commitSeq,
272
- deadlineMs: this.now() + this.coalesceMs,
273
- };
274
- }
275
- if (!options.bypassDelay && this.now() < this.delayWindow.deadlineMs) {
276
- return {
277
- batch: emptyBatch(state),
278
- readyEpochSeq: ready.epochSeq,
279
- nextAttemptAtMs: this.delayWindow.deadlineMs,
280
- };
281
- }
282
-
283
- const deliveryVia = validateDetailDeliveryVia(options.deliveryVia ?? 'mailbox_full');
284
- const leaseTtlMs = options.leaseTtlMs ?? this.leaseTtlMs;
285
- if (!Number.isFinite(leaseTtlMs) || leaseTtlMs <= 0) {
286
- throw new Error('Agent Mailbox leaseTtlMs must be positive.');
287
- }
288
- const lease = this.repository.acquireLease({
289
- consumerId: this.consumerId,
290
- channel: 'details',
291
- ownerId: `${options.ownerIdPrefix ?? 'agent_mailbox'}:${randomUUID()}`,
292
- ttlMs: leaseTtlMs,
293
- nowMs: this.now(),
294
- });
295
- if (!lease) throw new Error('agent_mailbox_delivery_busy');
296
-
297
- try {
298
- const candidates = this.repository.listEvents({
299
- sessionId: ready.scope.sessionId,
300
- detailStates: ['pending', 'deferred'],
301
- maxCommitSeq: ready.eventWatermark,
302
- maxEpochSeq: ready.epochSeq,
303
- order: 'desc',
304
- }, this.consumerId, ['details']).filter((row) => (
305
- (options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
306
- && this.selectsEvent(row.event, ready.state.state)
307
- ));
308
- if (candidates.length === 0) {
309
- this.delayWindow = undefined;
310
- this.repository.releaseLease(lease);
311
- return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
312
- }
313
-
314
- const deliveryToken = randomUUID();
315
- const segmentIds = [...new Set(candidates.map((row) => row.event.segmentId))];
316
- this.prepared.set(deliveryToken, {
317
- lease,
318
- leaseTtlMs,
319
- eventIds: candidates.map((row) => row.event.eventId),
320
- readyEpochSeq: ready.epochSeq,
321
- sessionId: ready.scope.sessionId,
322
- segmentIds,
323
- deliveryVia,
324
- });
325
- this.delayWindow = undefined;
326
- this.diagnostic?.('runtime.agent_mailbox.delivery_prepared', {
327
- consumer: this.consumerId,
328
- delivery_token: deliveryToken,
329
- delivery_via: deliveryVia,
330
- session_id: ready.scope.sessionId,
331
- segment_ids: segmentIds,
332
- ready_epoch_seq: ready.epochSeq,
333
- event_count: candidates.length,
334
- });
335
- return {
336
- batch: {
337
- state,
338
- events: candidates.map((row) => this.presentEvent(row.event, ready.state.state)),
339
- },
340
- deliveryToken,
341
- readyEpochSeq: ready.epochSeq,
342
- };
343
- } catch (error) {
344
- this.repository.releaseLease(lease);
345
- throw error;
346
- }
347
- }
348
-
349
- prepareWhenAvailable(
350
- options: PrepareAgentMailboxBatchOptions = {},
351
- timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS,
352
- ): Promise<PreparedAgentMailboxBatch> {
353
- return this.prepareEventsWhenAvailable(options, timeoutMs);
354
- }
355
-
356
- prepareEventsWhenAvailable(
357
- options: PrepareAgentMailboxBatchOptions = {},
358
- timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS,
359
- ): Promise<PreparedAgentMailboxBatch> {
360
- const operation = this.prepareTail.then(async () => {
361
- await this.waitForPreparedSlot(timeoutMs);
362
- return this.prepareEvents(options);
363
- });
364
- this.prepareTail = operation.then(() => undefined, () => undefined);
365
- return operation;
366
- }
367
-
368
- stateForReadyView(readyView?: RuntimeReadyView): Record<string, any> | null {
369
- this.assertRunning();
370
- return this.compactReadyState(this.captureReadyView(readyView));
371
- }
372
-
373
- ack(deliveryToken: string): boolean {
374
- const prepared = this.prepared.get(deliveryToken);
375
- if (!prepared || !this.renewPreparedLease(prepared)) return false;
376
- const nowMs = this.now();
377
- const transition = {
378
- eventIds: prepared.eventIds,
379
- consumerId: this.consumerId,
380
- from: ['pending', 'deferred'],
381
- to: 'delivered',
382
- deliveredAt: new Date(nowMs).toISOString(),
383
- deliveryVia: prepared.deliveryVia,
384
- lease: prepared.lease,
385
- nowMs,
386
- } as Parameters<EventRepository['transitionDetails']>[0];
387
- const changed = this.repository.transitionDetails(transition);
388
- if (changed !== prepared.eventIds.length) return false;
389
- try {
390
- this.onDelivered?.(prepared.eventIds.flatMap((id) => {
391
- const event = this.repository.eventById(id);
392
- return event ? [event] : [];
393
- }));
394
- } catch { /* Display reporting must not affect delivery ACK. */ }
395
- this.prepared.delete(deliveryToken);
396
- this.repository.releaseLease(prepared.lease);
397
- this.notifyPreparedSlotAvailable();
398
- this.diagnostic?.('runtime.agent_mailbox.delivery_acked', {
399
- consumer: this.consumerId,
400
- delivery_token: deliveryToken,
401
- delivery_via: prepared.deliveryVia,
402
- session_id: prepared.sessionId,
403
- segment_ids: prepared.segmentIds,
404
- ready_epoch_seq: prepared.readyEpochSeq,
405
- event_count: prepared.eventIds.length,
406
- });
407
- return true;
408
- }
409
-
410
- renew(deliveryToken: string): boolean {
411
- const prepared = this.prepared.get(deliveryToken);
412
- return prepared ? this.renewPreparedLease(prepared) : false;
413
- }
414
-
415
- release(deliveryToken: string): boolean {
416
- const prepared = this.prepared.get(deliveryToken);
417
- if (!prepared) return false;
418
- this.prepared.delete(deliveryToken);
419
- const released = this.repository.releaseLease(prepared.lease);
420
- this.delayWindow = {
421
- sessionId: prepared.sessionId,
422
- firstCommitSeq: 0,
423
- deadlineMs: this.now(),
9
+ if (!value || typeof value !== 'object' || Array.isArray(value))
10
+ return undefined;
11
+ const activation = value as Record<string, unknown>;
12
+ const id = nonEmptyString(activation.activationId);
13
+ const behavior = nonEmptyString(activation.behaviorId);
14
+ const layer = nonEmptyString(activation.layer);
15
+ if (!id || !behavior || !layer)
16
+ return undefined;
17
+ return {
18
+ id,
19
+ behavior,
20
+ layer,
21
+ ...(nonEmptyString(activation.source) ? { source: nonEmptyString(activation.source) } : {}),
22
+ ...(nonEmptyString(activation.state) ? { state: nonEmptyString(activation.state) } : {}),
23
+ ...(Number.isSafeInteger(activation.instanceGeneration)
24
+ ? { instance_generation: activation.instanceGeneration }
25
+ : {}),
424
26
  };
425
- this.notifyPreparedSlotAvailable();
426
- this.diagnostic?.('runtime.agent_mailbox.delivery_released', {
427
- consumer: this.consumerId,
428
- delivery_token: deliveryToken,
429
- delivery_via: prepared.deliveryVia,
430
- session_id: prepared.sessionId,
431
- segment_ids: prepared.segmentIds,
432
- ready_epoch_seq: prepared.readyEpochSeq,
433
- event_count: prepared.eventIds.length,
434
- released,
435
- });
436
- return released;
437
- }
438
-
439
- observeEvents(events: readonly CanonicalEvent[]): void {
440
- const first = events
441
- .filter((event) => (
442
- event.deliveryClass === 'monitor_and_events'
443
- && this.selectsEvent(event, undefined)
444
- ))
445
- .sort((left, right) => left.commitSeq - right.commitSeq)[0];
446
- if (!first || this.delayWindow?.sessionId === first.sessionId) return;
447
- this.delayWindow = {
448
- sessionId: first.sessionId,
449
- firstCommitSeq: first.commitSeq,
450
- deadlineMs: this.now() + this.coalesceMs,
27
+ }
28
+ function compactBehaviorStateForAgent(value: unknown, outcome: RuntimeReadyView['pluginOutcomes'][string] | undefined): Record<string, unknown> | null {
29
+ const status = value && typeof value === 'object' && !Array.isArray(value)
30
+ ? value as Record<string, unknown>
31
+ : {};
32
+ const stackValue = status.stack && typeof status.stack === 'object' && !Array.isArray(status.stack)
33
+ ? status.stack as Record<string, unknown>
34
+ : {};
35
+ const stack = Object.fromEntries((['long', 'short', 'reflex'] as const).flatMap((layer) => {
36
+ const activation = compactBehaviorActivation(stackValue[layer]);
37
+ return activation ? [[layer, activation]] : [];
38
+ }));
39
+ const semantic = status.status && typeof status.status === 'object' && !Array.isArray(status.status)
40
+ ? status.status as Record<string, unknown>
41
+ : {};
42
+ const currentId = nonEmptyString(status.activation_id);
43
+ const behavior = nonEmptyString(status.behavior);
44
+ const layer = nonEmptyString(status.layer);
45
+ const result = {
46
+ running: status.running === true,
47
+ ...(currentId ? { id: currentId } : {}),
48
+ ...(behavior ? { behavior } : {}),
49
+ ...(layer ? { layer } : {}),
50
+ ...(nonEmptyString(status.source) ? { source: nonEmptyString(status.source) } : {}),
51
+ ...(Number.isSafeInteger(status.instance_generation)
52
+ ? { instance_generation: status.instance_generation }
53
+ : {}),
54
+ ...(nonEmptyString(semantic.summary) ? { doing: nonEmptyString(semantic.summary) } : {}),
55
+ ...(Object.keys(stack).length > 0 ? { stack } : {}),
56
+ ...(outcome?.outcome === 'failed' ? { issue: outcome.reason } : {}),
451
57
  };
452
- }
453
-
454
- async flush(): Promise<void> {
455
- if (this.delayWindow) this.delayWindow.deadlineMs = this.now();
456
- }
457
-
458
- async waitForDrain(shouldAbort: () => boolean = () => false): Promise<boolean> {
459
- while (!shouldAbort()) {
460
- const ready = this.captureReadyView();
461
- if (ready.epochSeq <= 0) return this.prepared.size === 0;
462
- this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
463
- const pending = this.repository.listEvents({
464
- sessionId: ready.scope.sessionId,
465
- deliveryClasses: ['monitor_and_events'],
466
- detailStates: ['pending', 'deferred'],
467
- maxCommitSeq: ready.eventWatermark,
468
- maxEpochSeq: ready.epochSeq,
469
- order: 'asc',
470
- }, this.consumerId, ['details']).filter((row) => (
471
- this.selectsEvent(row.event, ready.state.state)
472
- ));
473
- if (!pending.some(({ event }) => event.wakeAgent !== false) && this.prepared.size === 0) return true;
474
- await new Promise<void>((resolve) => {
475
- const timer = setTimeout(resolve, READY_VIEW_RETRY_MS);
476
- timer.unref?.();
477
- });
478
- }
479
- return false;
480
- }
481
-
482
- async stop(): Promise<void> {
483
- if (this.stopped) return;
484
- this.stopped = true;
485
- for (const token of [...this.prepared.keys()]) this.release(token);
486
- }
487
-
488
- private selectsEvent(
489
- event: CanonicalEvent,
490
- state: Record<string, any> | null | undefined,
491
- ): boolean {
492
- if (event.deliveryClass === 'events_only') return true;
493
- if (this.delegatedMonitorConsumerId && event.deliveryClass !== 'internal_only' && event.wakeAgent === false) return true;
494
- if (this.eventFilter(event, state)) return true;
495
- if (!this.delegatedMonitorConsumerId) return false;
496
- return this.repository.delivery(event.eventId, this.delegatedMonitorConsumerId)
497
- ?.monitorState === 'suppressed';
498
- }
499
-
500
- private captureReadyView(readyView?: RuntimeReadyView): RuntimeReadyView {
501
- const ready = structuredClone(readyView ?? this.readyView());
502
- if (ready.epochSeq > this.lastObservedReadyEpochSeq) {
503
- this.diagnostic?.('runtime.agent_mailbox.ready_advanced', {
504
- previous_ready_epoch_seq: this.lastObservedReadyEpochSeq,
505
- ready_epoch_seq: ready.epochSeq,
506
- event_commit_seq: ready.eventWatermark,
507
- frame_seq: ready.frameSeq,
508
- });
509
- this.lastObservedReadyEpochSeq = ready.epochSeq;
510
- }
511
- return ready;
512
- }
513
-
514
- private compactReadyState(ready: RuntimeReadyView): Record<string, any> | null {
515
- if (!ready.state.state) return null;
516
- const state = this.compactState(ready.state.state);
517
- if (!state) return null;
518
- const behavior = compactBehaviorStateForAgent(
519
- ready.pluginStates['behavior.status']?.value,
520
- ready.pluginOutcomes['clawclaw.behavior'],
521
- );
58
+ return status.running === true || Object.keys(stack).length > 0 || outcome?.outcome === 'failed'
59
+ ? result
60
+ : null;
61
+ }
62
+ export function projectClawclawMailboxState(state: Record<string, any>, ready: RuntimeReadyView): Record<string, any> {
63
+ const behavior = compactBehaviorStateForAgent(ready.pluginStates['behavior.status']?.value, ready.pluginOutcomes['clawclaw.behavior']);
522
64
  return behavior ? { ...state, behavior } : state;
523
- }
524
-
525
- private releaseExpiredPrepared(): void {
526
- const nowMs = this.now();
527
- for (const [token, prepared] of this.prepared) {
528
- if (prepared.lease.expiresAt > nowMs) continue;
529
- this.prepared.delete(token);
530
- this.repository.releaseLease(prepared.lease);
531
- }
532
- this.notifyPreparedSlotAvailable();
533
- }
534
-
535
- private renewPreparedLease(prepared: PreparedDelivery): boolean {
536
- const renewed = this.repository.acquireLease({
537
- consumerId: prepared.lease.consumerId,
538
- channel: prepared.lease.channel,
539
- ownerId: prepared.lease.ownerId,
540
- ttlMs: prepared.leaseTtlMs,
541
- nowMs: this.now(),
542
- });
543
- if (!renewed) return false;
544
- prepared.lease = renewed;
545
- return true;
546
- }
547
-
548
- private waitForPreparedSlot(timeoutMs: number): Promise<void> {
549
- this.assertRunning();
550
- this.releaseExpiredPrepared();
551
- if (this.prepared.size === 0) return Promise.resolve();
552
- const boundedTimeoutMs = Math.max(1, Math.trunc(timeoutMs));
553
- return new Promise((resolve, reject) => {
554
- let timer: ReturnType<typeof setTimeout> | undefined;
555
- const cleanup = (): void => {
556
- if (timer) clearTimeout(timer);
557
- this.preparedSlotWaiters.delete(available);
558
- };
559
- const available = (): void => {
560
- cleanup();
561
- resolve();
562
- };
563
- this.preparedSlotWaiters.add(available);
564
- timer = setTimeout(() => {
565
- cleanup();
566
- reject(new Error('agent_mailbox_delivery_busy'));
567
- }, boundedTimeoutMs);
568
- timer.unref?.();
569
- });
570
- }
571
-
572
- private notifyPreparedSlotAvailable(): void {
573
- if (this.prepared.size > 0) return;
574
- for (const waiter of [...this.preparedSlotWaiters]) waiter();
575
- }
576
-
577
- private assertRunning(): void {
578
- if (this.stopped) throw new Error('agent_mailbox_stopped');
579
- }
65
+ }
66
+ export class AgentMailboxCoordinator extends CoreCoordinator {
67
+ constructor(options: AgentMailboxCoordinatorOptions) { super({ ...options, projectState: options.projectState ?? projectClawclawMailboxState }); }
580
68
  }