@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0

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 (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +242 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +56 -0
  127. package/dist/mailbox/mailbox-plugin.js +111 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +336 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,279 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createConnection } from 'node:net';
3
+ const DEFAULT_RECEIPT_TIMEOUT_MS = 10_000;
4
+ const DEFAULT_RECONNECT_BASE_MS = 100;
5
+ const DEFAULT_RECONNECT_MAX_MS = 5_000;
6
+ export class ClaudeChannelSocketDeliveryError extends Error {
7
+ code;
8
+ retryable;
9
+ constructor(code, message, retryable = true) {
10
+ super(message);
11
+ this.name = 'ClaudeChannelSocketDeliveryError';
12
+ this.code = code;
13
+ this.retryable = retryable;
14
+ }
15
+ }
16
+ /** Owner-side IPC client. Mailbox batches flow outward to the Channel MCP process. */
17
+ export class ClaudeChannelSocketSink {
18
+ protocol;
19
+ receiptTimeoutMs;
20
+ reconnectBaseMs;
21
+ reconnectMaxMs;
22
+ now;
23
+ endpoint;
24
+ onConnected;
25
+ diagnostic;
26
+ socket;
27
+ ready = false;
28
+ stopped = false;
29
+ connectionId;
30
+ sequence = 0;
31
+ reconnectAttempt = 0;
32
+ reconnectTimer;
33
+ inputBuffer = '';
34
+ pendingReceipt;
35
+ constructor(options) {
36
+ this.protocol = options.protocol;
37
+ this.receiptTimeoutMs = options.receiptTimeoutMs ?? DEFAULT_RECEIPT_TIMEOUT_MS;
38
+ this.reconnectBaseMs = options.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
39
+ this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
40
+ this.now = options.now ?? Date.now;
41
+ this.endpoint = options.endpoint;
42
+ this.onConnected = options.onConnected;
43
+ this.diagnostic = options.diagnostic;
44
+ if (!Number.isFinite(this.receiptTimeoutMs) || this.receiptTimeoutMs <= 0) {
45
+ throw new Error('Claude Channel IPC receipt timeout must be positive.');
46
+ }
47
+ if (!Number.isFinite(this.reconnectBaseMs)
48
+ || this.reconnectBaseMs <= 0
49
+ || !Number.isFinite(this.reconnectMaxMs)
50
+ || this.reconnectMaxMs < this.reconnectBaseMs) {
51
+ throw new Error('Claude Channel IPC reconnect delays are invalid.');
52
+ }
53
+ }
54
+ start() {
55
+ if (this.stopped || this.socket || this.reconnectTimer)
56
+ return;
57
+ this.connect();
58
+ }
59
+ async deliver(envelope, signal) {
60
+ if (this.stopped) {
61
+ throw new ClaudeChannelSocketDeliveryError('claude_channel_socket_stopped', 'Claude Channel IPC is stopped.', false);
62
+ }
63
+ if (signal.aborted)
64
+ throw this.abortError(signal);
65
+ const socket = this.socket;
66
+ const connectionId = this.connectionId;
67
+ if (!socket || !this.ready || !connectionId) {
68
+ this.start();
69
+ throw new ClaudeChannelSocketDeliveryError('claude_channel_socket_not_connected', 'Claude Channel IPC is not connected.');
70
+ }
71
+ if (this.pendingReceipt) {
72
+ throw new ClaudeChannelSocketDeliveryError('claude_channel_batch_in_flight', 'A Claude Channel batch is already awaiting its transport receipt.');
73
+ }
74
+ const seq = ++this.sequence;
75
+ const frame = {
76
+ schema: this.protocol.schema,
77
+ type: 'mailbox_batch',
78
+ connection_id: connectionId,
79
+ seq,
80
+ delivery_id: envelope.deliveryId,
81
+ payload: {
82
+ schema: this.protocol.payloadSchema,
83
+ events: envelope.batch.events,
84
+ },
85
+ };
86
+ return new Promise((resolve, reject) => {
87
+ const onAbort = () => {
88
+ if (this.pendingReceipt?.seq !== seq)
89
+ return;
90
+ this.rejectPending(this.abortError(signal));
91
+ socket.destroy();
92
+ };
93
+ const timer = setTimeout(() => {
94
+ if (this.pendingReceipt?.seq !== seq)
95
+ return;
96
+ this.rejectPending(new ClaudeChannelSocketDeliveryError('claude_channel_receipt_timeout', 'Channel MCP did not return the transport receipt in time.'));
97
+ socket.destroy();
98
+ }, this.receiptTimeoutMs);
99
+ timer.unref?.();
100
+ this.pendingReceipt = {
101
+ connectionId,
102
+ seq,
103
+ deliveryId: envelope.deliveryId,
104
+ timer,
105
+ signal,
106
+ onAbort,
107
+ resolve,
108
+ reject,
109
+ };
110
+ signal.addEventListener('abort', onAbort, { once: true });
111
+ socket.write(`${JSON.stringify(frame)}\n`, (error) => {
112
+ if (!error || this.pendingReceipt?.seq !== seq)
113
+ return;
114
+ this.rejectPending(new ClaudeChannelSocketDeliveryError('claude_channel_socket_write_failed', error.message));
115
+ socket.destroy();
116
+ });
117
+ });
118
+ }
119
+ async close() {
120
+ if (this.stopped)
121
+ return;
122
+ this.stopped = true;
123
+ if (this.reconnectTimer)
124
+ clearTimeout(this.reconnectTimer);
125
+ this.reconnectTimer = undefined;
126
+ this.rejectPending(new ClaudeChannelSocketDeliveryError('claude_channel_socket_stopped', 'Claude Channel IPC stopped before transport acceptance.', false));
127
+ const socket = this.socket;
128
+ this.socket = undefined;
129
+ this.ready = false;
130
+ this.connectionId = undefined;
131
+ if (!socket || socket.destroyed)
132
+ return;
133
+ await new Promise((resolve) => {
134
+ socket.once('close', () => resolve());
135
+ socket.destroy();
136
+ });
137
+ }
138
+ connect() {
139
+ if (this.stopped || this.socket)
140
+ return;
141
+ const endpoint = this.endpoint();
142
+ if (!endpoint) {
143
+ this.scheduleReconnect('endpoint_unavailable');
144
+ return;
145
+ }
146
+ const connectionId = randomUUID();
147
+ const socket = createConnection(endpoint.socket_path);
148
+ this.socket = socket;
149
+ this.connectionId = connectionId;
150
+ this.ready = false;
151
+ this.inputBuffer = '';
152
+ socket.setEncoding('utf8');
153
+ socket.setNoDelay(true);
154
+ socket.once('connect', () => {
155
+ if (this.socket !== socket || this.stopped)
156
+ return;
157
+ socket.write(`${JSON.stringify({
158
+ schema: this.protocol.schema,
159
+ type: 'hello',
160
+ connection_id: connectionId,
161
+ token: endpoint.token,
162
+ owner_pid: process.pid,
163
+ })}\n`);
164
+ });
165
+ socket.on('data', (chunk) => this.onData(socket, chunk));
166
+ socket.once('error', (error) => {
167
+ this.diagnostic?.('runtime.channel.ipc_error', {
168
+ code: typeof error.code === 'string'
169
+ ? error.code
170
+ : error.name,
171
+ });
172
+ });
173
+ socket.once('close', () => this.onClose(socket));
174
+ }
175
+ onData(socket, chunk) {
176
+ if (this.socket !== socket || this.stopped)
177
+ return;
178
+ this.inputBuffer += chunk;
179
+ if (this.inputBuffer.length > this.protocol.maxFrameCharacters) {
180
+ socket.destroy(new Error('claude_channel_ipc_receipt_frame_too_large'));
181
+ return;
182
+ }
183
+ for (;;) {
184
+ const newline = this.inputBuffer.indexOf('\n');
185
+ if (newline < 0)
186
+ return;
187
+ const line = this.inputBuffer.slice(0, newline).trim();
188
+ this.inputBuffer = this.inputBuffer.slice(newline + 1);
189
+ if (!line)
190
+ continue;
191
+ let frame;
192
+ try {
193
+ const parsed = JSON.parse(line);
194
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
195
+ throw new Error();
196
+ frame = parsed;
197
+ }
198
+ catch {
199
+ socket.destroy(new Error('claude_channel_ipc_receipt_invalid_json'));
200
+ return;
201
+ }
202
+ this.handleFrame(frame);
203
+ }
204
+ }
205
+ handleFrame(frame) {
206
+ if (!this.ready
207
+ && frame.schema === this.protocol.schema
208
+ && frame.type === 'ready'
209
+ && frame.connection_id === this.connectionId) {
210
+ this.ready = true;
211
+ this.reconnectAttempt = 0;
212
+ this.diagnostic?.('runtime.channel.ipc_connected');
213
+ this.onConnected?.();
214
+ return;
215
+ }
216
+ const pending = this.pendingReceipt;
217
+ if (!pending
218
+ || frame.schema !== this.protocol.schema
219
+ || frame.type !== 'receipt'
220
+ || frame.connection_id !== pending.connectionId
221
+ || frame.seq !== pending.seq
222
+ || frame.delivery_id !== pending.deliveryId) {
223
+ this.diagnostic?.('runtime.channel.ipc_receipt_ignored');
224
+ return;
225
+ }
226
+ const acceptedAt = typeof frame.accepted_at === 'string'
227
+ ? frame.accepted_at
228
+ : new Date(this.now()).toISOString();
229
+ const receiptId = typeof frame.receipt_id === 'string' && frame.receipt_id.length <= 256
230
+ ? frame.receipt_id
231
+ : undefined;
232
+ this.pendingReceipt = undefined;
233
+ clearTimeout(pending.timer);
234
+ pending.signal.removeEventListener('abort', pending.onAbort);
235
+ pending.resolve({ acceptedAt, ...(receiptId ? { receiptId } : {}),
236
+ acceptanceLevel: frame.acceptance_level === 'host_accepted' ? 'host_accepted' : 'sink_emitted' });
237
+ }
238
+ onClose(socket) {
239
+ if (this.socket !== socket)
240
+ return;
241
+ this.socket = undefined;
242
+ this.ready = false;
243
+ this.connectionId = undefined;
244
+ this.inputBuffer = '';
245
+ this.rejectPending(new ClaudeChannelSocketDeliveryError('claude_channel_socket_disconnected', 'Claude Channel IPC disconnected before transport acceptance.'));
246
+ if (!this.stopped)
247
+ this.scheduleReconnect('disconnected');
248
+ }
249
+ scheduleReconnect(reason) {
250
+ if (this.stopped || this.reconnectTimer)
251
+ return;
252
+ this.reconnectAttempt += 1;
253
+ const delayMs = Math.min(this.reconnectMaxMs, this.reconnectBaseMs * (2 ** Math.min(8, this.reconnectAttempt - 1)));
254
+ this.diagnostic?.('runtime.channel.ipc_reconnecting', {
255
+ reason,
256
+ retry_in_ms: delayMs,
257
+ });
258
+ const timer = setTimeout(() => {
259
+ this.reconnectTimer = undefined;
260
+ this.connect();
261
+ }, delayMs);
262
+ timer.unref?.();
263
+ this.reconnectTimer = timer;
264
+ }
265
+ rejectPending(error) {
266
+ const pending = this.pendingReceipt;
267
+ if (!pending)
268
+ return;
269
+ this.pendingReceipt = undefined;
270
+ clearTimeout(pending.timer);
271
+ pending.signal.removeEventListener('abort', pending.onAbort);
272
+ pending.reject(error);
273
+ }
274
+ abortError(signal) {
275
+ return new ClaudeChannelSocketDeliveryError('claude_channel_delivery_aborted', signal.reason instanceof Error
276
+ ? signal.reason.message
277
+ : 'Claude Channel delivery aborted.');
278
+ }
279
+ }
@@ -0,0 +1,81 @@
1
+ import type { MailboxEventBatchAcceptance, MailboxEventBatchEnvelope, MailboxEventBatchSink } from '../mailbox-event-batch-delivery.js';
2
+ export interface DesktopEventProtocol {
3
+ readonly schema: string;
4
+ readonly payloadSchema: string;
5
+ readonly eventType?: (event: Record<string, unknown> | string) => string | undefined;
6
+ }
7
+ export interface DesktopEventSocketConfig {
8
+ socketPath: string;
9
+ token: string;
10
+ }
11
+ export interface DesktopActiveResource {
12
+ readonly id: string;
13
+ readonly name: string;
14
+ readonly description: string;
15
+ }
16
+ export interface DesktopActiveResources {
17
+ readonly locale: string;
18
+ readonly strategy: DesktopActiveResource | null;
19
+ readonly perceptions: readonly DesktopActiveResource[];
20
+ }
21
+ export interface DesktopEventDescriptor {
22
+ readonly type: string;
23
+ readonly perception_id: string;
24
+ readonly name: string;
25
+ readonly description: string;
26
+ }
27
+ export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
28
+ readonly protocol: DesktopEventProtocol;
29
+ ackTimeoutMs?: number;
30
+ reconnectBaseMs?: number;
31
+ reconnectMaxMs?: number;
32
+ now?: () => number;
33
+ platform?: NodeJS.Platform;
34
+ onConnected?: () => void;
35
+ activeResources?: () => DesktopActiveResources;
36
+ eventDescriptors?: () => readonly DesktopEventDescriptor[];
37
+ diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
38
+ }
39
+ export declare class DesktopEventSocketDeliveryError extends Error {
40
+ readonly code: string;
41
+ readonly retryable: boolean;
42
+ constructor(code: string, message: string, retryable?: boolean);
43
+ }
44
+ export declare function normalizeDesktopEventSocketPath(value: string, platform?: NodeJS.Platform): string;
45
+ export declare function validateDesktopEventToken(value: string): string;
46
+ /** Persistent NDJSON client for a Desktop-owned local socket/named pipe. */
47
+ export declare class DesktopEventSocketSink implements MailboxEventBatchSink {
48
+ private readonly protocol;
49
+ private readonly path;
50
+ private readonly token;
51
+ private readonly ackTimeoutMs;
52
+ private readonly reconnectBaseMs;
53
+ private readonly reconnectMaxMs;
54
+ private readonly now;
55
+ private readonly onConnected?;
56
+ private readonly activeResources?;
57
+ private readonly eventDescriptors?;
58
+ private readonly diagnostic?;
59
+ private socket;
60
+ private connected;
61
+ private stopped;
62
+ private connectionId;
63
+ private sequence;
64
+ private reconnectAttempt;
65
+ private reconnectTimer;
66
+ private inputBuffer;
67
+ private pendingAck;
68
+ private deliveryMetadata;
69
+ constructor(options: DesktopEventSocketOptions);
70
+ start(): void;
71
+ deliver(envelope: MailboxEventBatchEnvelope, signal: AbortSignal): Promise<MailboxEventBatchAcceptance>;
72
+ close(): Promise<void>;
73
+ private connect;
74
+ private onData;
75
+ private handleFrame;
76
+ private onClose;
77
+ private rejectPending;
78
+ private abortError;
79
+ private readActiveResources;
80
+ private metadataForDelivery;
81
+ }
@@ -0,0 +1,339 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createConnection } from 'node:net';
3
+ const WINDOWS_PIPE_PREFIX = '\\\\.\\pipe\\';
4
+ const MAX_ACK_BUFFER_CHARACTERS = 64 * 1024;
5
+ const DEFAULT_ACK_TIMEOUT_MS = 10_000;
6
+ const DEFAULT_RECONNECT_BASE_MS = 100;
7
+ const DEFAULT_RECONNECT_MAX_MS = 5_000;
8
+ export class DesktopEventSocketDeliveryError extends Error {
9
+ code;
10
+ retryable;
11
+ constructor(code, message, retryable = true) {
12
+ super(message);
13
+ this.name = 'DesktopEventSocketDeliveryError';
14
+ this.code = code;
15
+ this.retryable = retryable;
16
+ }
17
+ }
18
+ function controlledText(value, label, maxLength) {
19
+ const text = value.trim();
20
+ if (!text)
21
+ throw new Error(`${label} is required.`);
22
+ if (text.length > maxLength || /[\0\r\n]/u.test(text)) {
23
+ throw new Error(`${label} is invalid.`);
24
+ }
25
+ return text;
26
+ }
27
+ function mailboxEventType(event) {
28
+ return typeof event === 'string' ? event.split(' | ', 1)[0].trim() || undefined
29
+ : typeof event.type === 'string' ? event.type : undefined;
30
+ }
31
+ export function normalizeDesktopEventSocketPath(value, platform = process.platform) {
32
+ const path = controlledText(value, 'Desktop event socket', 512);
33
+ if (platform === 'win32') {
34
+ if (path.startsWith(WINDOWS_PIPE_PREFIX))
35
+ return path;
36
+ if (path.startsWith('\\\\')) {
37
+ throw new Error('Desktop event socket must be a local named pipe.');
38
+ }
39
+ if (/[\\/]/u.test(path)) {
40
+ throw new Error('Desktop event socket must be a named-pipe name or local named-pipe path.');
41
+ }
42
+ return `${WINDOWS_PIPE_PREFIX}${path}`;
43
+ }
44
+ if (!path.startsWith('/')) {
45
+ throw new Error('Desktop event socket must be an absolute Unix socket path.');
46
+ }
47
+ return path;
48
+ }
49
+ export function validateDesktopEventToken(value) {
50
+ const token = controlledText(value, 'Desktop event token', 1_024);
51
+ if (token.length < 16) {
52
+ throw new Error('Desktop event token must contain at least 16 characters.');
53
+ }
54
+ return token;
55
+ }
56
+ /** Persistent NDJSON client for a Desktop-owned local socket/named pipe. */
57
+ export class DesktopEventSocketSink {
58
+ protocol;
59
+ path;
60
+ token;
61
+ ackTimeoutMs;
62
+ reconnectBaseMs;
63
+ reconnectMaxMs;
64
+ now;
65
+ onConnected;
66
+ activeResources;
67
+ eventDescriptors;
68
+ diagnostic;
69
+ socket;
70
+ connected = false;
71
+ stopped = false;
72
+ connectionId;
73
+ sequence = 0;
74
+ reconnectAttempt = 0;
75
+ reconnectTimer;
76
+ inputBuffer = '';
77
+ pendingAck;
78
+ deliveryMetadata;
79
+ constructor(options) {
80
+ this.protocol = options.protocol;
81
+ this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
82
+ this.token = validateDesktopEventToken(options.token);
83
+ this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
84
+ this.reconnectBaseMs = options.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
85
+ this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
86
+ this.now = options.now ?? Date.now;
87
+ this.onConnected = options.onConnected;
88
+ this.activeResources = options.activeResources;
89
+ this.eventDescriptors = options.eventDescriptors;
90
+ this.diagnostic = options.diagnostic;
91
+ if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
92
+ throw new Error('Desktop event ACK timeout must be positive.');
93
+ }
94
+ if (!Number.isFinite(this.reconnectBaseMs)
95
+ || this.reconnectBaseMs <= 0
96
+ || !Number.isFinite(this.reconnectMaxMs)
97
+ || this.reconnectMaxMs < this.reconnectBaseMs) {
98
+ throw new Error('Desktop event reconnect delays are invalid.');
99
+ }
100
+ }
101
+ start() {
102
+ if (this.stopped || this.socket)
103
+ return;
104
+ this.connect();
105
+ }
106
+ async deliver(envelope, signal) {
107
+ if (this.stopped) {
108
+ throw new DesktopEventSocketDeliveryError('desktop_event_socket_stopped', 'Desktop event socket is stopped.', false);
109
+ }
110
+ if (signal.aborted)
111
+ throw this.abortError(signal);
112
+ const socket = this.socket;
113
+ const connectionId = this.connectionId;
114
+ if (!socket || !this.connected || !connectionId) {
115
+ this.start();
116
+ throw new DesktopEventSocketDeliveryError('desktop_event_socket_not_connected', 'Desktop event socket is not connected.');
117
+ }
118
+ if (this.pendingAck) {
119
+ throw new DesktopEventSocketDeliveryError('desktop_event_batch_in_flight', 'A Desktop event batch is already awaiting acknowledgement.');
120
+ }
121
+ const seq = ++this.sequence;
122
+ const metadata = this.metadataForDelivery(envelope.deliveryId, envelope.batch.events);
123
+ const frame = {
124
+ schema: this.protocol.schema,
125
+ type: 'mailbox_batch',
126
+ connection_id: connectionId,
127
+ seq,
128
+ delivery_id: envelope.deliveryId,
129
+ ...(metadata.activeResources ? { active_resources: metadata.activeResources } : {}),
130
+ ...(metadata.eventDescriptors.length > 0
131
+ ? { event_descriptors: metadata.eventDescriptors }
132
+ : {}),
133
+ payload: {
134
+ schema: this.protocol.payloadSchema,
135
+ ...envelope.batch,
136
+ },
137
+ };
138
+ return new Promise((resolve, reject) => {
139
+ const onAbort = () => {
140
+ if (this.pendingAck?.seq !== seq)
141
+ return;
142
+ this.rejectPending(this.abortError(signal));
143
+ socket.destroy();
144
+ };
145
+ const timer = setTimeout(() => {
146
+ if (this.pendingAck?.seq !== seq)
147
+ return;
148
+ this.rejectPending(new DesktopEventSocketDeliveryError('desktop_event_ack_timeout', 'Desktop did not acknowledge the event batch in time.'));
149
+ socket.destroy();
150
+ }, this.ackTimeoutMs);
151
+ timer.unref?.();
152
+ this.pendingAck = {
153
+ connectionId,
154
+ seq,
155
+ deliveryId: envelope.deliveryId,
156
+ timer,
157
+ signal,
158
+ onAbort,
159
+ resolve,
160
+ reject,
161
+ };
162
+ signal.addEventListener('abort', onAbort, { once: true });
163
+ const line = `${JSON.stringify(frame)}\n`;
164
+ socket.write(line, (error) => {
165
+ if (!error || this.pendingAck?.seq !== seq)
166
+ return;
167
+ this.rejectPending(new DesktopEventSocketDeliveryError('desktop_event_socket_write_failed', error.message));
168
+ socket.destroy();
169
+ });
170
+ });
171
+ }
172
+ async close() {
173
+ if (this.stopped)
174
+ return;
175
+ this.stopped = true;
176
+ if (this.reconnectTimer)
177
+ clearTimeout(this.reconnectTimer);
178
+ this.reconnectTimer = undefined;
179
+ this.rejectPending(new DesktopEventSocketDeliveryError('desktop_event_socket_stopped', 'Desktop event socket stopped before acknowledgement.', false));
180
+ const socket = this.socket;
181
+ this.socket = undefined;
182
+ this.connected = false;
183
+ this.connectionId = undefined;
184
+ this.deliveryMetadata = undefined;
185
+ if (!socket || socket.destroyed)
186
+ return;
187
+ await new Promise((resolve) => {
188
+ socket.once('close', () => resolve());
189
+ socket.destroy();
190
+ });
191
+ }
192
+ connect() {
193
+ if (this.stopped || this.socket)
194
+ return;
195
+ const connectionId = randomUUID();
196
+ const socket = createConnection(this.path);
197
+ this.socket = socket;
198
+ this.connectionId = connectionId;
199
+ this.inputBuffer = '';
200
+ socket.setEncoding('utf8');
201
+ socket.setNoDelay(true);
202
+ socket.once('connect', () => {
203
+ if (this.socket !== socket || this.stopped)
204
+ return;
205
+ this.connected = true;
206
+ this.reconnectAttempt = 0;
207
+ const activeResources = this.readActiveResources();
208
+ socket.write(`${JSON.stringify({
209
+ schema: this.protocol.schema,
210
+ type: 'hello',
211
+ connection_id: connectionId,
212
+ token: this.token,
213
+ pid: process.pid,
214
+ ...(activeResources ? { active_resources: activeResources } : {}),
215
+ })}\n`);
216
+ this.diagnostic?.('runtime.desktop_event_socket.connected', {
217
+ connection_id: connectionId,
218
+ });
219
+ this.onConnected?.();
220
+ });
221
+ socket.on('data', (chunk) => this.onData(socket, chunk));
222
+ socket.once('error', (error) => {
223
+ this.diagnostic?.('runtime.desktop_event_socket.error', {
224
+ code: typeof error.code === 'string'
225
+ ? error.code
226
+ : error.name,
227
+ });
228
+ });
229
+ socket.once('close', () => this.onClose(socket));
230
+ }
231
+ onData(socket, chunk) {
232
+ if (this.socket !== socket || this.stopped)
233
+ return;
234
+ this.inputBuffer += chunk;
235
+ if (this.inputBuffer.length > MAX_ACK_BUFFER_CHARACTERS) {
236
+ socket.destroy(new Error('desktop_event_ack_frame_too_large'));
237
+ return;
238
+ }
239
+ for (;;) {
240
+ const newline = this.inputBuffer.indexOf('\n');
241
+ if (newline < 0)
242
+ return;
243
+ const line = this.inputBuffer.slice(0, newline).trim();
244
+ this.inputBuffer = this.inputBuffer.slice(newline + 1);
245
+ if (!line)
246
+ continue;
247
+ let frame;
248
+ try {
249
+ const parsed = JSON.parse(line);
250
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
251
+ throw new Error();
252
+ frame = parsed;
253
+ }
254
+ catch {
255
+ socket.destroy(new Error('desktop_event_ack_invalid_json'));
256
+ return;
257
+ }
258
+ this.handleFrame(frame);
259
+ }
260
+ }
261
+ handleFrame(frame) {
262
+ const pending = this.pendingAck;
263
+ if (!pending
264
+ || frame.schema !== this.protocol.schema
265
+ || frame.type !== 'ack'
266
+ || frame.connection_id !== pending.connectionId
267
+ || frame.seq !== pending.seq
268
+ || frame.delivery_id !== pending.deliveryId) {
269
+ this.diagnostic?.('runtime.desktop_event_socket.ack_ignored');
270
+ return;
271
+ }
272
+ const receiptId = typeof frame.receipt_id === 'string' && frame.receipt_id.length <= 256
273
+ ? frame.receipt_id
274
+ : undefined;
275
+ this.pendingAck = undefined;
276
+ clearTimeout(pending.timer);
277
+ pending.signal.removeEventListener('abort', pending.onAbort);
278
+ if (this.deliveryMetadata?.deliveryId === pending.deliveryId) {
279
+ this.deliveryMetadata = undefined;
280
+ }
281
+ pending.resolve({
282
+ acceptedAt: new Date(this.now()).toISOString(),
283
+ acceptanceLevel: frame.acceptance_level === 'host_accepted' ? 'host_accepted' : 'sink_emitted',
284
+ ...(receiptId ? { receiptId } : {}),
285
+ });
286
+ }
287
+ onClose(socket) {
288
+ if (this.socket !== socket)
289
+ return;
290
+ this.socket = undefined;
291
+ this.connected = false;
292
+ this.connectionId = undefined;
293
+ this.inputBuffer = '';
294
+ this.rejectPending(new DesktopEventSocketDeliveryError('desktop_event_socket_disconnected', 'Desktop event socket disconnected before acknowledgement.'));
295
+ if (this.stopped)
296
+ return;
297
+ this.reconnectAttempt += 1;
298
+ const delayMs = Math.min(this.reconnectMaxMs, this.reconnectBaseMs * (2 ** Math.min(8, this.reconnectAttempt - 1)));
299
+ this.diagnostic?.('runtime.desktop_event_socket.reconnecting', {
300
+ retry_in_ms: delayMs,
301
+ });
302
+ const timer = setTimeout(() => {
303
+ this.reconnectTimer = undefined;
304
+ this.connect();
305
+ }, delayMs);
306
+ timer.unref?.();
307
+ this.reconnectTimer = timer;
308
+ }
309
+ rejectPending(error) {
310
+ const pending = this.pendingAck;
311
+ if (!pending)
312
+ return;
313
+ this.pendingAck = undefined;
314
+ clearTimeout(pending.timer);
315
+ pending.signal.removeEventListener('abort', pending.onAbort);
316
+ pending.reject(error);
317
+ }
318
+ abortError(signal) {
319
+ return new DesktopEventSocketDeliveryError('desktop_event_delivery_aborted', signal.reason instanceof Error ? signal.reason.message : 'Desktop event delivery aborted.');
320
+ }
321
+ readActiveResources() {
322
+ if (!this.activeResources)
323
+ return undefined;
324
+ return structuredClone(this.activeResources());
325
+ }
326
+ metadataForDelivery(deliveryId, events) {
327
+ if (this.deliveryMetadata?.deliveryId === deliveryId)
328
+ return this.deliveryMetadata;
329
+ const activeEventTypes = new Set(events.map(this.protocol.eventType ?? mailboxEventType).filter((type) => type !== undefined));
330
+ const eventDescriptors = structuredClone(this.eventDescriptors?.() ?? [])
331
+ .filter((descriptor) => activeEventTypes.has(descriptor.type));
332
+ this.deliveryMetadata = {
333
+ deliveryId,
334
+ activeResources: this.readActiveResources(),
335
+ eventDescriptors,
336
+ };
337
+ return this.deliveryMetadata;
338
+ }
339
+ }