@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,93 +1,8 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { createConnection, type Socket } from 'node:net';
3
- import type {
4
- MailboxEventBatchAcceptance,
5
- MailboxEventBatchEnvelope,
6
- MailboxEventBatchSink,
7
- } from './mailbox-event-batch-delivery.js';
8
-
1
+ import { DesktopEventSocketSink as CoreDesktopSink, type DesktopEventSocketOptions as CoreOptions } from '@myclaw163/game-agent-runtime/mailbox/adapters/desktop-event-socket.js';
2
+ export { DesktopEventSocketDeliveryError, normalizeDesktopEventSocketPath, validateDesktopEventToken } from '@myclaw163/game-agent-runtime/mailbox/adapters/desktop-event-socket.js';
3
+ export type { DesktopEventSocketConfig, DesktopActiveResource, DesktopActiveResources, DesktopEventDescriptor } from '@myclaw163/game-agent-runtime/mailbox/adapters/desktop-event-socket.js';
9
4
  export const DESKTOP_EVENT_PROTOCOL_SCHEMA = 'ccl.desktop-events.v1';
10
-
11
- const WINDOWS_PIPE_PREFIX = '\\\\.\\pipe\\';
12
- const MAX_ACK_BUFFER_CHARACTERS = 64 * 1024;
13
- const DEFAULT_ACK_TIMEOUT_MS = 10_000;
14
- const DEFAULT_RECONNECT_BASE_MS = 100;
15
- const DEFAULT_RECONNECT_MAX_MS = 5_000;
16
-
17
- export interface DesktopEventSocketConfig {
18
- socketPath: string;
19
- token: string;
20
- }
21
-
22
- export interface DesktopActiveResource {
23
- readonly id: string;
24
- readonly name: string;
25
- readonly description: string;
26
- }
27
-
28
- export interface DesktopActiveResources {
29
- readonly locale: string;
30
- readonly strategy: DesktopActiveResource | null;
31
- readonly perceptions: readonly DesktopActiveResource[];
32
- }
33
-
34
- export interface DesktopEventDescriptor {
35
- readonly type: string;
36
- readonly perception_id: string;
37
- readonly name: string;
38
- readonly description: string;
39
- }
40
-
41
- export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
42
- ackTimeoutMs?: number;
43
- reconnectBaseMs?: number;
44
- reconnectMaxMs?: number;
45
- now?: () => number;
46
- platform?: NodeJS.Platform;
47
- onConnected?: () => void;
48
- activeResources?: () => DesktopActiveResources;
49
- eventDescriptors?: () => readonly DesktopEventDescriptor[];
50
- diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
51
- }
52
-
53
- interface PendingDesktopAck {
54
- connectionId: string;
55
- seq: number;
56
- deliveryId: string;
57
- timer: ReturnType<typeof setTimeout>;
58
- signal: AbortSignal;
59
- onAbort: () => void;
60
- resolve: (acceptance: MailboxEventBatchAcceptance) => void;
61
- reject: (error: Error) => void;
62
- }
63
-
64
- interface DesktopDeliveryMetadata {
65
- readonly deliveryId: string;
66
- readonly activeResources: DesktopActiveResources | undefined;
67
- readonly eventDescriptors: readonly DesktopEventDescriptor[];
68
- }
69
-
70
- export class DesktopEventSocketDeliveryError extends Error {
71
- readonly code: string;
72
- readonly retryable: boolean;
73
-
74
- constructor(code: string, message: string, retryable = true) {
75
- super(message);
76
- this.name = 'DesktopEventSocketDeliveryError';
77
- this.code = code;
78
- this.retryable = retryable;
79
- }
80
- }
81
-
82
- function controlledText(value: string, label: string, maxLength: number): string {
83
- const text = value.trim();
84
- if (!text) throw new Error(`${label} is required.`);
85
- if (text.length > maxLength || /[\0\r\n]/u.test(text)) {
86
- throw new Error(`${label} is invalid.`);
87
- }
88
- return text;
89
- }
90
-
5
+ export type DesktopEventSocketOptions = Omit<CoreOptions, 'protocol'>;
91
6
  function mailboxEventType(event: Record<string, unknown> | string): string | undefined {
92
7
  if (typeof event === 'string') {
93
8
  const separator = event.indexOf(' | ');
@@ -98,349 +13,6 @@ function mailboxEventType(event: Record<string, unknown> | string): string | und
98
13
  return /^visual\.[a-z0-9_.-]+$/.test(type) ? type : undefined;
99
14
  }
100
15
 
101
- export function normalizeDesktopEventSocketPath(
102
- value: string,
103
- platform: NodeJS.Platform = process.platform,
104
- ): string {
105
- const path = controlledText(value, 'Desktop event socket', 512);
106
- if (platform === 'win32') {
107
- if (path.startsWith(WINDOWS_PIPE_PREFIX)) return path;
108
- if (path.startsWith('\\\\')) {
109
- throw new Error('Desktop event socket must be a local named pipe.');
110
- }
111
- if (/[\\/]/u.test(path)) {
112
- throw new Error('Desktop event socket must be a named-pipe name or local named-pipe path.');
113
- }
114
- return `${WINDOWS_PIPE_PREFIX}${path}`;
115
- }
116
- if (!path.startsWith('/')) {
117
- throw new Error('Desktop event socket must be an absolute Unix socket path.');
118
- }
119
- return path;
120
- }
121
-
122
- export function validateDesktopEventToken(value: string): string {
123
- const token = controlledText(value, 'Desktop event token', 1_024);
124
- if (token.length < 16) {
125
- throw new Error('Desktop event token must contain at least 16 characters.');
126
- }
127
- return token;
128
- }
129
-
130
- /** Persistent NDJSON client for a Desktop-owned local socket/named pipe. */
131
- export class DesktopEventSocketSink implements MailboxEventBatchSink {
132
- private readonly path: string;
133
- private readonly token: string;
134
- private readonly ackTimeoutMs: number;
135
- private readonly reconnectBaseMs: number;
136
- private readonly reconnectMaxMs: number;
137
- private readonly now: () => number;
138
- private readonly onConnected?: DesktopEventSocketOptions['onConnected'];
139
- private readonly activeResources?: DesktopEventSocketOptions['activeResources'];
140
- private readonly eventDescriptors?: DesktopEventSocketOptions['eventDescriptors'];
141
- private readonly diagnostic?: DesktopEventSocketOptions['diagnostic'];
142
-
143
- private socket: Socket | undefined;
144
- private connected = false;
145
- private stopped = false;
146
- private connectionId: string | undefined;
147
- private sequence = 0;
148
- private reconnectAttempt = 0;
149
- private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
150
- private inputBuffer = '';
151
- private pendingAck: PendingDesktopAck | undefined;
152
- private deliveryMetadata: DesktopDeliveryMetadata | undefined;
153
-
154
- constructor(options: DesktopEventSocketOptions) {
155
- this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
156
- this.token = validateDesktopEventToken(options.token);
157
- this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
158
- this.reconnectBaseMs = options.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
159
- this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
160
- this.now = options.now ?? Date.now;
161
- this.onConnected = options.onConnected;
162
- this.activeResources = options.activeResources;
163
- this.eventDescriptors = options.eventDescriptors;
164
- this.diagnostic = options.diagnostic;
165
- if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
166
- throw new Error('Desktop event ACK timeout must be positive.');
167
- }
168
- if (
169
- !Number.isFinite(this.reconnectBaseMs)
170
- || this.reconnectBaseMs <= 0
171
- || !Number.isFinite(this.reconnectMaxMs)
172
- || this.reconnectMaxMs < this.reconnectBaseMs
173
- ) {
174
- throw new Error('Desktop event reconnect delays are invalid.');
175
- }
176
- }
177
-
178
- start(): void {
179
- if (this.stopped || this.socket) return;
180
- this.connect();
181
- }
182
-
183
- async deliver(
184
- envelope: MailboxEventBatchEnvelope,
185
- signal: AbortSignal,
186
- ): Promise<MailboxEventBatchAcceptance> {
187
- if (this.stopped) {
188
- throw new DesktopEventSocketDeliveryError(
189
- 'desktop_event_socket_stopped',
190
- 'Desktop event socket is stopped.',
191
- false,
192
- );
193
- }
194
- if (signal.aborted) throw this.abortError(signal);
195
- const socket = this.socket;
196
- const connectionId = this.connectionId;
197
- if (!socket || !this.connected || !connectionId) {
198
- this.start();
199
- throw new DesktopEventSocketDeliveryError(
200
- 'desktop_event_socket_not_connected',
201
- 'Desktop event socket is not connected.',
202
- );
203
- }
204
- if (this.pendingAck) {
205
- throw new DesktopEventSocketDeliveryError(
206
- 'desktop_event_batch_in_flight',
207
- 'A Desktop event batch is already awaiting acknowledgement.',
208
- );
209
- }
210
-
211
- const seq = ++this.sequence;
212
- const metadata = this.metadataForDelivery(envelope.deliveryId, envelope.batch.events);
213
- const frame = {
214
- schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
215
- type: 'mailbox_batch',
216
- connection_id: connectionId,
217
- seq,
218
- delivery_id: envelope.deliveryId,
219
- ...(metadata.activeResources ? { active_resources: metadata.activeResources } : {}),
220
- ...(metadata.eventDescriptors.length > 0
221
- ? { event_descriptors: metadata.eventDescriptors }
222
- : {}),
223
- payload: {
224
- schema: 'clawclaw.channel-events.v1',
225
- ...envelope.batch,
226
- },
227
- };
228
-
229
- return new Promise<MailboxEventBatchAcceptance>((resolve, reject) => {
230
- const onAbort = (): void => {
231
- if (this.pendingAck?.seq !== seq) return;
232
- this.rejectPending(this.abortError(signal));
233
- socket.destroy();
234
- };
235
- const timer = setTimeout(() => {
236
- if (this.pendingAck?.seq !== seq) return;
237
- this.rejectPending(new DesktopEventSocketDeliveryError(
238
- 'desktop_event_ack_timeout',
239
- 'Desktop did not acknowledge the event batch in time.',
240
- ));
241
- socket.destroy();
242
- }, this.ackTimeoutMs);
243
- timer.unref?.();
244
- this.pendingAck = {
245
- connectionId,
246
- seq,
247
- deliveryId: envelope.deliveryId,
248
- timer,
249
- signal,
250
- onAbort,
251
- resolve,
252
- reject,
253
- };
254
- signal.addEventListener('abort', onAbort, { once: true });
255
-
256
- const line = `${JSON.stringify(frame)}\n`;
257
- socket.write(line, (error?: Error | null) => {
258
- if (!error || this.pendingAck?.seq !== seq) return;
259
- this.rejectPending(new DesktopEventSocketDeliveryError(
260
- 'desktop_event_socket_write_failed',
261
- error.message,
262
- ));
263
- socket.destroy();
264
- });
265
- });
266
- }
267
-
268
- async close(): Promise<void> {
269
- if (this.stopped) return;
270
- this.stopped = true;
271
- if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
272
- this.reconnectTimer = undefined;
273
- this.rejectPending(new DesktopEventSocketDeliveryError(
274
- 'desktop_event_socket_stopped',
275
- 'Desktop event socket stopped before acknowledgement.',
276
- false,
277
- ));
278
- const socket = this.socket;
279
- this.socket = undefined;
280
- this.connected = false;
281
- this.connectionId = undefined;
282
- this.deliveryMetadata = undefined;
283
- if (!socket || socket.destroyed) return;
284
- await new Promise<void>((resolve) => {
285
- socket.once('close', () => resolve());
286
- socket.destroy();
287
- });
288
- }
289
-
290
- private connect(): void {
291
- if (this.stopped || this.socket) return;
292
- const connectionId = randomUUID();
293
- const socket = createConnection(this.path);
294
- this.socket = socket;
295
- this.connectionId = connectionId;
296
- this.inputBuffer = '';
297
- socket.setEncoding('utf8');
298
- socket.setNoDelay(true);
299
-
300
- socket.once('connect', () => {
301
- if (this.socket !== socket || this.stopped) return;
302
- this.connected = true;
303
- this.reconnectAttempt = 0;
304
- const activeResources = this.readActiveResources();
305
- socket.write(`${JSON.stringify({
306
- schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
307
- type: 'hello',
308
- connection_id: connectionId,
309
- token: this.token,
310
- pid: process.pid,
311
- ...(activeResources ? { active_resources: activeResources } : {}),
312
- })}\n`);
313
- this.diagnostic?.('runtime.desktop_event_socket.connected', {
314
- connection_id: connectionId,
315
- });
316
- this.onConnected?.();
317
- });
318
- socket.on('data', (chunk: string) => this.onData(socket, chunk));
319
- socket.once('error', (error) => {
320
- this.diagnostic?.('runtime.desktop_event_socket.error', {
321
- code: typeof (error as NodeJS.ErrnoException).code === 'string'
322
- ? (error as NodeJS.ErrnoException).code
323
- : error.name,
324
- });
325
- });
326
- socket.once('close', () => this.onClose(socket));
327
- }
328
-
329
- private onData(socket: Socket, chunk: string): void {
330
- if (this.socket !== socket || this.stopped) return;
331
- this.inputBuffer += chunk;
332
- if (this.inputBuffer.length > MAX_ACK_BUFFER_CHARACTERS) {
333
- socket.destroy(new Error('desktop_event_ack_frame_too_large'));
334
- return;
335
- }
336
- for (;;) {
337
- const newline = this.inputBuffer.indexOf('\n');
338
- if (newline < 0) return;
339
- const line = this.inputBuffer.slice(0, newline).trim();
340
- this.inputBuffer = this.inputBuffer.slice(newline + 1);
341
- if (!line) continue;
342
- let frame: Record<string, unknown>;
343
- try {
344
- const parsed = JSON.parse(line);
345
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error();
346
- frame = parsed as Record<string, unknown>;
347
- } catch {
348
- socket.destroy(new Error('desktop_event_ack_invalid_json'));
349
- return;
350
- }
351
- this.handleFrame(frame);
352
- }
353
- }
354
-
355
- private handleFrame(frame: Record<string, unknown>): void {
356
- const pending = this.pendingAck;
357
- if (
358
- !pending
359
- || frame.schema !== DESKTOP_EVENT_PROTOCOL_SCHEMA
360
- || frame.type !== 'ack'
361
- || frame.connection_id !== pending.connectionId
362
- || frame.seq !== pending.seq
363
- || frame.delivery_id !== pending.deliveryId
364
- ) {
365
- this.diagnostic?.('runtime.desktop_event_socket.ack_ignored');
366
- return;
367
- }
368
- const receiptId = typeof frame.receipt_id === 'string' && frame.receipt_id.length <= 256
369
- ? frame.receipt_id
370
- : undefined;
371
- this.pendingAck = undefined;
372
- clearTimeout(pending.timer);
373
- pending.signal.removeEventListener('abort', pending.onAbort);
374
- if (this.deliveryMetadata?.deliveryId === pending.deliveryId) {
375
- this.deliveryMetadata = undefined;
376
- }
377
- pending.resolve({
378
- acceptedAt: new Date(this.now()).toISOString(),
379
- ...(receiptId ? { receiptId } : {}),
380
- });
381
- }
382
-
383
- private onClose(socket: Socket): void {
384
- if (this.socket !== socket) return;
385
- this.socket = undefined;
386
- this.connected = false;
387
- this.connectionId = undefined;
388
- this.inputBuffer = '';
389
- this.rejectPending(new DesktopEventSocketDeliveryError(
390
- 'desktop_event_socket_disconnected',
391
- 'Desktop event socket disconnected before acknowledgement.',
392
- ));
393
- if (this.stopped) return;
394
- this.reconnectAttempt += 1;
395
- const delayMs = Math.min(
396
- this.reconnectMaxMs,
397
- this.reconnectBaseMs * (2 ** Math.min(8, this.reconnectAttempt - 1)),
398
- );
399
- this.diagnostic?.('runtime.desktop_event_socket.reconnecting', {
400
- retry_in_ms: delayMs,
401
- });
402
- const timer = setTimeout(() => {
403
- this.reconnectTimer = undefined;
404
- this.connect();
405
- }, delayMs);
406
- timer.unref?.();
407
- this.reconnectTimer = timer;
408
- }
409
-
410
- private rejectPending(error: Error): void {
411
- const pending = this.pendingAck;
412
- if (!pending) return;
413
- this.pendingAck = undefined;
414
- clearTimeout(pending.timer);
415
- pending.signal.removeEventListener('abort', pending.onAbort);
416
- pending.reject(error);
417
- }
418
-
419
- private abortError(signal: AbortSignal): DesktopEventSocketDeliveryError {
420
- return new DesktopEventSocketDeliveryError(
421
- 'desktop_event_delivery_aborted',
422
- signal.reason instanceof Error ? signal.reason.message : 'Desktop event delivery aborted.',
423
- );
424
- }
425
-
426
- private readActiveResources(): DesktopActiveResources | undefined {
427
- if (!this.activeResources) return undefined;
428
- return structuredClone(this.activeResources());
429
- }
430
-
431
- private metadataForDelivery(
432
- deliveryId: string,
433
- events: readonly (Record<string, unknown> | string)[],
434
- ): Omit<DesktopDeliveryMetadata, 'deliveryId'> {
435
- if (this.deliveryMetadata?.deliveryId === deliveryId) return this.deliveryMetadata;
436
- const activeEventTypes = new Set(events.map(mailboxEventType).filter((type) => type !== undefined));
437
- const eventDescriptors = structuredClone(this.eventDescriptors?.() ?? [])
438
- .filter((descriptor) => activeEventTypes.has(descriptor.type));
439
- this.deliveryMetadata = {
440
- deliveryId,
441
- activeResources: this.readActiveResources(),
442
- eventDescriptors,
443
- };
444
- return this.deliveryMetadata;
445
- }
16
+ export class DesktopEventSocketSink extends CoreDesktopSink {
17
+ constructor(options: DesktopEventSocketOptions) { super({...options,protocol:{schema:DESKTOP_EVENT_PROTOCOL_SCHEMA,payloadSchema:'clawclaw.channel-events.v1',eventType:mailboxEventType}}); }
446
18
  }