@factory/droid-sdk 0.6.0 → 0.7.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 (80) hide show
  1. package/README.md +35 -482
  2. package/dist/chunk-5UXINOXG.mjs +24483 -0
  3. package/dist/chunk-5UXINOXG.mjs.map +1 -0
  4. package/dist/chunk-C3KHERVH.js +24483 -0
  5. package/dist/chunk-C3KHERVH.js.map +1 -0
  6. package/dist/{index-CwXX5IUH.d.cts → index-D_SzTnFR.d.mts} +83826 -81547
  7. package/dist/{index-CwXX5IUH.d.ts → index-D_SzTnFR.d.ts} +83826 -81547
  8. package/dist/index.d.mts +4 -0
  9. package/dist/index.d.ts +4 -93103
  10. package/dist/index.js +821 -11745
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +822 -0
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/node.d.mts +736 -0
  15. package/dist/node.d.ts +736 -0
  16. package/dist/node.js +4601 -0
  17. package/dist/node.js.map +1 -0
  18. package/dist/node.mjs +4601 -0
  19. package/dist/node.mjs.map +1 -0
  20. package/docs/typescript-sdk-reference.md +1260 -0
  21. package/examples/browser/daemon-lifecycle.ts +95 -0
  22. package/examples/browser/daemon-multi-session.ts +66 -0
  23. package/examples/browser/daemon-session.ts +73 -0
  24. package/examples/browser/index.html +68 -0
  25. package/examples/browser/list-sessions.ts +52 -0
  26. package/examples/{abort-session-stream.ts → node/abort-session-stream.ts} +8 -10
  27. package/examples/node/ask-user-elicitation.ts +35 -0
  28. package/examples/node/compact-session.ts +48 -0
  29. package/examples/node/enter-spec-mode.ts +66 -0
  30. package/examples/node/fork-session.ts +45 -0
  31. package/examples/node/hook-execution.ts +94 -0
  32. package/examples/node/image-attachment.ts +35 -0
  33. package/examples/node/init-metadata.ts +24 -0
  34. package/examples/{interrupt-session.ts → node/interrupt-session.ts} +7 -6
  35. package/examples/node/list-sessions.ts +20 -0
  36. package/examples/node/multi-turn-session.ts +33 -0
  37. package/examples/node/observability.ts +88 -0
  38. package/examples/node/permission-handler.ts +55 -0
  39. package/examples/node/rename-session.ts +29 -0
  40. package/examples/node/result-metadata.ts +34 -0
  41. package/examples/node/rewind-session.ts +69 -0
  42. package/examples/node/run.ts +25 -0
  43. package/examples/{sdk-mcp-tool.ts → node/sdk-mcp-tool.ts} +22 -12
  44. package/examples/node/session-settings.ts +35 -0
  45. package/examples/node/session-stream.ts +44 -0
  46. package/examples/node/spec-mode-new-session.ts +92 -0
  47. package/examples/node/spec-mode-same-session.ts +85 -0
  48. package/examples/node/structured-output.ts +73 -0
  49. package/examples/node/tool-controls.ts +26 -0
  50. package/examples/package.json +3 -0
  51. package/package.json +20 -42
  52. package/dist/index.cjs +0 -12135
  53. package/dist/index.cjs.map +0 -1
  54. package/dist/index.d.cts +0 -93103
  55. package/dist/protocol/index.cjs +0 -6466
  56. package/dist/protocol/index.cjs.map +0 -1
  57. package/dist/protocol/index.d.cts +0 -2
  58. package/dist/protocol/index.d.ts +0 -2
  59. package/dist/protocol/index.js +0 -6078
  60. package/dist/protocol/index.js.map +0 -1
  61. package/docs/daemon-usage-guide.md +0 -544
  62. package/docs/sdk-usage-guide.md +0 -748
  63. package/examples/daemon-multi-session.ts +0 -67
  64. package/examples/droid-dev-structured-output.ts +0 -44
  65. package/examples/fork-session.ts +0 -68
  66. package/examples/hook-execution.ts +0 -68
  67. package/examples/init-metadata.ts +0 -24
  68. package/examples/list-sessions.ts +0 -19
  69. package/examples/multi-turn-session.ts +0 -40
  70. package/examples/permission-handler.ts +0 -41
  71. package/examples/readme-structured-output.ts +0 -26
  72. package/examples/result-metadata.ts +0 -63
  73. package/examples/run.ts +0 -39
  74. package/examples/session-stream.ts +0 -57
  75. package/examples/spec-mode-new-session.ts +0 -61
  76. package/examples/spec-mode-same-session.ts +0 -72
  77. package/examples/structured-output.ts +0 -60
  78. package/examples/test-compact.ts +0 -65
  79. package/examples/test-rewind.ts +0 -87
  80. package/examples/tool-controls.ts +0 -37
package/dist/node.mjs ADDED
@@ -0,0 +1,4601 @@
1
+ import {
2
+ AbortError,
3
+ AddMcpServerRequestParamsSchema,
4
+ AddMcpServerRequestSchema,
5
+ AddMcpServerResponseSchema,
6
+ AddMcpServerResultSchema,
7
+ AddUserMessageRequestParamsSchema,
8
+ AddUserMessageRequestSchema,
9
+ AddUserMessageResponseSchema,
10
+ AddUserMessageResultSchema,
11
+ ApplyPatchToolConfirmationDetailsSchema,
12
+ AskUserCollectedAnswerSchema,
13
+ AskUserConfirmationDetailsSchema,
14
+ AskUserQuestionSchema,
15
+ AskUserRequestParamsSchema,
16
+ AskUserRequestSchema,
17
+ AskUserResponseSchema,
18
+ AskUserResultSchema,
19
+ AssistantTextCompleteNotificationSchema,
20
+ AssistantTextDeltaNotificationSchema,
21
+ AuthenticateMcpServerRequestParamsSchema,
22
+ AuthenticateMcpServerRequestSchema,
23
+ AuthenticateMcpServerResponseSchema,
24
+ AuthenticateMcpServerResultSchema,
25
+ AutonomyLevel,
26
+ AvailableModelConfigSchema,
27
+ Base64ImageSourceSchema,
28
+ BaseNotificationSchema,
29
+ BaseRequestSchema,
30
+ BaseResponseFailureSchema,
31
+ BaseResponseSuccessSchema,
32
+ COMPACTION_TIMEOUT,
33
+ CancelMcpAuthRequestParamsSchema,
34
+ CancelMcpAuthRequestSchema,
35
+ CancelMcpAuthResponseSchema,
36
+ CancelMcpAuthResultSchema,
37
+ ChangeWorkingDirectoryRequestParamsSchema,
38
+ ChangeWorkingDirectoryRequestSchema,
39
+ ChangeWorkingDirectoryResponseSchema,
40
+ ChangeWorkingDirectoryResultSchema,
41
+ ClearMcpAuthRequestParamsSchema,
42
+ ClearMcpAuthRequestSchema,
43
+ ClearMcpAuthResponseSchema,
44
+ ClearMcpAuthResultSchema,
45
+ CliRequestOrNotificationSchema,
46
+ ClientDestroyedError,
47
+ ClientRequestSchema,
48
+ ClientUiSurface,
49
+ CloseSessionRequestParamsSchema,
50
+ CloseSessionRequestSchema,
51
+ CloseSessionResponseSchema,
52
+ CloseSessionResultSchema,
53
+ CompactSessionRequestParamsSchema,
54
+ CompactSessionRequestSchema,
55
+ CompactSessionResponseSchema,
56
+ CompactSessionResultSchema,
57
+ ComputeLimitExceededError,
58
+ ComputerConnectAttemptTrigger,
59
+ ComputerConnectStartType,
60
+ ComputerListResponseSchema,
61
+ ComputerMetricSchema,
62
+ ComputerMetricsResponseSchema,
63
+ ComputerSchema,
64
+ ConcurrentStreamError,
65
+ ConnectionClosedError,
66
+ ConnectionError,
67
+ ConnectionFailureReason,
68
+ ContentBlockSchema,
69
+ ContextBreakdownCategorySchema,
70
+ ContextStatsAccuracy,
71
+ ContextStatsSchema,
72
+ CreateMessageNotificationSchema,
73
+ CreateToolConfirmationDetailsSchema,
74
+ DEFAULT_LOCAL_DAEMON_WS_URL,
75
+ DEFAULT_REQUEST_TIMEOUT,
76
+ DaemonAuthenticationMode,
77
+ DaemonClient,
78
+ DaemonDroidEvent,
79
+ DaemonRequestPermissionSchema,
80
+ DaemonSessionController,
81
+ DecompSessionType,
82
+ DiscoveredIssueSchema,
83
+ DismissalRecordSchema,
84
+ DismissalType,
85
+ DocumentBlockSchema,
86
+ DocumentSourceSchema,
87
+ DroidClientError,
88
+ DroidClientMethod,
89
+ DroidErrorType,
90
+ DroidEvent,
91
+ DroidHookEventSchema,
92
+ DroidHookExecutionResultSchema,
93
+ DroidHookOutputSchema,
94
+ DroidHookSpecificOutputSchema,
95
+ DroidInteractionMode,
96
+ DroidMessageType,
97
+ DroidServerMethod,
98
+ DroidWorkingState,
99
+ DroidWorkingStateChangedNotificationSchema,
100
+ EditToolConfirmationDetailsSchema,
101
+ EmptyResultSchema,
102
+ ErrorDetailSchema,
103
+ ErrorNotificationSchema,
104
+ ExecToolInfoSchema,
105
+ ExecuteRewindRequestParamsSchema,
106
+ ExecuteRewindRequestSchema,
107
+ ExecuteRewindResponseSchema,
108
+ ExecuteRewindResultSchema,
109
+ ExecuteToolConfirmationDetailsSchema,
110
+ ExitSpecModeConfirmationDetailsSchema,
111
+ FACTORY_CLIENT_HEADER,
112
+ FACTORY_CLIENT_VERSION,
113
+ FACTORY_PROTOCOL_VERSION,
114
+ FACTORY_PROTOCOL_VERSION2,
115
+ FactoryDaemonTransport,
116
+ FactoryDroidMessageRole,
117
+ FactoryDroidMessageSchema,
118
+ FeatureStatus,
119
+ FeatureSuccessState,
120
+ FeatureSuccessStateSchema,
121
+ ForkSessionRequestParamsSchema,
122
+ ForkSessionRequestSchema,
123
+ ForkSessionResponseSchema,
124
+ ForkSessionResultSchema,
125
+ GetContextBreakdownResponseSchema,
126
+ GetContextBreakdownResultSchema,
127
+ GetContextStatsRequestParamsSchema,
128
+ GetContextStatsRequestSchema,
129
+ GetContextStatsResponseSchema,
130
+ GetRewindInfoRequestParamsSchema,
131
+ GetRewindInfoRequestSchema,
132
+ GetRewindInfoResponseSchema,
133
+ GetRewindInfoResultSchema,
134
+ GitRepoInfoSchema,
135
+ HandoffItemsDismissedEntrySchema,
136
+ HandoffSchema,
137
+ HookCommandSchema,
138
+ HookExecutionCompletedNotificationSchema,
139
+ HookExecutionStartedNotificationSchema,
140
+ HookResultSchema,
141
+ HttpHeaderSchema,
142
+ HttpMcpSchema,
143
+ IPC_DAEMON_URL,
144
+ ImageBlockSchema,
145
+ InProcessDaemonClientTransport,
146
+ InitializeSessionRequestParamsSchema,
147
+ InitializeSessionRequestSchema,
148
+ InitializeSessionResponseSchema,
149
+ InitializeSessionResultSchema,
150
+ InitializeSessionResultSchema2,
151
+ InteractiveCheckSchema,
152
+ InterruptSessionRequestParamsSchema,
153
+ InterruptSessionRequestSchema,
154
+ InterruptSessionResponseSchema,
155
+ InterruptSessionResultSchema,
156
+ InvalidSessionCwdError,
157
+ IpcDaemonClientTransport,
158
+ IssueSeverity,
159
+ JSONRPC_VERSION,
160
+ JSONRPC_VERSION2,
161
+ JSONRPC_VERSION3,
162
+ JsonArraySchema,
163
+ JsonObjectSchema,
164
+ JsonRpcBaseResponseSchema,
165
+ JsonRpcEnvelopeSchema,
166
+ JsonRpcErrorCode,
167
+ JsonRpcErrorSchema,
168
+ JsonRpcMessageSchema,
169
+ JsonRpcMessageType,
170
+ JsonRpcNotificationSchema,
171
+ JsonRpcRequestError,
172
+ JsonRpcRequestSchema,
173
+ JsonRpcResponseFailureSchema,
174
+ JsonRpcResponseSchema,
175
+ JsonRpcResponseSuccessSchema,
176
+ JsonValueSchema,
177
+ KillWorkerSessionRequestParamsSchema,
178
+ KillWorkerSessionRequestSchema,
179
+ KillWorkerSessionResponseSchema,
180
+ KillWorkerSessionResultSchema,
181
+ LEGACY_FACTORY_API_VERSION,
182
+ LEGACY_FACTORY_API_VERSION2,
183
+ LOCAL_MACHINE_ID,
184
+ ListCommandsResponseSchema,
185
+ ListMcpRegistryRequestParamsSchema,
186
+ ListMcpRegistryRequestSchema,
187
+ ListMcpRegistryResponseSchema,
188
+ ListMcpRegistryResultSchema,
189
+ ListMcpServersRequestParamsSchema,
190
+ ListMcpServersRequestSchema,
191
+ ListMcpServersResponseSchema,
192
+ ListMcpServersResultSchema,
193
+ ListMcpToolsRequestParamsSchema,
194
+ ListMcpToolsRequestSchema,
195
+ ListMcpToolsResponseSchema,
196
+ ListMcpToolsResultSchema,
197
+ ListSkillsRequestParamsSchema,
198
+ ListSkillsRequestSchema,
199
+ ListSkillsResponseSchema,
200
+ ListSkillsResultSchema,
201
+ ListToolsRequestParamsSchema,
202
+ ListToolsRequestSchema,
203
+ ListToolsResponseSchema,
204
+ ListToolsResultSchema,
205
+ LoadSessionRequestParamsSchema,
206
+ LoadSessionRequestSchema,
207
+ LoadSessionResponseSchema,
208
+ LoadSessionResultSchema,
209
+ MACHINE_TYPE_WEBSOCKET_OVERRIDES,
210
+ MANAGED_COMPUTER_MAX_RETRIES,
211
+ MCP_AUTH_TIMEOUT,
212
+ MachineTemplateBuildStatusSchema,
213
+ MachineTemplateListResponseSchema,
214
+ MachineTemplateSchema,
215
+ MachineType,
216
+ McpAuthCompletedNotificationSchema,
217
+ McpAuthOutcome,
218
+ McpAuthRequiredNotificationSchema,
219
+ McpHttpServerConfigFieldsSchema,
220
+ McpRegistryServerSchema,
221
+ McpServerConfigSchema,
222
+ McpServerStatus,
223
+ McpServerStatusInfoSchema,
224
+ McpServerType,
225
+ McpSseServerConfigFieldsSchema,
226
+ McpStatus,
227
+ McpStatusChangedNotificationSchema,
228
+ McpStatusSummarySchema,
229
+ McpStdioServerConfigFieldsSchema,
230
+ McpToolConfirmationDetailsSchema,
231
+ McpToolInfoSchema,
232
+ McpToolInputSchemaSchema,
233
+ MessageVisibility,
234
+ MetaError,
235
+ Metric,
236
+ MilestoneValidationTriggeredEntrySchema,
237
+ MissionAcceptedEntrySchema,
238
+ MissionFeatureSchema,
239
+ MissionFeaturesChangedNotificationSchema,
240
+ MissionHeartbeatNotificationSchema,
241
+ MissionPausedEntrySchema,
242
+ MissionProgressEntryNotificationSchema,
243
+ MissionResumedEntrySchema,
244
+ MissionRunStartedEntrySchema,
245
+ MissionState,
246
+ MissionStateChangedNotificationSchema,
247
+ MissionStateSchema,
248
+ MissionWorkerCompletedNotificationSchema,
249
+ MissionWorkerStartedNotificationSchema,
250
+ ModelProvider,
251
+ MultiMissionStateManager,
252
+ MultiSessionStateManager,
253
+ OtelTracing,
254
+ OutputFormatSchema,
255
+ OutputFormatType,
256
+ PermissionResolvedNotificationSchema,
257
+ ProcessExitError,
258
+ ProgressLogEntrySchema,
259
+ ProgressLogEntryType,
260
+ ProposeMissionConfirmationDetailsSchema,
261
+ ProtocolError,
262
+ QueuedUserMessageDisplayGroup,
263
+ QueuedUserMessageKind,
264
+ REWIND_TIMEOUT,
265
+ ReasoningEffort,
266
+ RedactedThinkingBlockSchema,
267
+ RefreshComputerResponseSchema,
268
+ RelayConnectionError,
269
+ RemoteSessionListResponseSchema,
270
+ RemoteSessionSchema,
271
+ RemoveMcpServerRequestParamsSchema,
272
+ RemoveMcpServerRequestSchema,
273
+ RemoveMcpServerResponseSchema,
274
+ RemoveMcpServerResultSchema,
275
+ RenameSessionRequestParamsSchema,
276
+ RenameSessionRequestSchema,
277
+ RenameSessionResponseSchema,
278
+ RenameSessionResultSchema,
279
+ RequestPermissionRequestParamsSchema,
280
+ RequestPermissionRequestSchema,
281
+ RequestPermissionResponseSchema,
282
+ RequestPermissionResultSchema,
283
+ ResolveQueuedUserMessageResponseSchema,
284
+ RewindEvictedFileSchema,
285
+ RewindFileCreationSchema,
286
+ RewindFileSnapshotSchema,
287
+ SDK_TAG,
288
+ SDK_VERSION,
289
+ SESSION_INIT_TIMEOUT,
290
+ SLACK_DELEGATION_MAX_RETRIES,
291
+ ServerRequestHandlerType,
292
+ SessionError,
293
+ SessionMetadataSchema,
294
+ SessionNotFoundError,
295
+ SessionNotificationParamsSchema,
296
+ SessionNotificationPayloadSchema,
297
+ SessionNotificationSchema,
298
+ SessionNotificationSchemaList,
299
+ SessionNotificationType,
300
+ SessionPlatform,
301
+ SessionReplacedError,
302
+ SessionReplacementError,
303
+ SessionSettingsFileSchema,
304
+ SessionSettingsSchema,
305
+ SessionSourceSchema,
306
+ SessionStartDecompSessionTypeSchema,
307
+ SessionStartEventSchema,
308
+ SessionTagSchema,
309
+ SessionTitleUpdatedNotificationSchema,
310
+ SessionTokenUsageChangedNotificationSchema,
311
+ SetSkillDisabledRequestParamsSchema,
312
+ SetSkillDisabledRequestSchema,
313
+ SetSkillDisabledResponseSchema,
314
+ SetSkillDisabledResultSchema,
315
+ SettingsLevel,
316
+ SettingsUpdatedNotificationSchema,
317
+ SettingsUpdatedPayloadSchema,
318
+ SkillDeviationSchema,
319
+ SkillFeedbackSchema,
320
+ SkillInfoSchema,
321
+ SkillLocation,
322
+ SkillResourceSchema,
323
+ SpanAttribute,
324
+ SpanEvent,
325
+ SpanName,
326
+ SseMcpSchema,
327
+ StartMissionRunConfirmationDetailsSchema,
328
+ StdioMcpSchema,
329
+ StreamStateTracker,
330
+ StructuredOutputErrorSchema,
331
+ StructuredOutputNotificationSchema,
332
+ SubmitBugReportRequestParamsSchema,
333
+ SubmitBugReportRequestSchema,
334
+ SubmitBugReportResponseSchema,
335
+ SubmitBugReportResultSchema,
336
+ SubmitMcpAuthCodeRequestParamsSchema,
337
+ SubmitMcpAuthCodeRequestSchema,
338
+ SubmitMcpAuthCodeResponseSchema,
339
+ SubmitMcpAuthCodeResultSchema,
340
+ SubmitMcpAuthErrorResponseSchema,
341
+ SuccessResultSchema,
342
+ TestCaseSchema,
343
+ TestFileSchema,
344
+ TestsSchema,
345
+ TextBlockSchema,
346
+ ThinkingBlockSchema,
347
+ ThinkingTextCompleteNotificationSchema,
348
+ ThinkingTextDeltaNotificationSchema,
349
+ TimeoutError,
350
+ ToggleMcpServerRequestParamsSchema,
351
+ ToggleMcpServerRequestSchema,
352
+ ToggleMcpServerResponseSchema,
353
+ ToggleMcpServerResultSchema,
354
+ ToggleMcpToolRequestParamsSchema,
355
+ ToggleMcpToolRequestSchema,
356
+ ToggleMcpToolResponseSchema,
357
+ ToggleMcpToolResultSchema,
358
+ TokenUsageSchema,
359
+ ToolCallNotificationSchema,
360
+ ToolConfirmationDetailsSchema,
361
+ ToolConfirmationInfoSchema,
362
+ ToolConfirmationListItemSchema,
363
+ ToolConfirmationOutcome,
364
+ ToolConfirmationType,
365
+ ToolProgressUpdateNotificationSchema,
366
+ ToolProgressUpdateSchema,
367
+ ToolResultNotificationSchema,
368
+ ToolResultSchema,
369
+ ToolSelectionOverridesSchema,
370
+ ToolUseSchema,
371
+ ToolUseSchema2,
372
+ TraceContextMetaSchema,
373
+ TunnelConnection,
374
+ UpdateSessionSettingsRequestParamsSchema,
375
+ UpdateSessionSettingsRequestSchema,
376
+ UpdateSessionSettingsResponseSchema,
377
+ UpdateSessionSettingsResultSchema,
378
+ VerificationCommandSchema,
379
+ VerificationSchema,
380
+ WarmupCacheResponseSchema,
381
+ WebSocketConnectionError,
382
+ WebSocketDaemonTransport,
383
+ WorkerCompletedEntrySchema,
384
+ WorkerFailedEntrySchema,
385
+ WorkerPausedEntrySchema,
386
+ WorkerSelectedFeatureEntrySchema,
387
+ WorkerStartedEntrySchema,
388
+ WorkerStateInfoSchema,
389
+ buildUserMessageContentBlocks,
390
+ configureDaemonCoreDeps,
391
+ connectAndAuthenticate,
392
+ connectToDaemon,
393
+ connectWithRetry,
394
+ convertNotificationToStreamMessage,
395
+ createComputer,
396
+ createResponseSchema,
397
+ createWebSocketDaemonClient,
398
+ defaultDaemonCoreDeps,
399
+ deleteComputer,
400
+ extractInnerNotification,
401
+ filterMessagesForUI,
402
+ getComputer,
403
+ getComputerByName,
404
+ getComputerMetrics,
405
+ getMachineTemplate,
406
+ getPermissionToolInputForDisplay,
407
+ getQueuedUserMessageDisplayGroup,
408
+ getQueuedUserMessageReviewPriority,
409
+ getSubagentCallingMetadata,
410
+ getToolResultBlocks,
411
+ getToolResultToolUseId,
412
+ hasDecoupledInteractionSettings,
413
+ hasSubagentSessionTag,
414
+ inspectJsonRpcEnvelope,
415
+ isDaemonQueuedMessageKind,
416
+ isPendingToolResultMarker,
417
+ isPersistedHookMessage,
418
+ isReviewableQueuedMessageKind,
419
+ listComputers,
420
+ listMachineTemplates,
421
+ listRemoteSessions,
422
+ machineTypeToMachineConnectionType,
423
+ mergeSessionSettings,
424
+ orderMessagesByParentChain,
425
+ recordComputerConnectSli,
426
+ refreshComputer,
427
+ repairParentChainCorruption,
428
+ restartComputer,
429
+ retryInstallDeps,
430
+ retryWithLogger,
431
+ streamFromClient,
432
+ sumTokenUsage,
433
+ summarizeSessionToolUsage,
434
+ toError,
435
+ unwrapResponseResult,
436
+ updateComputer,
437
+ wireAbortSignal
438
+ } from "./chunk-5UXINOXG.mjs";
439
+
440
+ // src/exec-core/client.ts
441
+ import EventEmitter from "events";
442
+ import { v4 as uuidv4 } from "uuid";
443
+ import { z } from "zod";
444
+
445
+ // src/exec-core/constants.ts
446
+ var DEFAULT_REQUEST_TIMEOUT2 = 3e4;
447
+ var SESSION_INIT_TIMEOUT2 = 6e4;
448
+ var COMPACTION_TIMEOUT2 = 24e4;
449
+ var MCP_AUTH_TIMEOUT2 = 3e5;
450
+ var WINDOWS_JOB_OBJECT_ERROR_MARKER = "AssignProcessToJobObject";
451
+ var CLI_JSONRPC_CHILD_SPAWN_LATENCY_METRIC = "cli_jsonrpc_child_spawn_latency";
452
+ var noopLogger = {
453
+ info() {
454
+ },
455
+ warn() {
456
+ },
457
+ exception() {
458
+ }
459
+ };
460
+
461
+ // src/exec-core/default-deps.ts
462
+ function getRuntimeEnvironment() {
463
+ return globalThis.process?.env ?? {};
464
+ }
465
+ var defaultExecCoreDeps = {
466
+ logger: {
467
+ info() {
468
+ },
469
+ warn() {
470
+ },
471
+ exception() {
472
+ }
473
+ },
474
+ metrics: {
475
+ addToCounter() {
476
+ },
477
+ recordDuration() {
478
+ }
479
+ },
480
+ tracing: {
481
+ getCurrentContext() {
482
+ return void 0;
483
+ },
484
+ injectContext() {
485
+ }
486
+ },
487
+ commandResolver: {
488
+ resolveDroidCommand(isDevelopment) {
489
+ return {
490
+ execPath: isDevelopment ? "droid-dev" : "droid",
491
+ prefixArgs: []
492
+ };
493
+ }
494
+ },
495
+ factoryPathResolver: {
496
+ getFactoryHome() {
497
+ const env = getRuntimeEnvironment();
498
+ return env.FACTORY_HOME_OVERRIDE ?? env.HOME ?? env.USERPROFILE ?? "";
499
+ },
500
+ getFactoryDirName() {
501
+ return ".factory";
502
+ }
503
+ },
504
+ environmentResolver: {
505
+ resolveTransportLogEnvValue() {
506
+ return getRuntimeEnvironment().FACTORY_DROID_SDK_TRANSPORT_LOG;
507
+ },
508
+ sanitizeSpawnEnv(env) {
509
+ return env;
510
+ }
511
+ }
512
+ };
513
+
514
+ // src/exec-core/enums.ts
515
+ var DroidClientEvent = /* @__PURE__ */ ((DroidClientEvent2) => {
516
+ DroidClientEvent2["SESSION_NOTIFICATION"] = "session_notification";
517
+ DroidClientEvent2["REQUEST_PERMISSION"] = "request_permission";
518
+ DroidClientEvent2["ASK_USER"] = "ask_user";
519
+ DroidClientEvent2["ERROR"] = "error";
520
+ return DroidClientEvent2;
521
+ })(DroidClientEvent || {});
522
+ var DroidProcessMode = /* @__PURE__ */ ((DroidProcessMode2) => {
523
+ DroidProcessMode2["Acp"] = "acp";
524
+ DroidProcessMode2["StreamJsonRpc"] = "stream-jsonrpc";
525
+ return DroidProcessMode2;
526
+ })(DroidProcessMode || {});
527
+ var TransportDirection = /* @__PURE__ */ ((TransportDirection2) => {
528
+ TransportDirection2["In"] = "in";
529
+ TransportDirection2["Out"] = "out";
530
+ TransportDirection2["OutFailed"] = "out_failed";
531
+ return TransportDirection2;
532
+ })(TransportDirection || {});
533
+
534
+ // ../droid-sdk-core/src/observability.ts
535
+ function sanitizeAttributes(attributes) {
536
+ if (attributes === void 0) {
537
+ return void 0;
538
+ }
539
+ const sanitized = {};
540
+ for (const [key, value] of Object.entries(attributes)) {
541
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
542
+ sanitized[key] = value;
543
+ }
544
+ }
545
+ return Object.keys(sanitized).length > 0 ? sanitized : void 0;
546
+ }
547
+ function serializeError(error) {
548
+ if (error instanceof Error) {
549
+ const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
550
+ return {
551
+ name: error.name || void 0,
552
+ message: error.message,
553
+ ...code !== void 0 && { code }
554
+ };
555
+ }
556
+ return { message: String(error) };
557
+ }
558
+ function handleSinkFailure(error, options) {
559
+ try {
560
+ options?.onError?.(error);
561
+ } catch {
562
+ }
563
+ }
564
+ function emitDroidLog(observability, event, options) {
565
+ const sink = observability?.logger;
566
+ if (!sink) {
567
+ return false;
568
+ }
569
+ try {
570
+ sink.log({
571
+ level: event.level,
572
+ name: event.name,
573
+ message: event.message,
574
+ attributes: sanitizeAttributes(event.attributes),
575
+ ...event.error !== void 0 && {
576
+ error: serializeError(event.error)
577
+ }
578
+ });
579
+ return true;
580
+ } catch (error) {
581
+ handleSinkFailure(error, options);
582
+ return false;
583
+ }
584
+ }
585
+ function recordDroidMetric(observability, event, options) {
586
+ const sink = observability?.metrics;
587
+ if (!sink) {
588
+ return false;
589
+ }
590
+ try {
591
+ sink.record({
592
+ name: event.name,
593
+ kind: event.kind,
594
+ value: event.value,
595
+ unit: event.unit,
596
+ attributes: sanitizeAttributes(event.attributes)
597
+ });
598
+ return true;
599
+ } catch (error) {
600
+ handleSinkFailure(error, options);
601
+ return false;
602
+ }
603
+ }
604
+ function injectDroidTraceContext(observability, carrier, options) {
605
+ const sink = observability?.tracing;
606
+ if (!sink) {
607
+ return false;
608
+ }
609
+ try {
610
+ sink.inject(carrier);
611
+ return true;
612
+ } catch (error) {
613
+ handleSinkFailure(error, options);
614
+ return false;
615
+ }
616
+ }
617
+
618
+ // src/exec-core/deps.ts
619
+ function logWarn(logger, message, metadata) {
620
+ logger.warn(message, metadata);
621
+ }
622
+
623
+ // src/exec-core/observability-adapter.ts
624
+ function createSinkFailureOptions(fallback) {
625
+ return {
626
+ onError(sinkError) {
627
+ logWarn(fallback, "[droid-sdk observability] customer sink threw", {
628
+ cause: sinkError
629
+ });
630
+ }
631
+ };
632
+ }
633
+ var CONTENT_BEARING_KEYS = ["output", "preview", "stderrTail"];
634
+ function redactContentForCustomerSink(metadata) {
635
+ if (metadata === void 0) {
636
+ return void 0;
637
+ }
638
+ let redacted;
639
+ for (const key of CONTENT_BEARING_KEYS) {
640
+ if (!(key in metadata)) {
641
+ continue;
642
+ }
643
+ redacted ??= { ...metadata };
644
+ const value = redacted[key];
645
+ delete redacted[key];
646
+ if (typeof value === "string") {
647
+ redacted[`${key}ByteLength`] = new TextEncoder().encode(value).byteLength;
648
+ }
649
+ }
650
+ return redacted ?? metadata;
651
+ }
652
+ function createLogger(observability, fallback) {
653
+ const sink = observability?.logger;
654
+ if (!sink) {
655
+ return fallback;
656
+ }
657
+ const sinkObservability = { logger: sink };
658
+ const sinkFailureOptions = createSinkFailureOptions(fallback);
659
+ return {
660
+ info(message, metadata) {
661
+ emitDroidLog(
662
+ sinkObservability,
663
+ {
664
+ level: "info",
665
+ name: "droid.sdk.info",
666
+ message,
667
+ attributes: redactContentForCustomerSink(metadata)
668
+ },
669
+ sinkFailureOptions
670
+ );
671
+ },
672
+ warn(message, metadata) {
673
+ emitDroidLog(
674
+ sinkObservability,
675
+ {
676
+ level: "warn",
677
+ name: "droid.sdk.warn",
678
+ message,
679
+ attributes: redactContentForCustomerSink(metadata)
680
+ },
681
+ sinkFailureOptions
682
+ );
683
+ },
684
+ exception(error, message, metadata) {
685
+ emitDroidLog(
686
+ sinkObservability,
687
+ {
688
+ level: "error",
689
+ name: "droid.sdk.error",
690
+ message,
691
+ attributes: redactContentForCustomerSink(metadata),
692
+ error
693
+ },
694
+ sinkFailureOptions
695
+ );
696
+ }
697
+ };
698
+ }
699
+ function createMetrics(observability, fallback, failureLogger) {
700
+ const sink = observability?.metrics;
701
+ if (!sink) {
702
+ return fallback;
703
+ }
704
+ const sinkObservability = { metrics: sink };
705
+ const sinkFailureOptions = createSinkFailureOptions(failureLogger);
706
+ return {
707
+ addToCounter(metric, value, tags) {
708
+ recordDroidMetric(
709
+ sinkObservability,
710
+ {
711
+ name: metric,
712
+ kind: "counter",
713
+ value,
714
+ unit: "1",
715
+ attributes: tags
716
+ },
717
+ sinkFailureOptions
718
+ );
719
+ },
720
+ recordDuration(metric, valueMs, tags) {
721
+ recordDroidMetric(
722
+ sinkObservability,
723
+ {
724
+ name: metric,
725
+ kind: "histogram",
726
+ value: valueMs,
727
+ unit: "ms",
728
+ attributes: tags
729
+ },
730
+ sinkFailureOptions
731
+ );
732
+ }
733
+ };
734
+ }
735
+ function createTracing(observability, fallback, failureLogger) {
736
+ const sink = observability?.tracing;
737
+ if (!sink) {
738
+ return fallback;
739
+ }
740
+ const sinkObservability = { tracing: sink };
741
+ const sinkFailureOptions = createSinkFailureOptions(failureLogger);
742
+ return {
743
+ getCurrentContext() {
744
+ return {};
745
+ },
746
+ injectContext(meta) {
747
+ const carrier = {};
748
+ if (!injectDroidTraceContext(sinkObservability, carrier, sinkFailureOptions)) {
749
+ return;
750
+ }
751
+ if (carrier.traceparent !== void 0) {
752
+ meta.traceparent = carrier.traceparent;
753
+ }
754
+ if (carrier.tracestate !== void 0) {
755
+ meta.tracestate = carrier.tracestate;
756
+ }
757
+ }
758
+ };
759
+ }
760
+ function resolveExecCoreDeps(observability, fallback = defaultExecCoreDeps) {
761
+ return {
762
+ logger: createLogger(observability, fallback.logger),
763
+ metrics: createMetrics(observability, fallback.metrics, fallback.logger),
764
+ tracing: createTracing(observability, fallback.tracing, fallback.logger),
765
+ commandResolver: fallback.commandResolver,
766
+ factoryPathResolver: fallback.factoryPathResolver,
767
+ environmentResolver: fallback.environmentResolver
768
+ };
769
+ }
770
+
771
+ // src/exec-core/client.ts
772
+ function getResponseId(response) {
773
+ const parsed = JsonRpcBaseResponseSchema.safeParse(response);
774
+ return parsed.success ? parsed.data.id : void 0;
775
+ }
776
+ var JsonRpcEnvelopePeekSchema = JsonRpcEnvelopeSchema.partial().extend({
777
+ type: z.nativeEnum(JsonRpcMessageType).optional(),
778
+ method: z.string().optional(),
779
+ id: z.string().nullable().optional()
780
+ }).passthrough();
781
+ function inspectJsonRpcEnvelope2(message) {
782
+ const result = JsonRpcEnvelopePeekSchema.safeParse(message);
783
+ if (!result.success) {
784
+ return { protocolVersionMismatch: null };
785
+ }
786
+ const envelope = result.data;
787
+ return {
788
+ protocolVersionMismatch: envelope.factoryProtocolVersion !== void 0 && envelope.factoryProtocolVersion !== FACTORY_PROTOCOL_VERSION ? {
789
+ localFactoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
790
+ peerFactoryProtocolVersion: envelope.factoryProtocolVersion,
791
+ messageType: envelope.type,
792
+ method: envelope.method,
793
+ requestId: envelope.id
794
+ } : null
795
+ };
796
+ }
797
+ var DroidClient = class _DroidClient extends EventEmitter {
798
+ transport;
799
+ requestTimeout;
800
+ pendingRequests = /* @__PURE__ */ new Map();
801
+ permissionHandlers = /* @__PURE__ */ new Map();
802
+ askUserHandlers = /* @__PURE__ */ new Map();
803
+ pendingPermissionRequests = /* @__PURE__ */ new Map();
804
+ pendingAskUserRequests = /* @__PURE__ */ new Map();
805
+ currentSessionId = null;
806
+ peerProtocolVersion;
807
+ /**
808
+ * Sticky error from a transport failure. Once set, all subsequent
809
+ * `sendRequest()` calls throw this error immediately, preventing
810
+ * requests from hanging on a dead transport.
811
+ */
812
+ transportError = null;
813
+ logger;
814
+ tracing;
815
+ onRequestSettled;
816
+ constructor(options, deps = defaultExecCoreDeps) {
817
+ super();
818
+ this.transport = options.transport;
819
+ const resolved = resolveExecCoreDeps(options.observability, deps);
820
+ this.logger = resolved.logger;
821
+ this.tracing = resolved.tracing;
822
+ this.requestTimeout = options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT2;
823
+ this.onRequestSettled = options.onRequestSettled;
824
+ this.transport.onMessage((message) => {
825
+ void this.handleMessage(message).catch((error) => {
826
+ const err = error instanceof Error ? error : new Error(String(error));
827
+ this.emit(
828
+ "session_notification" /* SESSION_NOTIFICATION */,
829
+ _DroidClient.createNotificationEvent(
830
+ _DroidClient.createErrorNotification(err)
831
+ )
832
+ );
833
+ });
834
+ });
835
+ this.transport.onError((error) => {
836
+ const err = error instanceof Error ? error : new Error(String(error));
837
+ this.logger.exception(err, "Transport error");
838
+ this.transportError = err;
839
+ this.rejectAllPending(err);
840
+ if (this.listenerCount("error" /* ERROR */) > 0) {
841
+ this.emit("error" /* ERROR */, err);
842
+ }
843
+ this.emit(
844
+ "session_notification" /* SESSION_NOTIFICATION */,
845
+ _DroidClient.createNotificationEvent(
846
+ _DroidClient.createErrorNotification(err)
847
+ )
848
+ );
849
+ });
850
+ }
851
+ get sessionId() {
852
+ return this.currentSessionId;
853
+ }
854
+ get isConnected() {
855
+ return this.transport.isConnected;
856
+ }
857
+ requireMcpOAuthOptOutSupport() {
858
+ if (this.peerProtocolVersion === FACTORY_PROTOCOL_VERSION) {
859
+ return;
860
+ }
861
+ throw new ProtocolError(
862
+ "MCP OAuth opt-out requires a confirmed matching Droid protocol version. The connected Droid reported an incompatible protocol version and cannot disable OAuth for MCP servers.",
863
+ {
864
+ value: {
865
+ localFactoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
866
+ peerFactoryProtocolVersion: this.peerProtocolVersion
867
+ }
868
+ }
869
+ );
870
+ }
871
+ validateMcpServersProtocolSupport(mcpServers) {
872
+ if (mcpServers?.some((server) => "oauth" in server && server.oauth === false)) {
873
+ this.requireMcpOAuthOptOutSupport();
874
+ }
875
+ }
876
+ async initializeSession(params) {
877
+ const request = {
878
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
879
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
880
+ type: "request",
881
+ jsonrpc: JSONRPC_VERSION2,
882
+ id: uuidv4(),
883
+ method: "droid.initialize_session" /* INITIALIZE_SESSION */,
884
+ params
885
+ };
886
+ const rawResponse = await this.sendRequest(request, SESSION_INIT_TIMEOUT2);
887
+ const response = InitializeSessionResponseSchema.parse(rawResponse);
888
+ this.peerProtocolVersion = response.factoryProtocolVersion;
889
+ if (response.error) {
890
+ throw new ProtocolError("Initialize session request failed", {
891
+ requestId: request.id,
892
+ code: response.error.code,
893
+ message: response.error.message,
894
+ data: response.error.data
895
+ });
896
+ }
897
+ this.validateMcpServersProtocolSupport(params.mcpServers);
898
+ const result = InitializeSessionResultSchema.parse(response.result);
899
+ this.currentSessionId = result.sessionId;
900
+ return response;
901
+ }
902
+ async loadSession(params) {
903
+ const request = {
904
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
905
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
906
+ type: "request",
907
+ jsonrpc: JSONRPC_VERSION2,
908
+ id: uuidv4(),
909
+ method: "droid.load_session" /* LOAD_SESSION */,
910
+ params
911
+ };
912
+ const rawResponse = await this.sendRequest(request, SESSION_INIT_TIMEOUT2);
913
+ const response = LoadSessionResponseSchema.parse(rawResponse);
914
+ this.peerProtocolVersion = response.factoryProtocolVersion;
915
+ if (response.error) {
916
+ const isSessionNotFound = response.error.code === -32004 /* ENTITY_NOT_FOUND */;
917
+ if (isSessionNotFound) {
918
+ throw new SessionNotFoundError(params.sessionId, {
919
+ requestId: request.id,
920
+ code: response.error.code,
921
+ message: response.error.message,
922
+ data: response.error.data
923
+ });
924
+ }
925
+ throw new ProtocolError("Load session request failed", {
926
+ requestId: request.id,
927
+ code: response.error.code,
928
+ message: response.error.message,
929
+ data: response.error.data
930
+ });
931
+ }
932
+ this.validateMcpServersProtocolSupport(params.mcpServers);
933
+ this.currentSessionId = params.sessionId;
934
+ return response;
935
+ }
936
+ async addUserMessage(params, requestId) {
937
+ if (!this.currentSessionId) {
938
+ throw new SessionError(
939
+ "No active session. Call initializeSession or loadSession first."
940
+ );
941
+ }
942
+ const request = {
943
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
944
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
945
+ type: "request",
946
+ jsonrpc: JSONRPC_VERSION2,
947
+ id: requestId ?? uuidv4(),
948
+ method: "droid.add_user_message" /* ADD_USER_MESSAGE */,
949
+ params: {
950
+ ...params.messageId && { messageId: params.messageId },
951
+ text: params.text,
952
+ images: params.images,
953
+ imagePaths: params.imagePaths,
954
+ files: params.files,
955
+ outputFormat: params.outputFormat,
956
+ ...params.skipAgentLoop && { skipAgentLoop: params.skipAgentLoop },
957
+ queuePlacement: params.queuePlacement ?? "end_of_turn" /* EndOfTurn */,
958
+ ...params.role && { role: params.role },
959
+ ...params.visibility && { visibility: params.visibility }
960
+ }
961
+ };
962
+ const rawResponse = await this.sendRequest(request);
963
+ const response = AddUserMessageResponseSchema.parse(rawResponse);
964
+ if (response.error) {
965
+ throw new ProtocolError("Add user message request failed", {
966
+ requestId: request.id,
967
+ code: response.error.code,
968
+ message: response.error.message,
969
+ data: response.error.data
970
+ });
971
+ }
972
+ return response;
973
+ }
974
+ async resolveQueuedUserMessage(params) {
975
+ if (!this.currentSessionId) {
976
+ throw new SessionError(
977
+ "No active session. Call initializeSession or loadSession first."
978
+ );
979
+ }
980
+ const request = {
981
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
982
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
983
+ type: "request",
984
+ jsonrpc: JSONRPC_VERSION2,
985
+ id: uuidv4(),
986
+ method: "droid.resolve_queued_user_message" /* RESOLVE_QUEUED_USER_MESSAGE */,
987
+ params
988
+ };
989
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
990
+ const response = ResolveQueuedUserMessageResponseSchema.parse(rawResponse);
991
+ if (response.error) {
992
+ throw new ProtocolError("Resolve queued user message request failed", {
993
+ requestId: request.id,
994
+ code: response.error.code,
995
+ message: response.error.message,
996
+ data: response.error.data
997
+ });
998
+ }
999
+ return response;
1000
+ }
1001
+ async interruptSession(params = {}) {
1002
+ if (!this.currentSessionId) {
1003
+ throw new SessionError(
1004
+ "No active session. Call initializeSession or loadSession first."
1005
+ );
1006
+ }
1007
+ const request = {
1008
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1009
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1010
+ type: "request",
1011
+ jsonrpc: JSONRPC_VERSION2,
1012
+ id: uuidv4(),
1013
+ method: "droid.interrupt_session" /* INTERRUPT_SESSION */,
1014
+ params
1015
+ };
1016
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1017
+ const response = InterruptSessionResponseSchema.parse(rawResponse);
1018
+ if (response.error) {
1019
+ throw new ProtocolError("Interrupt session request failed", {
1020
+ requestId: request.id,
1021
+ code: response.error.code,
1022
+ message: response.error.message,
1023
+ data: response.error.data
1024
+ });
1025
+ }
1026
+ return response;
1027
+ }
1028
+ async closeSession(params = {}) {
1029
+ if (!this.currentSessionId) {
1030
+ throw new SessionError(
1031
+ "No active session. Call initializeSession or loadSession first."
1032
+ );
1033
+ }
1034
+ const request = {
1035
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1036
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1037
+ type: "request",
1038
+ jsonrpc: JSONRPC_VERSION2,
1039
+ id: uuidv4(),
1040
+ method: "droid.close_session" /* CLOSE_SESSION */,
1041
+ params
1042
+ };
1043
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1044
+ const response = CloseSessionResponseSchema.parse(rawResponse);
1045
+ if (response.error) {
1046
+ throw new ProtocolError("Close session request failed", {
1047
+ requestId: request.id,
1048
+ code: response.error.code,
1049
+ message: response.error.message,
1050
+ data: response.error.data
1051
+ });
1052
+ }
1053
+ return response;
1054
+ }
1055
+ async killWorkerSession(params) {
1056
+ if (!this.currentSessionId) {
1057
+ throw new SessionError(
1058
+ "No active session. Call initializeSession or loadSession first."
1059
+ );
1060
+ }
1061
+ const request = {
1062
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1063
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1064
+ type: "request",
1065
+ jsonrpc: JSONRPC_VERSION2,
1066
+ id: uuidv4(),
1067
+ method: "droid.kill_worker_session" /* KILL_WORKER_SESSION */,
1068
+ params
1069
+ };
1070
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1071
+ const response = KillWorkerSessionResponseSchema.parse(rawResponse);
1072
+ if (response.error) {
1073
+ throw new ProtocolError("Kill worker session request failed", {
1074
+ requestId: request.id,
1075
+ code: response.error.code,
1076
+ message: response.error.message,
1077
+ data: response.error.data
1078
+ });
1079
+ }
1080
+ return response;
1081
+ }
1082
+ async updateSessionSettings(params, requestId) {
1083
+ if (!this.currentSessionId) {
1084
+ throw new SessionError(
1085
+ "No active session. Call initializeSession or loadSession first."
1086
+ );
1087
+ }
1088
+ const request = {
1089
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1090
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1091
+ type: "request",
1092
+ jsonrpc: JSONRPC_VERSION2,
1093
+ id: requestId ?? uuidv4(),
1094
+ method: "droid.update_session_settings" /* UPDATE_SESSION_SETTINGS */,
1095
+ params: {
1096
+ modelId: params.modelId,
1097
+ reasoningEffort: params.reasoningEffort,
1098
+ interactionMode: params.interactionMode,
1099
+ autonomyLevel: params.autonomyLevel,
1100
+ specModeModelId: params.specModeModelId,
1101
+ specModeReasoningEffort: params.specModeReasoningEffort,
1102
+ missionSettings: params.missionSettings,
1103
+ tags: params.tags,
1104
+ compactionTokenLimit: params.compactionTokenLimit,
1105
+ compactionThresholdCheckEnabled: params.compactionThresholdCheckEnabled,
1106
+ disabledToolIds: params.disabledToolIds
1107
+ }
1108
+ };
1109
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1110
+ const responseParsed = UpdateSessionSettingsResponseSchema.safeParse(rawResponse);
1111
+ if (!responseParsed.success) {
1112
+ throw new ProtocolError(
1113
+ "Invalid update session settings response format",
1114
+ {
1115
+ requestId: request.id,
1116
+ code: -32700 /* PARSE_ERROR */,
1117
+ message: responseParsed.error.message,
1118
+ data: rawResponse
1119
+ }
1120
+ );
1121
+ }
1122
+ const response = responseParsed.data;
1123
+ if (response.error) {
1124
+ throw new ProtocolError("Update session settings request failed", {
1125
+ requestId: request.id,
1126
+ code: response.error.code,
1127
+ message: response.error.message,
1128
+ data: response.error.data
1129
+ });
1130
+ }
1131
+ return response;
1132
+ }
1133
+ async changeWorkingDirectory(params) {
1134
+ if (!this.currentSessionId) {
1135
+ throw new SessionError(
1136
+ "No active session. Call initializeSession or loadSession first."
1137
+ );
1138
+ }
1139
+ const request = {
1140
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1141
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1142
+ type: "request",
1143
+ jsonrpc: JSONRPC_VERSION2,
1144
+ id: uuidv4(),
1145
+ method: "droid.change_working_directory" /* CHANGE_WORKING_DIRECTORY */,
1146
+ params
1147
+ };
1148
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1149
+ const response = ChangeWorkingDirectoryResponseSchema.parse(rawResponse);
1150
+ if (response.error) {
1151
+ throw new ProtocolError("Change working directory request failed", {
1152
+ requestId: request.id,
1153
+ code: response.error.code,
1154
+ message: response.error.message,
1155
+ data: response.error.data
1156
+ });
1157
+ }
1158
+ return response;
1159
+ }
1160
+ async toggleMcpServer(params) {
1161
+ if (!this.currentSessionId) {
1162
+ throw new SessionError(
1163
+ "No active session. Call initializeSession or loadSession first."
1164
+ );
1165
+ }
1166
+ const request = {
1167
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1168
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1169
+ type: "request",
1170
+ jsonrpc: JSONRPC_VERSION2,
1171
+ id: uuidv4(),
1172
+ method: "droid.toggle_mcp_server" /* TOGGLE_MCP_SERVER */,
1173
+ params: {
1174
+ serverName: params.serverName,
1175
+ enabled: params.enabled,
1176
+ settingsLevel: params.settingsLevel
1177
+ }
1178
+ };
1179
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1180
+ const response = ToggleMcpServerResponseSchema.parse(rawResponse);
1181
+ return response;
1182
+ }
1183
+ async authenticateMcpServer(params) {
1184
+ if (!this.currentSessionId) {
1185
+ throw new SessionError(
1186
+ "No active session. Call initializeSession or loadSession first."
1187
+ );
1188
+ }
1189
+ const request = {
1190
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1191
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1192
+ type: "request",
1193
+ jsonrpc: JSONRPC_VERSION2,
1194
+ id: uuidv4(),
1195
+ method: "droid.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */,
1196
+ params: {
1197
+ serverName: params.serverName
1198
+ }
1199
+ };
1200
+ const rawResponse = await this.sendRequest(request, MCP_AUTH_TIMEOUT2);
1201
+ const response = AuthenticateMcpServerResponseSchema.parse(rawResponse);
1202
+ return response;
1203
+ }
1204
+ async cancelMcpAuth(params) {
1205
+ if (!this.currentSessionId) {
1206
+ throw new SessionError(
1207
+ "No active session. Call initializeSession or loadSession first."
1208
+ );
1209
+ }
1210
+ const request = {
1211
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1212
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1213
+ type: "request",
1214
+ jsonrpc: JSONRPC_VERSION2,
1215
+ id: uuidv4(),
1216
+ method: "droid.cancel_mcp_auth" /* CANCEL_MCP_AUTH */,
1217
+ params: {
1218
+ serverName: params.serverName
1219
+ }
1220
+ };
1221
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1222
+ const response = CancelMcpAuthResponseSchema.parse(rawResponse);
1223
+ return response;
1224
+ }
1225
+ async clearMcpAuth(params) {
1226
+ if (!this.currentSessionId) {
1227
+ throw new SessionError(
1228
+ "No active session. Call initializeSession or loadSession first."
1229
+ );
1230
+ }
1231
+ const request = {
1232
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1233
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1234
+ type: "request",
1235
+ jsonrpc: JSONRPC_VERSION2,
1236
+ id: uuidv4(),
1237
+ method: "droid.clear_mcp_auth" /* CLEAR_MCP_AUTH */,
1238
+ params: {
1239
+ serverName: params.serverName
1240
+ }
1241
+ };
1242
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1243
+ const response = ClearMcpAuthResponseSchema.parse(rawResponse);
1244
+ return response;
1245
+ }
1246
+ async addMcpServer(params) {
1247
+ if (!this.currentSessionId) {
1248
+ throw new SessionError(
1249
+ "No active session. Call initializeSession or loadSession first."
1250
+ );
1251
+ }
1252
+ if (params.oauth === false) {
1253
+ this.requireMcpOAuthOptOutSupport();
1254
+ }
1255
+ const request = {
1256
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1257
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1258
+ type: "request",
1259
+ jsonrpc: JSONRPC_VERSION2,
1260
+ id: uuidv4(),
1261
+ method: "droid.add_mcp_server" /* ADD_MCP_SERVER */,
1262
+ params
1263
+ };
1264
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1265
+ const response = AddMcpServerResponseSchema.parse(rawResponse);
1266
+ return response;
1267
+ }
1268
+ async removeMcpServer(params) {
1269
+ if (!this.currentSessionId) {
1270
+ throw new SessionError(
1271
+ "No active session. Call initializeSession or loadSession first."
1272
+ );
1273
+ }
1274
+ const request = {
1275
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1276
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1277
+ type: "request",
1278
+ jsonrpc: JSONRPC_VERSION2,
1279
+ id: uuidv4(),
1280
+ method: "droid.remove_mcp_server" /* REMOVE_MCP_SERVER */,
1281
+ params
1282
+ };
1283
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1284
+ const response = RemoveMcpServerResponseSchema.parse(rawResponse);
1285
+ return response;
1286
+ }
1287
+ async listMcpRegistry() {
1288
+ if (!this.currentSessionId) {
1289
+ throw new SessionError(
1290
+ "No active session. Call initializeSession or loadSession first."
1291
+ );
1292
+ }
1293
+ const request = {
1294
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1295
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1296
+ type: "request",
1297
+ jsonrpc: JSONRPC_VERSION2,
1298
+ id: uuidv4(),
1299
+ method: "droid.list_mcp_registry" /* LIST_MCP_REGISTRY */,
1300
+ params: {}
1301
+ };
1302
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1303
+ const response = ListMcpRegistryResponseSchema.parse(rawResponse);
1304
+ return response;
1305
+ }
1306
+ async listMcpTools() {
1307
+ if (!this.currentSessionId) {
1308
+ throw new SessionError(
1309
+ "No active session. Call initializeSession or loadSession first."
1310
+ );
1311
+ }
1312
+ const request = {
1313
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1314
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1315
+ type: "request",
1316
+ jsonrpc: JSONRPC_VERSION2,
1317
+ id: uuidv4(),
1318
+ method: "droid.list_mcp_tools" /* LIST_MCP_TOOLS */,
1319
+ params: {}
1320
+ };
1321
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1322
+ const response = ListMcpToolsResponseSchema.parse(rawResponse);
1323
+ return response;
1324
+ }
1325
+ async listTools(params = {}) {
1326
+ const request = {
1327
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1328
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1329
+ type: "request",
1330
+ jsonrpc: JSONRPC_VERSION2,
1331
+ id: uuidv4(),
1332
+ method: "droid.list_tools" /* LIST_TOOLS */,
1333
+ params
1334
+ };
1335
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1336
+ const response = ListToolsResponseSchema.parse(rawResponse);
1337
+ return response;
1338
+ }
1339
+ async listMcpServers() {
1340
+ if (!this.currentSessionId) {
1341
+ throw new SessionError(
1342
+ "No active session. Call initializeSession or loadSession first."
1343
+ );
1344
+ }
1345
+ const request = {
1346
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1347
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1348
+ type: "request",
1349
+ jsonrpc: JSONRPC_VERSION2,
1350
+ id: uuidv4(),
1351
+ method: "droid.list_mcp_servers" /* LIST_MCP_SERVERS */,
1352
+ params: {}
1353
+ };
1354
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1355
+ const response = ListMcpServersResponseSchema.parse(rawResponse);
1356
+ return response;
1357
+ }
1358
+ async toggleMcpTool(serverName, toolName, enabled) {
1359
+ if (!this.currentSessionId) {
1360
+ throw new SessionError(
1361
+ "No active session. Call initializeSession or loadSession first."
1362
+ );
1363
+ }
1364
+ const request = {
1365
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1366
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1367
+ type: "request",
1368
+ jsonrpc: JSONRPC_VERSION2,
1369
+ id: uuidv4(),
1370
+ method: "droid.toggle_mcp_tool" /* TOGGLE_MCP_TOOL */,
1371
+ params: { serverName, toolName, enabled }
1372
+ };
1373
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1374
+ const response = ToggleMcpToolResponseSchema.parse(rawResponse);
1375
+ return response;
1376
+ }
1377
+ async submitMcpAuthCode(params) {
1378
+ if (!this.currentSessionId) {
1379
+ throw new SessionError(
1380
+ "No active session. Call initializeSession or loadSession first."
1381
+ );
1382
+ }
1383
+ const request = {
1384
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1385
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1386
+ type: "request",
1387
+ jsonrpc: JSONRPC_VERSION2,
1388
+ id: uuidv4(),
1389
+ method: "droid.submit_mcp_auth_code" /* SUBMIT_MCP_AUTH_CODE */,
1390
+ params
1391
+ };
1392
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1393
+ const response = SubmitMcpAuthCodeResponseSchema.parse(rawResponse);
1394
+ return response;
1395
+ }
1396
+ async submitMcpAuthError(params) {
1397
+ if (!this.currentSessionId) {
1398
+ throw new SessionError(
1399
+ "No active session. Call initializeSession or loadSession first."
1400
+ );
1401
+ }
1402
+ const request = {
1403
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1404
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1405
+ type: "request",
1406
+ jsonrpc: JSONRPC_VERSION2,
1407
+ id: uuidv4(),
1408
+ method: "droid.submit_mcp_auth_error" /* SUBMIT_MCP_AUTH_ERROR */,
1409
+ params
1410
+ };
1411
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1412
+ const response = SubmitMcpAuthErrorResponseSchema.parse(rawResponse);
1413
+ return response;
1414
+ }
1415
+ async listSkills() {
1416
+ if (!this.currentSessionId) {
1417
+ throw new SessionError(
1418
+ "No active session. Call initializeSession or loadSession first."
1419
+ );
1420
+ }
1421
+ const request = {
1422
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1423
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1424
+ type: "request",
1425
+ jsonrpc: JSONRPC_VERSION2,
1426
+ id: uuidv4(),
1427
+ method: "droid.list_skills" /* LIST_SKILLS */,
1428
+ params: {}
1429
+ };
1430
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1431
+ const response = ListSkillsResponseSchema.parse(rawResponse);
1432
+ return response;
1433
+ }
1434
+ async setSkillDisabled(skillName, disabled, settingsLevel) {
1435
+ if (!this.currentSessionId) {
1436
+ throw new SessionError(
1437
+ "No active session. Call initializeSession or loadSession first."
1438
+ );
1439
+ }
1440
+ const request = {
1441
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1442
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1443
+ type: "request",
1444
+ jsonrpc: JSONRPC_VERSION2,
1445
+ id: uuidv4(),
1446
+ method: "droid.set_skill_disabled" /* SET_SKILL_DISABLED */,
1447
+ params: { skillName, disabled, settingsLevel }
1448
+ };
1449
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1450
+ return SetSkillDisabledResponseSchema.parse(rawResponse);
1451
+ }
1452
+ async listCommands() {
1453
+ if (!this.currentSessionId) {
1454
+ throw new SessionError(
1455
+ "No active session. Call initializeSession or loadSession first."
1456
+ );
1457
+ }
1458
+ const request = {
1459
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1460
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1461
+ type: "request",
1462
+ jsonrpc: JSONRPC_VERSION2,
1463
+ id: uuidv4(),
1464
+ method: "droid.list_commands" /* LIST_COMMANDS */,
1465
+ params: {}
1466
+ };
1467
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1468
+ const response = ListCommandsResponseSchema.parse(rawResponse);
1469
+ return response;
1470
+ }
1471
+ async getContextStats() {
1472
+ if (!this.currentSessionId) {
1473
+ throw new SessionError(
1474
+ "No active session. Call initializeSession or loadSession first."
1475
+ );
1476
+ }
1477
+ const request = {
1478
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1479
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1480
+ type: "request",
1481
+ jsonrpc: JSONRPC_VERSION2,
1482
+ id: uuidv4(),
1483
+ method: "droid.get_context_stats" /* GET_CONTEXT_STATS */,
1484
+ params: {}
1485
+ };
1486
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1487
+ const response = GetContextStatsResponseSchema.parse(rawResponse);
1488
+ return response;
1489
+ }
1490
+ async getContextBreakdown() {
1491
+ if (!this.currentSessionId) {
1492
+ throw new SessionError(
1493
+ "No active session. Call initializeSession or loadSession first."
1494
+ );
1495
+ }
1496
+ const request = {
1497
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1498
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1499
+ type: "request",
1500
+ jsonrpc: JSONRPC_VERSION2,
1501
+ id: uuidv4(),
1502
+ method: "droid.get_context_breakdown" /* GET_CONTEXT_BREAKDOWN */,
1503
+ params: {}
1504
+ };
1505
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1506
+ const response = GetContextBreakdownResponseSchema.parse(rawResponse);
1507
+ return response;
1508
+ }
1509
+ async submitBugReport(userComment, clientLogs, source) {
1510
+ if (!this.currentSessionId) {
1511
+ throw new SessionError(
1512
+ "No active session. Call initializeSession or loadSession first."
1513
+ );
1514
+ }
1515
+ const request = {
1516
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1517
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1518
+ type: "request",
1519
+ jsonrpc: JSONRPC_VERSION2,
1520
+ id: uuidv4(),
1521
+ method: "droid.submit_bug_report" /* SUBMIT_BUG_REPORT */,
1522
+ params: { userComment, clientLogs, source }
1523
+ };
1524
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1525
+ const response = SubmitBugReportResponseSchema.parse(rawResponse);
1526
+ return response;
1527
+ }
1528
+ async getRewindInfo(params, timeout = this.requestTimeout) {
1529
+ if (!this.currentSessionId) {
1530
+ throw new SessionError(
1531
+ "No active session. Call initializeSession or loadSession first."
1532
+ );
1533
+ }
1534
+ const request = {
1535
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1536
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1537
+ type: "request",
1538
+ jsonrpc: JSONRPC_VERSION2,
1539
+ id: uuidv4(),
1540
+ method: "droid.get_rewind_info" /* GET_REWIND_INFO */,
1541
+ params: {
1542
+ sessionId: this.currentSessionId,
1543
+ messageId: params.messageId
1544
+ }
1545
+ };
1546
+ const rawResponse = await this.sendRequest(request, timeout);
1547
+ return GetRewindInfoResponseSchema.parse(rawResponse);
1548
+ }
1549
+ async executeRewind(params) {
1550
+ if (!this.currentSessionId) {
1551
+ throw new SessionError(
1552
+ "No active session. Call initializeSession or loadSession first."
1553
+ );
1554
+ }
1555
+ const request = {
1556
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1557
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1558
+ type: "request",
1559
+ jsonrpc: JSONRPC_VERSION2,
1560
+ id: uuidv4(),
1561
+ method: "droid.execute_rewind" /* EXECUTE_REWIND */,
1562
+ params: {
1563
+ sessionId: this.currentSessionId,
1564
+ messageId: params.messageId,
1565
+ filesToRestore: params.filesToRestore,
1566
+ filesToDelete: params.filesToDelete,
1567
+ forkTitle: params.forkTitle
1568
+ }
1569
+ };
1570
+ const rawResponse = await this.sendRequest(
1571
+ request,
1572
+ this.requestTimeout * 2
1573
+ );
1574
+ return ExecuteRewindResponseSchema.parse(rawResponse);
1575
+ }
1576
+ async compactSession(params) {
1577
+ if (!this.currentSessionId) {
1578
+ throw new SessionError(
1579
+ "No active session. Call initializeSession or loadSession first."
1580
+ );
1581
+ }
1582
+ const request = {
1583
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1584
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1585
+ type: "request",
1586
+ jsonrpc: JSONRPC_VERSION2,
1587
+ id: uuidv4(),
1588
+ method: "droid.compact_session" /* COMPACT_SESSION */,
1589
+ params: {
1590
+ customInstructions: params.customInstructions
1591
+ }
1592
+ };
1593
+ const rawResponse = await this.sendRequest(request, COMPACTION_TIMEOUT2);
1594
+ return CompactSessionResponseSchema.parse(rawResponse);
1595
+ }
1596
+ async forkSession(params) {
1597
+ if (!this.currentSessionId) {
1598
+ throw new SessionError(
1599
+ "No active session. Call initializeSession or loadSession first."
1600
+ );
1601
+ }
1602
+ const request = {
1603
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1604
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1605
+ type: "request",
1606
+ jsonrpc: JSONRPC_VERSION2,
1607
+ id: uuidv4(),
1608
+ method: "droid.fork_session" /* FORK_SESSION */,
1609
+ params: params ?? {}
1610
+ };
1611
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1612
+ return ForkSessionResponseSchema.parse(rawResponse);
1613
+ }
1614
+ async renameSession(params, requestId) {
1615
+ if (!this.currentSessionId) {
1616
+ throw new SessionError(
1617
+ "No active session. Call initializeSession or loadSession first."
1618
+ );
1619
+ }
1620
+ const request = {
1621
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1622
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1623
+ type: "request",
1624
+ jsonrpc: JSONRPC_VERSION2,
1625
+ id: requestId ?? uuidv4(),
1626
+ method: "droid.rename_session" /* RENAME_SESSION */,
1627
+ params: {
1628
+ title: params.title
1629
+ }
1630
+ };
1631
+ const rawResponse = await this.sendRequest(request, this.requestTimeout);
1632
+ return RenameSessionResponseSchema.parse(rawResponse);
1633
+ }
1634
+ async warmupCache() {
1635
+ const response = {
1636
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1637
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1638
+ type: "response",
1639
+ jsonrpc: JSONRPC_VERSION2,
1640
+ id: uuidv4(),
1641
+ result: {}
1642
+ };
1643
+ return WarmupCacheResponseSchema.parse(response);
1644
+ }
1645
+ onNotification(callback, filter) {
1646
+ const handler = (notification) => {
1647
+ if (filter?.type !== void 0 && filter.type !== notification.params.notification.type) {
1648
+ return;
1649
+ }
1650
+ try {
1651
+ callback(notification);
1652
+ } catch {
1653
+ }
1654
+ };
1655
+ this.on("session_notification" /* SESSION_NOTIFICATION */, handler);
1656
+ return () => this.off("session_notification" /* SESSION_NOTIFICATION */, handler);
1657
+ }
1658
+ onError(callback) {
1659
+ const handler = (error) => {
1660
+ try {
1661
+ callback(error);
1662
+ } catch {
1663
+ }
1664
+ };
1665
+ this.on("error" /* ERROR */, handler);
1666
+ if (this.transportError) {
1667
+ handler(this.transportError);
1668
+ }
1669
+ return () => this.off("error" /* ERROR */, handler);
1670
+ }
1671
+ setPermissionHandler(handler) {
1672
+ this.permissionHandlers.set(
1673
+ "default",
1674
+ async (event) => await handler(event)
1675
+ );
1676
+ }
1677
+ clearPermissionHandler() {
1678
+ this.permissionHandlers.delete("default");
1679
+ }
1680
+ setAskUserHandler(handler) {
1681
+ this.askUserHandlers.set("default", async (event) => await handler(event));
1682
+ }
1683
+ clearAskUserHandler() {
1684
+ this.askUserHandlers.delete("default");
1685
+ }
1686
+ async close() {
1687
+ const closeError = new ConnectionError(
1688
+ "Droid client closed: pending requests cancelled"
1689
+ );
1690
+ this.rejectAllPending(closeError);
1691
+ this.permissionHandlers.clear();
1692
+ this.askUserHandlers.clear();
1693
+ this.removeAllListeners();
1694
+ await this.transport.close();
1695
+ }
1696
+ rejectAllPending(error) {
1697
+ this.pendingRequests.forEach(({ timeoutId, reject }, requestId) => {
1698
+ if (timeoutId) {
1699
+ clearTimeout(timeoutId);
1700
+ }
1701
+ reject(error);
1702
+ this.notifyRequestSettled(requestId);
1703
+ });
1704
+ this.pendingRequests.clear();
1705
+ this.pendingPermissionRequests.forEach(({ reject }) => {
1706
+ reject(error);
1707
+ });
1708
+ this.pendingPermissionRequests.clear();
1709
+ this.pendingAskUserRequests.forEach(({ reject }) => {
1710
+ reject(error);
1711
+ });
1712
+ this.pendingAskUserRequests.clear();
1713
+ }
1714
+ settleRequest(requestId) {
1715
+ this.pendingRequests.delete(requestId);
1716
+ this.notifyRequestSettled(requestId);
1717
+ }
1718
+ notifyRequestSettled(requestId) {
1719
+ try {
1720
+ this.onRequestSettled?.(requestId);
1721
+ } catch {
1722
+ }
1723
+ }
1724
+ async sendRequest(request, timeout) {
1725
+ if (this.transportError) {
1726
+ throw this.transportError;
1727
+ }
1728
+ const responsePromise = new Promise(
1729
+ (resolve2, reject) => {
1730
+ const timeoutId = timeout ? setTimeout(() => {
1731
+ this.settleRequest(request.id);
1732
+ reject(
1733
+ new TimeoutError("Send request timed out", {
1734
+ requestId: request.id,
1735
+ method: request.method,
1736
+ timeout
1737
+ })
1738
+ );
1739
+ }, timeout) : void 0;
1740
+ this.pendingRequests.set(request.id, {
1741
+ method: request.method,
1742
+ resolve: resolve2,
1743
+ reject,
1744
+ timeoutId
1745
+ });
1746
+ }
1747
+ );
1748
+ const _meta = {};
1749
+ this.tracing.injectContext(_meta, this.tracing.getCurrentContext());
1750
+ const requestWithMeta = _meta.traceparent ? { ...request, _meta } : request;
1751
+ try {
1752
+ this.logger.info("[DroidClient] [daemon -> droid] sending request", {
1753
+ requestId: request.id,
1754
+ method: request.method
1755
+ });
1756
+ await this.transport.send(JSON.stringify(requestWithMeta));
1757
+ } catch (error) {
1758
+ const pending = this.pendingRequests.get(request.id);
1759
+ if (pending) {
1760
+ if (pending.timeoutId) {
1761
+ clearTimeout(pending.timeoutId);
1762
+ }
1763
+ this.settleRequest(request.id);
1764
+ pending.reject(
1765
+ new ProtocolError("[daemon -> droid] Failed to send request", {
1766
+ requestId: request.id,
1767
+ cause: error
1768
+ })
1769
+ );
1770
+ }
1771
+ }
1772
+ return responsePromise;
1773
+ }
1774
+ async handleMessage(message) {
1775
+ try {
1776
+ const parsed = JSON.parse(message);
1777
+ if ("result" in parsed || "error" in parsed) {
1778
+ this.handleResponse(parsed);
1779
+ } else if ("method" in parsed) {
1780
+ await this.handleEvent(parsed);
1781
+ } else {
1782
+ throw new ProtocolError("Invalid message format", {
1783
+ message
1784
+ });
1785
+ }
1786
+ } catch {
1787
+ this.logger.warn("[DroidClient] Failed to handle message", {
1788
+ messageByteLength: new TextEncoder().encode(message).byteLength
1789
+ });
1790
+ }
1791
+ }
1792
+ handleResponse(response) {
1793
+ try {
1794
+ const responseId = getResponseId(response);
1795
+ if (responseId !== null && responseId !== void 0) {
1796
+ const pending = this.pendingRequests.get(responseId);
1797
+ if (pending) {
1798
+ let validatedResponse;
1799
+ switch (pending.method) {
1800
+ case "droid.initialize_session" /* INITIALIZE_SESSION */:
1801
+ validatedResponse = InitializeSessionResponseSchema.parse(response);
1802
+ break;
1803
+ case "droid.load_session" /* LOAD_SESSION */:
1804
+ validatedResponse = LoadSessionResponseSchema.parse(response);
1805
+ break;
1806
+ case "droid.add_user_message" /* ADD_USER_MESSAGE */:
1807
+ validatedResponse = AddUserMessageResponseSchema.parse(response);
1808
+ break;
1809
+ case "droid.resolve_queued_user_message" /* RESOLVE_QUEUED_USER_MESSAGE */:
1810
+ validatedResponse = ResolveQueuedUserMessageResponseSchema.parse(response);
1811
+ break;
1812
+ case "droid.interrupt_session" /* INTERRUPT_SESSION */:
1813
+ validatedResponse = InterruptSessionResponseSchema.parse(response);
1814
+ break;
1815
+ case "droid.close_session" /* CLOSE_SESSION */:
1816
+ validatedResponse = CloseSessionResponseSchema.parse(response);
1817
+ break;
1818
+ case "droid.update_session_settings" /* UPDATE_SESSION_SETTINGS */:
1819
+ validatedResponse = UpdateSessionSettingsResponseSchema.parse(response);
1820
+ break;
1821
+ case "droid.change_working_directory" /* CHANGE_WORKING_DIRECTORY */:
1822
+ validatedResponse = ChangeWorkingDirectoryResponseSchema.parse(response);
1823
+ break;
1824
+ case "droid.toggle_mcp_server" /* TOGGLE_MCP_SERVER */:
1825
+ validatedResponse = ToggleMcpServerResponseSchema.parse(response);
1826
+ break;
1827
+ case "droid.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */:
1828
+ validatedResponse = AuthenticateMcpServerResponseSchema.parse(response);
1829
+ break;
1830
+ case "droid.cancel_mcp_auth" /* CANCEL_MCP_AUTH */:
1831
+ validatedResponse = CancelMcpAuthResponseSchema.parse(response);
1832
+ break;
1833
+ case "droid.clear_mcp_auth" /* CLEAR_MCP_AUTH */:
1834
+ validatedResponse = ClearMcpAuthResponseSchema.parse(response);
1835
+ break;
1836
+ case "droid.add_mcp_server" /* ADD_MCP_SERVER */:
1837
+ validatedResponse = AddMcpServerResponseSchema.parse(response);
1838
+ break;
1839
+ case "droid.remove_mcp_server" /* REMOVE_MCP_SERVER */:
1840
+ validatedResponse = RemoveMcpServerResponseSchema.parse(response);
1841
+ break;
1842
+ case "droid.list_mcp_registry" /* LIST_MCP_REGISTRY */:
1843
+ validatedResponse = ListMcpRegistryResponseSchema.parse(response);
1844
+ break;
1845
+ case "droid.list_mcp_tools" /* LIST_MCP_TOOLS */:
1846
+ validatedResponse = ListMcpToolsResponseSchema.parse(response);
1847
+ break;
1848
+ case "droid.list_tools" /* LIST_TOOLS */:
1849
+ validatedResponse = ListToolsResponseSchema.parse(response);
1850
+ break;
1851
+ case "droid.toggle_mcp_tool" /* TOGGLE_MCP_TOOL */:
1852
+ validatedResponse = ToggleMcpToolResponseSchema.parse(response);
1853
+ break;
1854
+ case "droid.submit_mcp_auth_code" /* SUBMIT_MCP_AUTH_CODE */:
1855
+ validatedResponse = SubmitMcpAuthCodeResponseSchema.parse(response);
1856
+ break;
1857
+ case "droid.submit_mcp_auth_error" /* SUBMIT_MCP_AUTH_ERROR */:
1858
+ validatedResponse = SubmitMcpAuthErrorResponseSchema.parse(response);
1859
+ break;
1860
+ case "droid.kill_worker_session" /* KILL_WORKER_SESSION */:
1861
+ validatedResponse = KillWorkerSessionResponseSchema.parse(response);
1862
+ break;
1863
+ case "droid.list_skills" /* LIST_SKILLS */:
1864
+ validatedResponse = ListSkillsResponseSchema.parse(response);
1865
+ break;
1866
+ case "droid.set_skill_disabled" /* SET_SKILL_DISABLED */:
1867
+ validatedResponse = SetSkillDisabledResponseSchema.parse(response);
1868
+ break;
1869
+ case "droid.list_commands" /* LIST_COMMANDS */:
1870
+ validatedResponse = ListCommandsResponseSchema.parse(response);
1871
+ break;
1872
+ case "droid.submit_bug_report" /* SUBMIT_BUG_REPORT */:
1873
+ validatedResponse = SubmitBugReportResponseSchema.parse(response);
1874
+ break;
1875
+ case "droid.list_mcp_servers" /* LIST_MCP_SERVERS */:
1876
+ validatedResponse = ListMcpServersResponseSchema.parse(response);
1877
+ break;
1878
+ case "droid.get_rewind_info" /* GET_REWIND_INFO */:
1879
+ validatedResponse = GetRewindInfoResponseSchema.parse(response);
1880
+ break;
1881
+ case "droid.execute_rewind" /* EXECUTE_REWIND */:
1882
+ validatedResponse = ExecuteRewindResponseSchema.parse(response);
1883
+ break;
1884
+ case "droid.compact_session" /* COMPACT_SESSION */:
1885
+ validatedResponse = CompactSessionResponseSchema.parse(response);
1886
+ break;
1887
+ case "droid.fork_session" /* FORK_SESSION */:
1888
+ validatedResponse = ForkSessionResponseSchema.parse(response);
1889
+ break;
1890
+ case "droid.rename_session" /* RENAME_SESSION */:
1891
+ validatedResponse = RenameSessionResponseSchema.parse(response);
1892
+ break;
1893
+ case "droid.get_context_stats" /* GET_CONTEXT_STATS */:
1894
+ validatedResponse = GetContextStatsResponseSchema.parse(response);
1895
+ break;
1896
+ case "droid.get_context_breakdown" /* GET_CONTEXT_BREAKDOWN */:
1897
+ validatedResponse = GetContextBreakdownResponseSchema.parse(response);
1898
+ break;
1899
+ case "droid.warmup_cache" /* WARMUP_CACHE */:
1900
+ validatedResponse = WarmupCacheResponseSchema.parse(response);
1901
+ break;
1902
+ default: {
1903
+ const exhaustiveCheck = pending.method;
1904
+ throw new DroidClientError(
1905
+ "Unsupported method in response handler",
1906
+ {
1907
+ method: exhaustiveCheck
1908
+ }
1909
+ );
1910
+ }
1911
+ }
1912
+ if (pending.timeoutId) {
1913
+ clearTimeout(pending.timeoutId);
1914
+ }
1915
+ this.settleRequest(responseId);
1916
+ pending.resolve(validatedResponse);
1917
+ } else {
1918
+ const validatedResponse = JsonRpcBaseResponseSchema.parse(response);
1919
+ this.logger.info(
1920
+ "[DroidClient] Received response for request not in pending map",
1921
+ {
1922
+ requestId: validatedResponse.id ?? void 0
1923
+ }
1924
+ );
1925
+ }
1926
+ }
1927
+ } catch (error) {
1928
+ const responseId = getResponseId(response);
1929
+ const pending = responseId !== null && responseId !== void 0 ? this.pendingRequests.get(responseId) : void 0;
1930
+ const zodIssues = error instanceof z.ZodError ? error.issues.map((issue) => ({
1931
+ path: issue.path,
1932
+ code: issue.code,
1933
+ message: issue.message
1934
+ })) : void 0;
1935
+ this.logger.exception(error, "Invalid response format", {
1936
+ method: pending?.method,
1937
+ requestId: responseId ?? void 0,
1938
+ zodIssues
1939
+ });
1940
+ const err = error instanceof Error ? error : new Error(String(error));
1941
+ const code = error instanceof z.ZodError ? -32700 /* PARSE_ERROR */ : -32603 /* INTERNAL_ERROR */;
1942
+ const message = code === -32700 /* PARSE_ERROR */ ? "Invalid response format" : "Internal error while handling response";
1943
+ if (responseId === null || responseId === void 0) {
1944
+ return;
1945
+ }
1946
+ if (!pending) {
1947
+ this.logger.info(
1948
+ "[DroidClient] Dropping unhandleable response with no pending request",
1949
+ {
1950
+ requestId: responseId,
1951
+ code,
1952
+ message: err.message
1953
+ }
1954
+ );
1955
+ return;
1956
+ }
1957
+ if (pending.timeoutId) {
1958
+ clearTimeout(pending.timeoutId);
1959
+ }
1960
+ this.settleRequest(responseId);
1961
+ const syntheticFailure = {
1962
+ jsonrpc: JSONRPC_VERSION2,
1963
+ type: "response",
1964
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
1965
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
1966
+ id: responseId,
1967
+ error: {
1968
+ code,
1969
+ message,
1970
+ data: err.message
1971
+ }
1972
+ };
1973
+ pending.resolve(syntheticFailure);
1974
+ }
1975
+ }
1976
+ async handleEvent(event) {
1977
+ try {
1978
+ const validatedEvent = CliRequestOrNotificationSchema.parse(event);
1979
+ if (validatedEvent.method === "droid.session_notification" /* SESSION_NOTIFICATION */) {
1980
+ this.emit("session_notification" /* SESSION_NOTIFICATION */, validatedEvent);
1981
+ } else if (validatedEvent.method === "droid.request_permission" /* REQUEST_PERMISSION */) {
1982
+ await this.handlePermissionRequest(validatedEvent);
1983
+ } else if (validatedEvent.method === "droid.ask_user" /* ASK_USER */) {
1984
+ await this.handleAskUserRequest(validatedEvent);
1985
+ }
1986
+ } catch (error) {
1987
+ this.logDroppedEventParseError(error, event);
1988
+ await this.replyWithParseFailureIfRequest(error, event);
1989
+ }
1990
+ }
1991
+ /**
1992
+ * When an incoming CLI->client request fails to parse, send back a
1993
+ * structurally valid JsonRpcBaseResponseFailure so the peer's pending
1994
+ * request doesn't hang. No-ops for notifications (no id to reply on)
1995
+ * or events we can't correlate.
1996
+ */
1997
+ async replyWithParseFailureIfRequest(error, event) {
1998
+ const type = _DroidClient.getNestedString(event, ["type"]);
1999
+ const id = _DroidClient.getNestedString(event, ["id"]);
2000
+ if (type !== "request" || !id) {
2001
+ return;
2002
+ }
2003
+ const err = error instanceof Error ? error : new Error(String(error));
2004
+ const code = error instanceof z.ZodError ? -32600 /* INVALID_REQUEST */ : -32603 /* INTERNAL_ERROR */;
2005
+ const message = code === -32600 /* INVALID_REQUEST */ ? "Invalid request format" : "Internal error while handling request";
2006
+ const errorResponse = {
2007
+ jsonrpc: JSONRPC_VERSION2,
2008
+ type: "response",
2009
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2010
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2011
+ id,
2012
+ error: {
2013
+ code,
2014
+ message,
2015
+ data: err.message
2016
+ }
2017
+ };
2018
+ try {
2019
+ await this.transport.send(JSON.stringify(errorResponse));
2020
+ } catch (sendError) {
2021
+ this.logger.exception(
2022
+ sendError,
2023
+ "Failed to send parse-failure response back to peer"
2024
+ );
2025
+ }
2026
+ }
2027
+ /**
2028
+ * Invariant: parsing failures for incoming events (notifications or
2029
+ * server-initiated requests) must NEVER surface as user-visible ERROR
2030
+ * notifications. Version skew, unknown inner enum values, missing
2031
+ * fields, or malformed shapes all degrade to a log-and-drop so the
2032
+ * session continues quietly instead of flashing a synthetic error on
2033
+ * every
2034
+ */
2035
+ logDroppedEventParseError(error, event) {
2036
+ const { protocolVersionMismatch } = inspectJsonRpcEnvelope2(event);
2037
+ const method = _DroidClient.getNestedString(event, ["method"]);
2038
+ const notificationType = _DroidClient.getNestedString(event, [
2039
+ "params",
2040
+ "notification",
2041
+ "type"
2042
+ ]);
2043
+ const sessionId = this.currentSessionId ?? _DroidClient.getNestedString(event, ["params", "sessionId"]);
2044
+ const meta = {
2045
+ value: {
2046
+ method: method ?? void 0,
2047
+ notificationType: notificationType ?? void 0,
2048
+ protocolVersionMismatch: protocolVersionMismatch ?? void 0,
2049
+ sessionId: sessionId ?? void 0
2050
+ }
2051
+ };
2052
+ if (protocolVersionMismatch) {
2053
+ this.logger.info(
2054
+ "[DroidClient] Dropping unsupported event from newer peer",
2055
+ meta
2056
+ );
2057
+ } else {
2058
+ this.logger.warn("[DroidClient] Dropping malformed event", {
2059
+ ...meta,
2060
+ cause: error
2061
+ });
2062
+ }
2063
+ }
2064
+ async handlePermissionRequest(event) {
2065
+ if (this.pendingPermissionRequests.has(event.id)) {
2066
+ this.logger.info(
2067
+ "[DroidClient] Ignoring duplicate pending permission request",
2068
+ {
2069
+ requestId: event.id
2070
+ }
2071
+ );
2072
+ return;
2073
+ }
2074
+ this.logger.info("[DroidClient] Handling permission request", {
2075
+ requestId: event.id,
2076
+ toolCount: event.params.toolUses.length
2077
+ });
2078
+ this.emit("request_permission" /* REQUEST_PERMISSION */, event);
2079
+ let selectedOption = "cancel" /* Cancel */;
2080
+ let comment;
2081
+ let editedSpecContent;
2082
+ const handler = this.permissionHandlers.get("default");
2083
+ if (handler) {
2084
+ try {
2085
+ this.logger.info(
2086
+ "[DroidClient] Waiting for permission handler to resolve",
2087
+ {
2088
+ requestId: event.id
2089
+ }
2090
+ );
2091
+ const handlerPromise = new Promise(
2092
+ (resolve2, reject) => {
2093
+ this.pendingPermissionRequests.set(event.id, { reject });
2094
+ handler(event).then(resolve2).catch(reject).finally(() => {
2095
+ this.pendingPermissionRequests.delete(event.id);
2096
+ });
2097
+ }
2098
+ );
2099
+ const handlerResult = await handlerPromise;
2100
+ if (typeof handlerResult === "string" && handlerResult === "proceed_edit" /* ProceedEdit */) {
2101
+ throw new DroidClientError(
2102
+ "Permission handler returned proceed_edit without editedSpecContent"
2103
+ );
2104
+ }
2105
+ const parsedHandlerResult = RequestPermissionResultSchema.safeParse(
2106
+ typeof handlerResult === "string" ? { selectedOption: handlerResult } : handlerResult
2107
+ );
2108
+ if (parsedHandlerResult.success) {
2109
+ selectedOption = parsedHandlerResult.data.selectedOption;
2110
+ comment = parsedHandlerResult.data.comment;
2111
+ editedSpecContent = parsedHandlerResult.data.editedSpecContent;
2112
+ } else {
2113
+ throw new DroidClientError(
2114
+ "Permission handler returned invalid result",
2115
+ {
2116
+ cause: parsedHandlerResult.error
2117
+ }
2118
+ );
2119
+ }
2120
+ if (!event.params.options.some(
2121
+ (option) => option.value === selectedOption
2122
+ )) {
2123
+ throw new DroidClientError(
2124
+ `Permission handler selected unavailable option: ${selectedOption}`
2125
+ );
2126
+ }
2127
+ this.logger.info("[DroidClient] Permission handler resolved", {
2128
+ requestId: event.id,
2129
+ result: selectedOption
2130
+ });
2131
+ } catch (error) {
2132
+ this.logger.exception(
2133
+ error,
2134
+ "Failed to handle permission request (processing)"
2135
+ );
2136
+ const err = error instanceof Error ? error : new Error(String(error));
2137
+ this.emit(
2138
+ "session_notification" /* SESSION_NOTIFICATION */,
2139
+ _DroidClient.createNotificationEvent(
2140
+ _DroidClient.createErrorNotification(err)
2141
+ )
2142
+ );
2143
+ this.pendingPermissionRequests.delete(event.id);
2144
+ const cancelResponse = {
2145
+ type: "response",
2146
+ jsonrpc: JSONRPC_VERSION2,
2147
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2148
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2149
+ id: event.id,
2150
+ result: {
2151
+ selectedOption: "cancel" /* Cancel */
2152
+ }
2153
+ };
2154
+ try {
2155
+ await this.transport.send(JSON.stringify(cancelResponse));
2156
+ } catch (sendError) {
2157
+ this.logger.exception(
2158
+ sendError,
2159
+ "Failed to handle permission request (send cancellation)"
2160
+ );
2161
+ const sendErr = sendError instanceof Error ? sendError : new Error(String(sendError));
2162
+ this.emit(
2163
+ "session_notification" /* SESSION_NOTIFICATION */,
2164
+ _DroidClient.createNotificationEvent(
2165
+ _DroidClient.createErrorNotification(sendErr)
2166
+ )
2167
+ );
2168
+ }
2169
+ return;
2170
+ }
2171
+ }
2172
+ const response = {
2173
+ type: "response",
2174
+ jsonrpc: JSONRPC_VERSION2,
2175
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2176
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2177
+ id: event.id,
2178
+ result: {
2179
+ selectedOption,
2180
+ ...comment !== void 0 && { comment },
2181
+ ...editedSpecContent !== void 0 && { editedSpecContent }
2182
+ }
2183
+ };
2184
+ this.logger.info("[DroidClient] Sending permission response back to CLI", {
2185
+ requestId: event.id,
2186
+ result: String(selectedOption)
2187
+ });
2188
+ await this.transport.send(JSON.stringify(response));
2189
+ }
2190
+ async handleAskUserRequest(event) {
2191
+ this.logger.info("[DroidClient] Handling ask-user request", {
2192
+ requestId: event.id,
2193
+ toolCallId: event.params.toolCallId,
2194
+ questionCount: event.params.questions.length
2195
+ });
2196
+ this.emit("ask_user" /* ASK_USER */, event);
2197
+ let result = { cancelled: true, answers: [] };
2198
+ const handler = this.askUserHandlers.get("default");
2199
+ if (handler) {
2200
+ try {
2201
+ this.logger.info(
2202
+ "[DroidClient] Waiting for ask-user handler to resolve",
2203
+ {
2204
+ requestId: event.id
2205
+ }
2206
+ );
2207
+ const handlerPromise = new Promise((resolve2, reject) => {
2208
+ this.pendingAskUserRequests.set(event.id, { reject });
2209
+ handler(event).then(resolve2).catch(reject).finally(() => {
2210
+ this.pendingAskUserRequests.delete(event.id);
2211
+ });
2212
+ });
2213
+ const parsedResult = AskUserResultSchema.safeParse(
2214
+ await handlerPromise
2215
+ );
2216
+ if (!parsedResult.success) {
2217
+ throw new DroidClientError(
2218
+ "AskUser handler returned invalid result",
2219
+ {
2220
+ cause: parsedResult.error
2221
+ }
2222
+ );
2223
+ }
2224
+ result = parsedResult.data;
2225
+ this.logger.info("[DroidClient] Ask-user handler resolved", {
2226
+ requestId: event.id,
2227
+ cancelled: result.cancelled ?? false,
2228
+ answerCount: result.answers.length
2229
+ });
2230
+ } catch (error) {
2231
+ this.logger.exception(error, "Failed to handle ask-user request");
2232
+ const err = error instanceof Error ? error : new Error(String(error));
2233
+ this.emit(
2234
+ "session_notification" /* SESSION_NOTIFICATION */,
2235
+ _DroidClient.createNotificationEvent(
2236
+ _DroidClient.createErrorNotification(err)
2237
+ )
2238
+ );
2239
+ this.pendingAskUserRequests.delete(event.id);
2240
+ const cancelResponse = {
2241
+ jsonrpc: JSONRPC_VERSION2,
2242
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2243
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2244
+ type: "response",
2245
+ id: event.id,
2246
+ result: {
2247
+ cancelled: true,
2248
+ answers: []
2249
+ }
2250
+ };
2251
+ try {
2252
+ await this.transport.send(JSON.stringify(cancelResponse));
2253
+ } catch (sendError) {
2254
+ this.logger.exception(
2255
+ sendError,
2256
+ "Failed to send ask-user cancellation"
2257
+ );
2258
+ }
2259
+ return;
2260
+ }
2261
+ }
2262
+ const response = {
2263
+ type: "response",
2264
+ jsonrpc: JSONRPC_VERSION2,
2265
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2266
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2267
+ id: event.id,
2268
+ result
2269
+ };
2270
+ this.logger.info("[DroidClient] Sending ask-user response back to CLI", {
2271
+ requestId: event.id,
2272
+ cancelled: result.cancelled ?? false
2273
+ });
2274
+ await this.transport.send(JSON.stringify(response));
2275
+ }
2276
+ static getErrorType(error) {
2277
+ switch (error.constructor) {
2278
+ case ConnectionError:
2279
+ return "ConnectionError" /* CONNECTION_ERROR */;
2280
+ case ProtocolError:
2281
+ return "ProtocolError" /* PROTOCOL_ERROR */;
2282
+ case SessionError:
2283
+ return "SessionError" /* SESSION_ERROR */;
2284
+ case TimeoutError:
2285
+ return "TimeoutError" /* TIMEOUT_ERROR */;
2286
+ case ProcessExitError:
2287
+ return "ProcessExitError" /* PROCESS_EXIT_ERROR */;
2288
+ case DroidClientError:
2289
+ return "DroidClientError" /* DROID_CLIENT_ERROR */;
2290
+ default:
2291
+ return "Error" /* ERROR */;
2292
+ }
2293
+ }
2294
+ static createErrorNotification(error) {
2295
+ return {
2296
+ type: "error" /* ERROR */,
2297
+ message: error.message,
2298
+ errorType: _DroidClient.getErrorType(error),
2299
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2300
+ error: {
2301
+ name: error.name,
2302
+ message: error.message
2303
+ }
2304
+ };
2305
+ }
2306
+ static getNestedString(value, path3) {
2307
+ let current = value;
2308
+ for (const key of path3) {
2309
+ if (!_DroidClient.isRecord(current)) {
2310
+ return null;
2311
+ }
2312
+ current = current[key];
2313
+ }
2314
+ return typeof current === "string" ? current : null;
2315
+ }
2316
+ static isRecord(value) {
2317
+ return typeof value === "object" && value !== null;
2318
+ }
2319
+ /**
2320
+ * Create a full SessionNotificationEvent for locally-generated notifications.
2321
+ * Used when the SDK needs to emit error notifications that weren't received from the CLI.
2322
+ */
2323
+ static createNotificationEvent(notification) {
2324
+ return {
2325
+ jsonrpc: JSONRPC_VERSION2,
2326
+ type: "notification",
2327
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2328
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2329
+ method: "droid.session_notification" /* SESSION_NOTIFICATION */,
2330
+ params: { notification }
2331
+ };
2332
+ }
2333
+ };
2334
+
2335
+ // src/exec-core/managed-process.ts
2336
+ import fs2 from "fs";
2337
+ import * as readline from "readline";
2338
+
2339
+ // src/exec-core/runtime-utils.ts
2340
+ import { homedir } from "os";
2341
+ import { join } from "path";
2342
+ function isErrnoException(error) {
2343
+ return error !== null && typeof error === "object" && "code" in error && typeof error.code === "string";
2344
+ }
2345
+ function expandTilde(filepath) {
2346
+ if (!filepath) {
2347
+ return filepath;
2348
+ }
2349
+ if (filepath === "~") {
2350
+ return homedir();
2351
+ }
2352
+ if (filepath.startsWith("~/") || filepath.startsWith("~\\")) {
2353
+ return join(homedir(), filepath.slice(2));
2354
+ }
2355
+ return filepath;
2356
+ }
2357
+
2358
+ // src/exec-core/transport-logger.ts
2359
+ import fs from "fs";
2360
+ import path from "path";
2361
+ var LOG_FILE_NAME = "droid-transport.log";
2362
+ var LOG_DIR_MODE = 448;
2363
+ var LOG_FILE_MODE = 384;
2364
+ var state = null;
2365
+ var enabledCache = null;
2366
+ var HOST_PID_TAG = `host_pid=${process.pid}`;
2367
+ function isTruthy(value) {
2368
+ const v = value.trim().toLowerCase();
2369
+ return v !== "" && v !== "0" && v !== "false" && v !== "off" && v !== "no";
2370
+ }
2371
+ function directionMarker(direction) {
2372
+ switch (direction) {
2373
+ case "in" /* In */:
2374
+ return "IN ";
2375
+ case "out" /* Out */:
2376
+ return "OUT";
2377
+ case "out_failed" /* OutFailed */:
2378
+ return "OUT!";
2379
+ default:
2380
+ return "???";
2381
+ }
2382
+ }
2383
+ function isTransportLoggingEnabled(deps = defaultExecCoreDeps) {
2384
+ if (enabledCache !== null) return enabledCache;
2385
+ enabledCache = isTruthy(
2386
+ deps.environmentResolver.resolveTransportLogEnvValue() ?? ""
2387
+ );
2388
+ return enabledCache;
2389
+ }
2390
+ function looksLikePath(value) {
2391
+ return path.isAbsolute(value) || value.startsWith("~") || value.startsWith("./") || value.startsWith("../") || value.startsWith(".\\") || value.startsWith("..\\") || value.includes("/") || value.includes("\\");
2392
+ }
2393
+ function resolveLogPath(deps) {
2394
+ const envValue = deps.environmentResolver.resolveTransportLogEnvValue();
2395
+ const pathResolver = deps.factoryPathResolver;
2396
+ if (envValue && looksLikePath(envValue)) {
2397
+ if (envValue === "~" || envValue.startsWith("~/") || envValue.startsWith("~\\")) {
2398
+ const rest = envValue.slice(2);
2399
+ const home = pathResolver.getFactoryHome();
2400
+ return rest ? path.join(home, rest) : home;
2401
+ }
2402
+ return envValue;
2403
+ }
2404
+ return path.join(
2405
+ pathResolver.getFactoryHome(),
2406
+ pathResolver.getFactoryDirName(),
2407
+ "logs",
2408
+ LOG_FILE_NAME
2409
+ );
2410
+ }
2411
+ function initState(deps) {
2412
+ const result = { stream: null, failed: false };
2413
+ try {
2414
+ const logPath = resolveLogPath(deps);
2415
+ const logsDir = path.dirname(logPath);
2416
+ const logsDirExisted = fs.existsSync(logsDir);
2417
+ if (!logsDirExisted) {
2418
+ fs.mkdirSync(logsDir, { recursive: true, mode: LOG_DIR_MODE });
2419
+ }
2420
+ if (process.platform !== "win32" && !logsDirExisted) {
2421
+ try {
2422
+ fs.chmodSync(logsDir, LOG_DIR_MODE);
2423
+ } catch (chmodError) {
2424
+ logWarn(
2425
+ deps.logger,
2426
+ "[droid-sdk transport-logger] failed to chmod logs dir",
2427
+ {
2428
+ cause: chmodError
2429
+ }
2430
+ );
2431
+ }
2432
+ }
2433
+ const stream = fs.createWriteStream(logPath, {
2434
+ flags: "a",
2435
+ encoding: "utf8",
2436
+ mode: LOG_FILE_MODE
2437
+ });
2438
+ if (process.platform !== "win32") {
2439
+ try {
2440
+ fs.chmodSync(logPath, LOG_FILE_MODE);
2441
+ } catch (chmodError) {
2442
+ logWarn(
2443
+ deps.logger,
2444
+ "[droid-sdk transport-logger] failed to chmod log file",
2445
+ {
2446
+ cause: chmodError
2447
+ }
2448
+ );
2449
+ }
2450
+ }
2451
+ stream.on("error", (streamError) => {
2452
+ deps.logger.warn("[droid-sdk transport-logger] write stream error", {
2453
+ cause: streamError
2454
+ });
2455
+ result.stream = null;
2456
+ result.failed = true;
2457
+ });
2458
+ result.stream = stream;
2459
+ } catch (initError) {
2460
+ logWarn(
2461
+ deps.logger,
2462
+ "[droid-sdk transport-logger] failed to open log file",
2463
+ {
2464
+ cause: initError
2465
+ }
2466
+ );
2467
+ result.failed = true;
2468
+ }
2469
+ return result;
2470
+ }
2471
+ function getState(deps) {
2472
+ if (!isTransportLoggingEnabled(deps)) return null;
2473
+ if (state === null) {
2474
+ state = initState(deps);
2475
+ }
2476
+ if (state.failed) return null;
2477
+ return state;
2478
+ }
2479
+ function logTransportMessage(direction, message, childPid, deps = defaultExecCoreDeps) {
2480
+ const s = getState(deps);
2481
+ if (!s || !s.stream) return;
2482
+ try {
2483
+ const marker = directionMarker(direction);
2484
+ const childTag = `[child_pid=${childPid ?? "-"}]`;
2485
+ s.stream.write(
2486
+ `[${(/* @__PURE__ */ new Date()).toISOString()}] [${HOST_PID_TAG}] ${childTag} ${marker} ${message}
2487
+ `
2488
+ );
2489
+ } catch (writeError) {
2490
+ logWarn(
2491
+ deps.logger,
2492
+ "[droid-sdk transport-logger] write failed, disabling",
2493
+ {
2494
+ cause: writeError
2495
+ }
2496
+ );
2497
+ s.failed = true;
2498
+ s.stream = null;
2499
+ }
2500
+ }
2501
+ async function __resetTransportLoggerForTests(deps = defaultExecCoreDeps) {
2502
+ const stream = state?.stream ?? null;
2503
+ state = null;
2504
+ enabledCache = null;
2505
+ if (!stream) return;
2506
+ await new Promise((resolve2) => {
2507
+ stream.once("finish", () => resolve2());
2508
+ stream.once("error", () => resolve2());
2509
+ try {
2510
+ stream.end();
2511
+ } catch (endError) {
2512
+ logWarn(
2513
+ deps.logger,
2514
+ "[droid-sdk transport-logger] failed to end stream on reset",
2515
+ {
2516
+ cause: endError
2517
+ }
2518
+ );
2519
+ resolve2();
2520
+ }
2521
+ });
2522
+ }
2523
+
2524
+ // src/exec-core/managed-process.ts
2525
+ var MAX_NON_JSON_LOG_LENGTH = 200;
2526
+ var EXIT_STDIO_DRAIN_TIMEOUT_MS = 2e3;
2527
+ var GRACEFUL_EXIT_TIMEOUT_MS = 2e3;
2528
+ var FORCED_EXIT_TIMEOUT_MS = 3e3;
2529
+ function describeSpawnError(error, context) {
2530
+ if (!isErrnoException(error)) {
2531
+ return `Failed to start Droid: ${error.message}`;
2532
+ }
2533
+ if (error.code === "ENOENT") {
2534
+ if (context?.cwd && !fs2.existsSync(context.cwd)) {
2535
+ return `Failed to start Droid: working directory does not exist (${context.cwd})`;
2536
+ }
2537
+ return `Failed to start Droid: executable not found${context?.execPath ? ` (${context.execPath})` : ""}`;
2538
+ }
2539
+ if (error.code === "EACCES") {
2540
+ return `Failed to start Droid: permission denied${context?.execPath ? ` (${context.execPath})` : ""}`;
2541
+ }
2542
+ return `Failed to start Droid: ${error.code}`;
2543
+ }
2544
+ function describeExitError(code, signal) {
2545
+ if (signal) {
2546
+ return `Droid process was killed (${signal})`;
2547
+ }
2548
+ if (code !== null) {
2549
+ return `Droid process exited unexpectedly (exit code ${code})`;
2550
+ }
2551
+ return "Droid process exited unexpectedly";
2552
+ }
2553
+ var ManagedProcessImpl = class {
2554
+ constructor(childProcess, logPrefix, spawnContext, deps, transportLoggerDeps = deps) {
2555
+ this.logPrefix = logPrefix;
2556
+ this.spawnContext = spawnContext;
2557
+ this.transportLoggerDeps = transportLoggerDeps;
2558
+ this._childProcess = childProcess;
2559
+ this.logger = deps.logger;
2560
+ this.setupHandlers();
2561
+ }
2562
+ logPrefix;
2563
+ spawnContext;
2564
+ transportLoggerDeps;
2565
+ _childProcess;
2566
+ messageHandler = null;
2567
+ errorHandler = null;
2568
+ readlineInterface = null;
2569
+ isClosing = false;
2570
+ /** Latch so exit teardown/classification runs exactly once per process. */
2571
+ exitFinalized = false;
2572
+ exitDrainTimer = null;
2573
+ /**
2574
+ * Sticky error from a process error or unexpected exit event. Once set,
2575
+ * all subsequent `send()` calls throw this error immediately instead of
2576
+ * hanging on a dead transport.
2577
+ */
2578
+ processError = null;
2579
+ queuedSendPromise = Promise.resolve();
2580
+ logger;
2581
+ get childProcess() {
2582
+ if (!this._childProcess) {
2583
+ throw new ConnectionError("Process not connected");
2584
+ }
2585
+ return this._childProcess;
2586
+ }
2587
+ setupHandlers() {
2588
+ if (!this.childProcess.stdout) {
2589
+ throw new ConnectionError("Failed to get process stdout");
2590
+ }
2591
+ this.readlineInterface = readline.createInterface({
2592
+ input: this.childProcess.stdout,
2593
+ crlfDelay: Infinity
2594
+ });
2595
+ this.readlineInterface.on("line", (line) => {
2596
+ const trimmedLine = line.trim();
2597
+ if (this.messageHandler && trimmedLine) {
2598
+ if (trimmedLine.startsWith("{") || trimmedLine.startsWith("[")) {
2599
+ logTransportMessage(
2600
+ "in" /* In */,
2601
+ trimmedLine,
2602
+ this._childProcess?.pid,
2603
+ this.transportLoggerDeps
2604
+ );
2605
+ this.messageHandler(trimmedLine);
2606
+ } else {
2607
+ const truncated = trimmedLine.length > MAX_NON_JSON_LOG_LENGTH ? trimmedLine.substring(0, MAX_NON_JSON_LOG_LENGTH) : trimmedLine;
2608
+ this.logger.warn("[droid process] non-JSON output", {
2609
+ state: this.logPrefix,
2610
+ output: truncated
2611
+ });
2612
+ }
2613
+ }
2614
+ });
2615
+ this.childProcess.on("error", (error) => {
2616
+ this.processError = new ConnectionError(
2617
+ describeSpawnError(error, this.spawnContext),
2618
+ {
2619
+ error,
2620
+ cwd: this.spawnContext?.cwd,
2621
+ execPath: this.spawnContext?.execPath
2622
+ }
2623
+ );
2624
+ if (!this.isClosing && this.errorHandler) {
2625
+ this.errorHandler(this.processError);
2626
+ }
2627
+ });
2628
+ this.childProcess.on("exit", (code, signal) => {
2629
+ this.exitDrainTimer = setTimeout(() => {
2630
+ this.finalizeExit(code, signal);
2631
+ }, EXIT_STDIO_DRAIN_TIMEOUT_MS);
2632
+ this.exitDrainTimer.unref?.();
2633
+ });
2634
+ this.childProcess.on("close", (code, signal) => {
2635
+ this.finalizeExit(code, signal);
2636
+ });
2637
+ if (this.childProcess.stderr) {
2638
+ this.childProcess.stderr.on("data", (data) => {
2639
+ this.logger.warn("[droid process] stderr", {
2640
+ state: this.logPrefix,
2641
+ output: data.toString()
2642
+ });
2643
+ });
2644
+ }
2645
+ }
2646
+ finalizeExit(code, signal) {
2647
+ if (this.exitFinalized) {
2648
+ return;
2649
+ }
2650
+ this.exitFinalized = true;
2651
+ if (this.exitDrainTimer) {
2652
+ clearTimeout(this.exitDrainTimer);
2653
+ this.exitDrainTimer = null;
2654
+ }
2655
+ this._childProcess = null;
2656
+ if (this.readlineInterface) {
2657
+ this.readlineInterface.close();
2658
+ this.readlineInterface = null;
2659
+ }
2660
+ if (!this.isClosing) {
2661
+ this.processError = new ProcessExitError(
2662
+ describeExitError(code, signal),
2663
+ {
2664
+ exitCode: code ?? void 0,
2665
+ signal: signal ?? void 0
2666
+ }
2667
+ );
2668
+ if (this.errorHandler) {
2669
+ this.errorHandler(this.processError);
2670
+ }
2671
+ }
2672
+ }
2673
+ async send(message) {
2674
+ if (this.processError) {
2675
+ throw this.processError;
2676
+ }
2677
+ if (!this._childProcess || !this._childProcess.stdin) {
2678
+ throw new ConnectionError("Process not connected");
2679
+ }
2680
+ const previousSends = this.queuedSendPromise;
2681
+ this.queuedSendPromise = (async () => {
2682
+ await previousSends.catch(() => {
2683
+ });
2684
+ if (!this._childProcess || !this._childProcess.stdin || this._childProcess.killed || this.isClosing) {
2685
+ throw new ConnectionError("Process disconnected before write");
2686
+ }
2687
+ await new Promise((resolve2, reject) => {
2688
+ try {
2689
+ if (!this._childProcess || !this._childProcess.stdin) {
2690
+ reject(new ConnectionError("Process stdin unavailable"));
2691
+ return;
2692
+ }
2693
+ const stdin = this._childProcess.stdin;
2694
+ if ("writable" in stdin && !stdin.writable) {
2695
+ reject(new ConnectionError("Process stdin is not writable"));
2696
+ return;
2697
+ }
2698
+ const childPid = this._childProcess?.pid;
2699
+ stdin.write(`${message}
2700
+ `, (error) => {
2701
+ if (error) {
2702
+ logTransportMessage(
2703
+ "out_failed" /* OutFailed */,
2704
+ message,
2705
+ childPid,
2706
+ this.transportLoggerDeps
2707
+ );
2708
+ const errorMessage = error.message || String(error);
2709
+ if (errorMessage.includes("EPIPE") || errorMessage.includes("ECONNRESET")) {
2710
+ reject(
2711
+ new ConnectionError("Process stdin closed during write", {
2712
+ error
2713
+ })
2714
+ );
2715
+ } else {
2716
+ reject(
2717
+ new ConnectionError("Failed to write to process stdin", {
2718
+ error
2719
+ })
2720
+ );
2721
+ }
2722
+ } else {
2723
+ logTransportMessage(
2724
+ "out" /* Out */,
2725
+ message,
2726
+ childPid,
2727
+ this.transportLoggerDeps
2728
+ );
2729
+ resolve2();
2730
+ }
2731
+ });
2732
+ } catch (error) {
2733
+ logWarn(
2734
+ this.logger,
2735
+ "[ManagedProcess] Error writing to process stdin",
2736
+ {
2737
+ cause: error
2738
+ }
2739
+ );
2740
+ reject(
2741
+ new ConnectionError("Error writing to process stdin", {
2742
+ error: error instanceof Error ? error : new Error(String(error))
2743
+ })
2744
+ );
2745
+ }
2746
+ });
2747
+ })();
2748
+ return this.queuedSendPromise;
2749
+ }
2750
+ onMessage(handler) {
2751
+ this.messageHandler = handler;
2752
+ }
2753
+ onError(handler) {
2754
+ this.errorHandler = handler;
2755
+ }
2756
+ async close() {
2757
+ this.isClosing = true;
2758
+ if (this._childProcess) {
2759
+ const processToClose = this._childProcess;
2760
+ if (processToClose.pid === void 0 || processToClose.exitCode !== null || processToClose.signalCode !== null && processToClose.signalCode !== void 0) {
2761
+ this._childProcess = null;
2762
+ } else {
2763
+ await new Promise((resolve2) => {
2764
+ let forcedExitTimeout;
2765
+ const gracefulExitTimeout = setTimeout(() => {
2766
+ if (processToClose.exitCode === null) {
2767
+ processToClose.kill("SIGTERM");
2768
+ forcedExitTimeout = setTimeout(() => {
2769
+ if (processToClose.exitCode === null) {
2770
+ processToClose.kill("SIGKILL");
2771
+ }
2772
+ }, FORCED_EXIT_TIMEOUT_MS);
2773
+ }
2774
+ }, GRACEFUL_EXIT_TIMEOUT_MS);
2775
+ processToClose.once("exit", () => {
2776
+ clearTimeout(gracefulExitTimeout);
2777
+ if (forcedExitTimeout) clearTimeout(forcedExitTimeout);
2778
+ resolve2();
2779
+ });
2780
+ if (processToClose.stdin) {
2781
+ processToClose.stdin.end();
2782
+ }
2783
+ });
2784
+ }
2785
+ }
2786
+ if (this.readlineInterface) {
2787
+ this.readlineInterface.close();
2788
+ this.readlineInterface = null;
2789
+ }
2790
+ this.exitFinalized = true;
2791
+ if (this.exitDrainTimer) {
2792
+ clearTimeout(this.exitDrainTimer);
2793
+ this.exitDrainTimer = null;
2794
+ }
2795
+ this._childProcess = null;
2796
+ this.isClosing = false;
2797
+ }
2798
+ get isConnected() {
2799
+ return this._childProcess !== null && !this._childProcess.killed && this._childProcess.stdin !== null && !this._childProcess.stdin.destroyed && ("writable" in this._childProcess.stdin ? this._childProcess.stdin.writable : true);
2800
+ }
2801
+ };
2802
+
2803
+ // src/exec-core/process-manager.ts
2804
+ import { spawn } from "child_process";
2805
+
2806
+ // src/exec-core/windows-job-object-retry.ts
2807
+ var DEFAULT_BACKOFF_MS = [50, 150, 400];
2808
+ var DEFAULT_MAX_RETRIES = 2;
2809
+ var DEFAULT_GRACE_PERIOD_MS = 250;
2810
+ var defaultSleep = (ms) => new Promise((resolve2) => {
2811
+ setTimeout(resolve2, ms);
2812
+ });
2813
+ function observeEarlySpawnFailure(childProcess, gracePeriodMs, sleep) {
2814
+ const observation = {
2815
+ exited: false,
2816
+ code: null,
2817
+ signal: null,
2818
+ error: null,
2819
+ stderr: ""
2820
+ };
2821
+ const stderrListener = (data) => {
2822
+ observation.stderr += data.toString();
2823
+ };
2824
+ const exitListener = (code, signal) => {
2825
+ observation.exited = true;
2826
+ observation.code = code;
2827
+ observation.signal = signal;
2828
+ };
2829
+ const errorListener = (err) => {
2830
+ observation.error = err;
2831
+ };
2832
+ childProcess.stderr?.on("data", stderrListener);
2833
+ childProcess.once("exit", exitListener);
2834
+ childProcess.once("error", errorListener);
2835
+ const cleanup = () => {
2836
+ childProcess.stderr?.off("data", stderrListener);
2837
+ childProcess.off("exit", exitListener);
2838
+ childProcess.off("error", errorListener);
2839
+ };
2840
+ return new Promise((resolve2) => {
2841
+ const resolveAndCleanup = () => {
2842
+ cleanup();
2843
+ resolve2(observation);
2844
+ };
2845
+ const onExitResolve = () => {
2846
+ setImmediate(resolveAndCleanup);
2847
+ };
2848
+ childProcess.once("exit", onExitResolve);
2849
+ childProcess.once("error", onExitResolve);
2850
+ void sleep(gracePeriodMs).then(() => {
2851
+ childProcess.off("exit", onExitResolve);
2852
+ childProcess.off("error", onExitResolve);
2853
+ resolveAndCleanup();
2854
+ });
2855
+ });
2856
+ }
2857
+ async function spawnWithWindowsJobObjectRetry(spawnFactory, options = {}) {
2858
+ const enabled = options.enabled ?? process.platform === "win32";
2859
+ if (!enabled) {
2860
+ return spawnFactory();
2861
+ }
2862
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
2863
+ const backoff = options.backoffMs ?? DEFAULT_BACKOFF_MS;
2864
+ const gracePeriodMs = options.gracePeriodMs ?? DEFAULT_GRACE_PERIOD_MS;
2865
+ const sleep = options.sleep ?? defaultSleep;
2866
+ const logPrefix = options.logPrefix ?? "[spawnWithWindowsJobObjectRetry]";
2867
+ const logger = options.logger ?? noopLogger;
2868
+ let lastChild = null;
2869
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2870
+ const child = spawnFactory();
2871
+ lastChild = child;
2872
+ const observation = await observeEarlySpawnFailure(
2873
+ child,
2874
+ gracePeriodMs,
2875
+ sleep
2876
+ );
2877
+ if (!observation.exited && !observation.error) {
2878
+ return child;
2879
+ }
2880
+ const isRetryableJobObjectFailure = observation.stderr.includes(WINDOWS_JOB_OBJECT_ERROR_MARKER) || observation.exited && observation.code !== 0 && !observation.error;
2881
+ if (attempt === maxRetries || !isRetryableJobObjectFailure) {
2882
+ return child;
2883
+ }
2884
+ logger.warn("spawnWithWindowsJobObjectRetry: retrying on early failure", {
2885
+ name: logPrefix,
2886
+ attempt: attempt + 1,
2887
+ maxAttempts: maxRetries,
2888
+ exitCode: observation.code,
2889
+ signal: observation.signal,
2890
+ stderrTail: observation.stderr.slice(-256)
2891
+ });
2892
+ try {
2893
+ await options.disposeEarlyExited?.(child);
2894
+ } catch (disposeErr) {
2895
+ logWarn(logger, "spawnWithWindowsJobObjectRetry: dispose error", {
2896
+ cause: disposeErr instanceof Error ? disposeErr : new Error(String(disposeErr)),
2897
+ name: logPrefix
2898
+ });
2899
+ }
2900
+ await sleep(backoff[attempt] ?? backoff[backoff.length - 1] ?? 400);
2901
+ }
2902
+ if (lastChild) return lastChild;
2903
+ throw new DroidClientError(
2904
+ "spawnWithWindowsJobObjectRetry: exhausted retries without child",
2905
+ {}
2906
+ );
2907
+ }
2908
+
2909
+ // src/exec-core/process-manager.ts
2910
+ function buildArgs(config) {
2911
+ const args = [];
2912
+ if (config.mode === "acp" /* Acp */) {
2913
+ args.push("exec", "--output-format", "acp");
2914
+ } else {
2915
+ args.push(
2916
+ "exec",
2917
+ "--input-format",
2918
+ "stream-jsonrpc",
2919
+ "--output-format",
2920
+ "stream-jsonrpc"
2921
+ );
2922
+ }
2923
+ if (config.extraArgs) {
2924
+ args.push(...config.extraArgs);
2925
+ }
2926
+ return args;
2927
+ }
2928
+ var DroidProcessManager = class {
2929
+ deps;
2930
+ transportLoggerDeps;
2931
+ logger;
2932
+ commandResolver;
2933
+ constructor(options = {}, deps = defaultExecCoreDeps) {
2934
+ const resolved = resolveExecCoreDeps(options.observability, deps);
2935
+ this.deps = resolved;
2936
+ this.transportLoggerDeps = deps;
2937
+ this.logger = resolved.logger;
2938
+ this.commandResolver = resolved.commandResolver;
2939
+ }
2940
+ /**
2941
+ * Spawn a new droid process with the given configuration.
2942
+ *
2943
+ * Returns a synchronous ManagedProcess as soon as the OS reports the child
2944
+ * as spawned. This does not retry Windows Job Object spawn failures — use
2945
+ * {@link DroidProcessManager#spawnWithWindowsRetry} for that.
2946
+ */
2947
+ spawn(config) {
2948
+ const { logPrefix, execPath, expandedCwd, childProcess } = this.spawnChildProcess(config);
2949
+ return new ManagedProcessImpl(
2950
+ childProcess,
2951
+ logPrefix,
2952
+ {
2953
+ cwd: expandedCwd,
2954
+ execPath
2955
+ },
2956
+ this.deps,
2957
+ this.transportLoggerDeps
2958
+ );
2959
+ }
2960
+ /**
2961
+ * Spawn a droid process with automatic retry for the Windows Job Object
2962
+ * spawn error class (FAC-19070). On non-Windows platforms this behaves
2963
+ * identically to {@link DroidProcessManager#spawn} but returns a promise.
2964
+ *
2965
+ * When a Windows child process exits within the startup grace period and
2966
+ * the exit looks like the `AssignProcessToJobObject` failure pattern, the
2967
+ * dead child is disposed and a fresh spawn is attempted, up to the
2968
+ * configured retry cap.
2969
+ */
2970
+ async spawnWithWindowsRetry(config, retryOptions = {}) {
2971
+ if (process.platform !== "win32") {
2972
+ return this.spawn(config);
2973
+ }
2974
+ const planned = this.prepareSpawn(config);
2975
+ const childProcess = await spawnWithWindowsJobObjectRetry(
2976
+ () => this.invokeNodeSpawn(planned),
2977
+ {
2978
+ ...retryOptions,
2979
+ logPrefix: "[DroidProcessManager]",
2980
+ logger: this.logger,
2981
+ disposeEarlyExited: (child) => {
2982
+ try {
2983
+ child.stdin?.end();
2984
+ } catch (stdinErr) {
2985
+ logWarn(
2986
+ this.logger,
2987
+ "DroidProcessManager: stdin.end() threw during dispose",
2988
+ {
2989
+ cause: stdinErr instanceof Error ? stdinErr : new Error(String(stdinErr))
2990
+ }
2991
+ );
2992
+ }
2993
+ try {
2994
+ child.kill();
2995
+ } catch (killErr) {
2996
+ logWarn(
2997
+ this.logger,
2998
+ "DroidProcessManager: kill() threw during dispose",
2999
+ {
3000
+ cause: killErr instanceof Error ? killErr : new Error(String(killErr))
3001
+ }
3002
+ );
3003
+ }
3004
+ }
3005
+ }
3006
+ );
3007
+ if (!childProcess.stdout || !childProcess.stdin) {
3008
+ throw new ConnectionError("Failed to get process stdio");
3009
+ }
3010
+ return new ManagedProcessImpl(
3011
+ childProcess,
3012
+ planned.logPrefix,
3013
+ {
3014
+ cwd: planned.expandedCwd,
3015
+ execPath: planned.execPath
3016
+ },
3017
+ this.deps,
3018
+ this.transportLoggerDeps
3019
+ );
3020
+ }
3021
+ prepareSpawn(config) {
3022
+ const command = this.commandResolver.resolveDroidCommand(
3023
+ config.isDevelopment ?? false
3024
+ );
3025
+ const execPath = config.execPath || command.execPath;
3026
+ const prefixArgs = config.execPath ? [] : command.prefixArgs;
3027
+ const args = [...prefixArgs, ...buildArgs(config)];
3028
+ const expandedCwd = config.cwd ? expandTilde(config.cwd) : void 0;
3029
+ const logPrefix = config.mode === "acp" /* Acp */ ? "[droid acp]" : "[droid exec]";
3030
+ this.logger.info("[droid process] Spawning", {
3031
+ state: logPrefix,
3032
+ path: execPath,
3033
+ args,
3034
+ cwd: expandedCwd,
3035
+ version: process.env.CLI_VERSION || "unknown"
3036
+ });
3037
+ return {
3038
+ logPrefix,
3039
+ execPath,
3040
+ expandedCwd,
3041
+ args,
3042
+ env: {
3043
+ ...this.deps.environmentResolver.sanitizeSpawnEnv({
3044
+ ...process.env,
3045
+ ...config.env
3046
+ }),
3047
+ ...config.trustedEnv
3048
+ },
3049
+ enableIpc: config.enableIpc ?? false,
3050
+ stdio: config.stdio
3051
+ };
3052
+ }
3053
+ invokeNodeSpawn(planned) {
3054
+ const options = {
3055
+ cwd: planned.expandedCwd,
3056
+ env: planned.env,
3057
+ stdio: planned.stdio ?? (planned.enableIpc ? ["pipe", "pipe", "pipe", "ipc"] : ["pipe", "pipe", "pipe"])
3058
+ };
3059
+ if (planned.enableIpc) {
3060
+ options.serialization = "json";
3061
+ }
3062
+ return spawn(planned.execPath, planned.args, options);
3063
+ }
3064
+ spawnChildProcess(config) {
3065
+ const planned = this.prepareSpawn(config);
3066
+ const childProcess = this.invokeNodeSpawn(planned);
3067
+ if (!childProcess.stdout || !childProcess.stdin) {
3068
+ throw new ConnectionError("Failed to get process stdio");
3069
+ }
3070
+ return {
3071
+ logPrefix: planned.logPrefix,
3072
+ execPath: planned.execPath,
3073
+ expandedCwd: planned.expandedCwd,
3074
+ childProcess
3075
+ };
3076
+ }
3077
+ };
3078
+
3079
+ // src/exec-core/process-transport.ts
3080
+ var ProcessTransport = class {
3081
+ managedProcess = null;
3082
+ processManager;
3083
+ options;
3084
+ // Store handlers that may be registered before connect() is called
3085
+ messageHandler = null;
3086
+ errorHandler = null;
3087
+ metrics;
3088
+ constructor(options = {}, deps = defaultExecCoreDeps) {
3089
+ this.options = options;
3090
+ const resolved = resolveExecCoreDeps(options.observability, deps);
3091
+ this.metrics = resolved.metrics;
3092
+ this.processManager = new DroidProcessManager(
3093
+ {
3094
+ observability: options.observability
3095
+ },
3096
+ deps
3097
+ );
3098
+ }
3099
+ async connect() {
3100
+ if (this.managedProcess && this.managedProcess.isConnected) {
3101
+ throw new ConnectionError("Transport already connected");
3102
+ }
3103
+ const config = {
3104
+ execPath: this.options.droidExecPath,
3105
+ isDevelopment: this.options.isDevelopment,
3106
+ mode: "stream-jsonrpc" /* StreamJsonRpc */,
3107
+ cwd: this.options.cwd,
3108
+ env: this.options.env,
3109
+ extraArgs: this.options.droidExecExtraArgs,
3110
+ enableIpc: this.options.enableIpc
3111
+ };
3112
+ const spawnStart = performance.now();
3113
+ let spawnOutcome = "error";
3114
+ try {
3115
+ this.managedProcess = process.platform === "win32" ? await this.processManager.spawnWithWindowsRetry(config) : this.processManager.spawn(config);
3116
+ spawnOutcome = "success";
3117
+ } finally {
3118
+ this.metrics.recordDuration(
3119
+ CLI_JSONRPC_CHILD_SPAWN_LATENCY_METRIC,
3120
+ performance.now() - spawnStart,
3121
+ { outcome: spawnOutcome, source: "process_transport" }
3122
+ );
3123
+ }
3124
+ if (this.messageHandler) {
3125
+ this.managedProcess.onMessage(this.messageHandler);
3126
+ }
3127
+ if (this.errorHandler) {
3128
+ this.managedProcess.onError(this.errorHandler);
3129
+ }
3130
+ }
3131
+ async send(message) {
3132
+ if (!this.managedProcess) {
3133
+ throw new ConnectionError("Transport not connected");
3134
+ }
3135
+ return this.managedProcess.send(message);
3136
+ }
3137
+ onMessage(handler) {
3138
+ this.messageHandler = handler;
3139
+ if (this.managedProcess) {
3140
+ this.managedProcess.onMessage(handler);
3141
+ }
3142
+ }
3143
+ onError(handler) {
3144
+ this.errorHandler = handler;
3145
+ if (this.managedProcess) {
3146
+ this.managedProcess.onError(handler);
3147
+ }
3148
+ }
3149
+ async close() {
3150
+ if (this.managedProcess) {
3151
+ await this.managedProcess.close();
3152
+ this.managedProcess = null;
3153
+ }
3154
+ }
3155
+ get isConnected() {
3156
+ return this.managedProcess?.isConnected ?? false;
3157
+ }
3158
+ getManagedProcess() {
3159
+ return this.managedProcess;
3160
+ }
3161
+ };
3162
+
3163
+ // src/helpers.ts
3164
+ function resolveApiKey(apiKey) {
3165
+ const resolved = apiKey ?? process.env.FACTORY_API_KEY;
3166
+ if (!resolved) {
3167
+ throw new DroidClientError(
3168
+ "No Factory API key found. Pass `apiKey` when creating the session, or set the FACTORY_API_KEY environment variable."
3169
+ );
3170
+ }
3171
+ return resolved;
3172
+ }
3173
+ async function createTransport(options) {
3174
+ if (options.transport) {
3175
+ return options.transport;
3176
+ }
3177
+ const processTransport = new ProcessTransport({
3178
+ droidExecPath: options.execPath,
3179
+ droidExecExtraArgs: options.execArgs,
3180
+ cwd: options.cwd,
3181
+ env: { ...options.env, FACTORY_API_KEY: resolveApiKey(options.apiKey) },
3182
+ observability: options.observability
3183
+ });
3184
+ await processTransport.connect();
3185
+ return processTransport;
3186
+ }
3187
+ function setupClientHandlers(client, options) {
3188
+ if (options.permissionHandler) {
3189
+ const handler = options.permissionHandler;
3190
+ client.setPermissionHandler((event) => handler(event.params));
3191
+ }
3192
+ if (options.askUserHandler) {
3193
+ const handler = options.askUserHandler;
3194
+ client.setAskUserHandler((event) => handler(event.params));
3195
+ }
3196
+ }
3197
+ async function createConfiguredClient(options) {
3198
+ const transport = await createTransport(options);
3199
+ const client = new DroidClient({
3200
+ transport,
3201
+ observability: options.observability
3202
+ });
3203
+ setupClientHandlers(client, options);
3204
+ return { transport, client };
3205
+ }
3206
+ async function closeQuietly(resource) {
3207
+ if (!resource) {
3208
+ return;
3209
+ }
3210
+ try {
3211
+ await resource.close();
3212
+ } catch {
3213
+ }
3214
+ }
3215
+ function buildInitParams(options) {
3216
+ return {
3217
+ machineId: options.machineId ?? "default",
3218
+ cwd: options.cwd ?? process.cwd(),
3219
+ ...options.modelId !== void 0 && { modelId: options.modelId },
3220
+ ...options.autonomyLevel !== void 0 && {
3221
+ autonomyLevel: options.autonomyLevel
3222
+ },
3223
+ ...options.interactionMode !== void 0 && {
3224
+ interactionMode: options.interactionMode
3225
+ },
3226
+ ...options.reasoningEffort !== void 0 && {
3227
+ reasoningEffort: options.reasoningEffort
3228
+ },
3229
+ ...options.specModeModelId !== void 0 && {
3230
+ specModeModelId: options.specModeModelId
3231
+ },
3232
+ ...options.specModeReasoningEffort !== void 0 && {
3233
+ specModeReasoningEffort: options.specModeReasoningEffort
3234
+ },
3235
+ ...options.mcpServers !== void 0 && {
3236
+ mcpServers: options.mcpServers
3237
+ },
3238
+ ...options.disabledToolIds !== void 0 && {
3239
+ disabledToolIds: options.disabledToolIds
3240
+ },
3241
+ ...options.sessionSource !== void 0 && {
3242
+ sessionSource: options.sessionSource
3243
+ },
3244
+ ...options.autoRejectPermissionRequests !== void 0 && {
3245
+ autoRejectPermissionRequests: options.autoRejectPermissionRequests
3246
+ },
3247
+ ...options.disableBuiltinSkills !== void 0 && {
3248
+ disableBuiltinSkills: options.disableBuiltinSkills
3249
+ },
3250
+ tags: [...options.tags ?? [], SDK_TAG]
3251
+ };
3252
+ }
3253
+
3254
+ // src/mcp.ts
3255
+ import { randomBytes, timingSafeEqual } from "crypto";
3256
+ import { once } from "events";
3257
+ import http from "http";
3258
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3259
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3260
+ import { z as z2 } from "zod";
3261
+ function tool(name, description, inputSchemaOrHandler, handler) {
3262
+ if (typeof inputSchemaOrHandler === "function") {
3263
+ const actualHandler = inputSchemaOrHandler;
3264
+ return {
3265
+ name,
3266
+ description,
3267
+ handler: (input) => actualHandler(input)
3268
+ };
3269
+ }
3270
+ if (!handler) {
3271
+ throw new Error(`Missing handler for SDK MCP tool "${name}"`);
3272
+ }
3273
+ const inputObjectSchema = z2.object(inputSchemaOrHandler);
3274
+ return {
3275
+ name,
3276
+ description,
3277
+ inputSchema: inputSchemaOrHandler,
3278
+ handler: (input) => handler(inputObjectSchema.parse(input))
3279
+ };
3280
+ }
3281
+ function isSdkMcpServer(server) {
3282
+ return server instanceof SdkMcpServer;
3283
+ }
3284
+ function toCallToolResult(result) {
3285
+ if (typeof result === "string") {
3286
+ return {
3287
+ content: [{ type: "text", text: result }]
3288
+ };
3289
+ }
3290
+ return result;
3291
+ }
3292
+ async function readJsonBody(req) {
3293
+ const chunks = [];
3294
+ for await (const chunk of req) {
3295
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
3296
+ }
3297
+ if (chunks.length === 0) {
3298
+ return void 0;
3299
+ }
3300
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
3301
+ }
3302
+ function writeJsonError(res, statusCode, message, headers = {}) {
3303
+ if (res.headersSent) {
3304
+ return;
3305
+ }
3306
+ res.writeHead(statusCode, {
3307
+ "content-type": "application/json",
3308
+ ...headers
3309
+ });
3310
+ res.end(
3311
+ JSON.stringify({
3312
+ jsonrpc: JSONRPC_VERSION,
3313
+ error: { code: -32603 /* INTERNAL_ERROR */, message },
3314
+ id: null
3315
+ })
3316
+ );
3317
+ }
3318
+ function hasValidBearerToken(authorization, token) {
3319
+ if (!authorization) {
3320
+ return false;
3321
+ }
3322
+ const separator = authorization.indexOf(" ");
3323
+ if (separator === -1 || authorization.slice(0, separator).toLowerCase() !== "bearer") {
3324
+ return false;
3325
+ }
3326
+ const actual = Buffer.from(authorization.slice(separator + 1));
3327
+ const expected = Buffer.from(token);
3328
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
3329
+ }
3330
+ var SdkMcpServer = class {
3331
+ name;
3332
+ version;
3333
+ tools;
3334
+ _httpServer = null;
3335
+ _url = null;
3336
+ _token = null;
3337
+ constructor(options) {
3338
+ this.name = options.name;
3339
+ this.version = options.version ?? "1.0.0";
3340
+ this.tools = options.tools;
3341
+ }
3342
+ get config() {
3343
+ if (!this._url || !this._token) {
3344
+ return null;
3345
+ }
3346
+ return {
3347
+ type: "http" /* Http */,
3348
+ name: this.name,
3349
+ url: this._url,
3350
+ oauth: false,
3351
+ headers: [
3352
+ {
3353
+ name: "Authorization",
3354
+ value: `Bearer ${this._token}`
3355
+ }
3356
+ ]
3357
+ };
3358
+ }
3359
+ async start() {
3360
+ if (this.config) {
3361
+ return this.config;
3362
+ }
3363
+ this._token = randomBytes(32).toString("base64url");
3364
+ this._httpServer = http.createServer((req, res) => {
3365
+ void this.handleRequest(req, res);
3366
+ });
3367
+ this._httpServer.listen(0, "127.0.0.1");
3368
+ await once(this._httpServer, "listening");
3369
+ const address = this._httpServer.address();
3370
+ if (!address || typeof address === "string") {
3371
+ throw new Error("Unable to determine SDK MCP server address");
3372
+ }
3373
+ this._url = `http://127.0.0.1:${address.port}/mcp`;
3374
+ const config = this.config;
3375
+ if (!config) {
3376
+ throw new Error("Unable to start SDK MCP server");
3377
+ }
3378
+ return config;
3379
+ }
3380
+ async close() {
3381
+ const server = this._httpServer;
3382
+ this._httpServer = null;
3383
+ this._url = null;
3384
+ this._token = null;
3385
+ if (!server) {
3386
+ return;
3387
+ }
3388
+ server.closeAllConnections?.();
3389
+ server.close();
3390
+ await once(server, "close");
3391
+ }
3392
+ createMcpServer() {
3393
+ const server = new McpServer({
3394
+ name: this.name,
3395
+ version: this.version
3396
+ });
3397
+ for (const sdkTool of this.tools) {
3398
+ server.registerTool(
3399
+ sdkTool.name,
3400
+ {
3401
+ description: sdkTool.description,
3402
+ ...sdkTool.inputSchema && {
3403
+ inputSchema: sdkTool.inputSchema
3404
+ }
3405
+ },
3406
+ async (input) => toCallToolResult(await sdkTool.handler(input))
3407
+ );
3408
+ }
3409
+ return server;
3410
+ }
3411
+ async handleRequest(req, res) {
3412
+ if (req.url !== "/mcp") {
3413
+ res.writeHead(404).end();
3414
+ return;
3415
+ }
3416
+ if (req.method !== "POST") {
3417
+ res.writeHead(405).end();
3418
+ return;
3419
+ }
3420
+ const token = this._token;
3421
+ if (!token || !hasValidBearerToken(req.headers.authorization, token)) {
3422
+ writeJsonError(res, 401, "Unauthorized", {
3423
+ "www-authenticate": "Bearer"
3424
+ });
3425
+ return;
3426
+ }
3427
+ const server = this.createMcpServer();
3428
+ const transport = new StreamableHTTPServerTransport({
3429
+ sessionIdGenerator: void 0
3430
+ });
3431
+ res.on("close", () => {
3432
+ void transport.close();
3433
+ void server.close();
3434
+ });
3435
+ try {
3436
+ const body = await readJsonBody(req);
3437
+ await server.connect(transport);
3438
+ await transport.handleRequest(req, res, body);
3439
+ } catch (error) {
3440
+ writeJsonError(
3441
+ res,
3442
+ 500,
3443
+ error instanceof Error ? error.message : "Internal server error"
3444
+ );
3445
+ await transport.close();
3446
+ await server.close();
3447
+ }
3448
+ }
3449
+ };
3450
+ function createSdkMcpServer(options) {
3451
+ return new SdkMcpServer(options);
3452
+ }
3453
+ async function startSdkMcpServers(servers) {
3454
+ if (!servers) {
3455
+ return { cleanup: async () => {
3456
+ } };
3457
+ }
3458
+ const startedServers = [];
3459
+ const mcpServers = [];
3460
+ try {
3461
+ for (const server of servers) {
3462
+ if (isSdkMcpServer(server)) {
3463
+ mcpServers.push(await server.start());
3464
+ startedServers.push(server);
3465
+ } else {
3466
+ mcpServers.push(server);
3467
+ }
3468
+ }
3469
+ } catch (error) {
3470
+ await Promise.all(startedServers.map((server) => server.close()));
3471
+ throw error;
3472
+ }
3473
+ return {
3474
+ mcpServers,
3475
+ cleanup: async () => {
3476
+ await Promise.all(startedServers.map((server) => server.close()));
3477
+ }
3478
+ };
3479
+ }
3480
+
3481
+ // src/session.ts
3482
+ var DroidSession = class _DroidSession {
3483
+ /** @internal */
3484
+ constructor(client, sessionId, metadata, _runtime, cleanupCallbacks = []) {
3485
+ this._runtime = _runtime;
3486
+ this._client = client;
3487
+ this._sessionId = sessionId;
3488
+ this._settings = metadata.settings;
3489
+ this._cwd = metadata.cwd;
3490
+ this._cleanupCallbacks = cleanupCallbacks;
3491
+ this._bindMetadataNotifications();
3492
+ this._bindAbortSignal();
3493
+ }
3494
+ _runtime;
3495
+ _client;
3496
+ _sessionId;
3497
+ _settings;
3498
+ _cwd;
3499
+ _settingsRevision = 0;
3500
+ _status = "active";
3501
+ _replacementSessionId;
3502
+ _cleanupAbortSignal = null;
3503
+ _cleanupCallbacks = [];
3504
+ _activeBridges = /* @__PURE__ */ new Set();
3505
+ _notificationCleanups = /* @__PURE__ */ new Set();
3506
+ get id() {
3507
+ return this._sessionId;
3508
+ }
3509
+ get settings() {
3510
+ return this._settings;
3511
+ }
3512
+ get cwd() {
3513
+ return this._cwd;
3514
+ }
3515
+ async *stream(prompt, options) {
3516
+ this._ensureNotClosed();
3517
+ yield* streamFromClient(
3518
+ {
3519
+ onNotification: (handler) => this._client.onNotification((notification) => {
3520
+ const inner = extractInnerNotification(notification);
3521
+ if (inner) handler(inner);
3522
+ }),
3523
+ onError: (handler) => this._client.onError(handler),
3524
+ addUserMessage: (params) => this._client.addUserMessage(params),
3525
+ interruptSession: () => this._client.interruptSession()
3526
+ },
3527
+ this._sessionId,
3528
+ this._activeBridges,
3529
+ prompt,
3530
+ options
3531
+ );
3532
+ }
3533
+ async interrupt() {
3534
+ this._ensureNotClosed();
3535
+ await this._client.interruptSession();
3536
+ }
3537
+ async close() {
3538
+ if (this._status === "closed" || this._status === "replaced") {
3539
+ return;
3540
+ }
3541
+ this._status = "closed";
3542
+ this._releaseHandleSubscriptions();
3543
+ this._cleanupAbortSignal?.();
3544
+ this._cleanupAbortSignal = null;
3545
+ for (const bridge of this._activeBridges) {
3546
+ bridge.signalDone();
3547
+ bridge.release();
3548
+ }
3549
+ try {
3550
+ await this._client.closeSession({ reason: "other" }).catch(() => {
3551
+ });
3552
+ await this._client.close();
3553
+ } finally {
3554
+ const cleanups = this._cleanupCallbacks.splice(0);
3555
+ await Promise.all(cleanups.map((cleanup) => cleanup()));
3556
+ }
3557
+ }
3558
+ async updateSettings(params) {
3559
+ this._ensureNotClosed();
3560
+ const revision = this._settingsRevision;
3561
+ const result = unwrapResponseResult(
3562
+ await this._client.updateSessionSettings(params)
3563
+ );
3564
+ if (params.disabledToolIds !== void 0) {
3565
+ this._runtime.loadParams.disabledToolIds = params.disabledToolIds;
3566
+ }
3567
+ if (this._settingsRevision === revision) {
3568
+ this._settings = mergeSessionSettings(this._settings, params);
3569
+ }
3570
+ return result;
3571
+ }
3572
+ async enterSpecMode(params = {}) {
3573
+ return this.updateSettings({
3574
+ interactionMode: "spec" /* Spec */,
3575
+ ...params
3576
+ });
3577
+ }
3578
+ async addMcpServer(params) {
3579
+ this._ensureNotClosed();
3580
+ return unwrapResponseResult(await this._client.addMcpServer(params));
3581
+ }
3582
+ async removeMcpServer(params) {
3583
+ this._ensureNotClosed();
3584
+ return unwrapResponseResult(await this._client.removeMcpServer(params));
3585
+ }
3586
+ async toggleMcpServer(params) {
3587
+ this._ensureNotClosed();
3588
+ return unwrapResponseResult(await this._client.toggleMcpServer(params));
3589
+ }
3590
+ async listMcpServers() {
3591
+ this._ensureNotClosed();
3592
+ return unwrapResponseResult(await this._client.listMcpServers());
3593
+ }
3594
+ async listMcpTools() {
3595
+ this._ensureNotClosed();
3596
+ return unwrapResponseResult(await this._client.listMcpTools()).tools;
3597
+ }
3598
+ async listTools(params = {}) {
3599
+ this._ensureNotClosed();
3600
+ return unwrapResponseResult(await this._client.listTools(params)).tools.map(
3601
+ ({ id: _protocolId, llmId, currentlyAllowed, ...tool2 }) => ({
3602
+ ...tool2,
3603
+ id: llmId,
3604
+ allowed: currentlyAllowed
3605
+ })
3606
+ );
3607
+ }
3608
+ async authenticateMcpServer(params) {
3609
+ this._ensureNotClosed();
3610
+ return unwrapResponseResult(
3611
+ await this._client.authenticateMcpServer(params)
3612
+ );
3613
+ }
3614
+ async listSkills() {
3615
+ this._ensureNotClosed();
3616
+ return unwrapResponseResult(await this._client.listSkills());
3617
+ }
3618
+ async setSkillDisabled(params) {
3619
+ this._ensureNotClosed();
3620
+ return unwrapResponseResult(
3621
+ await this._client.setSkillDisabled(
3622
+ params.skillName,
3623
+ params.disabled,
3624
+ params.settingsLevel
3625
+ )
3626
+ );
3627
+ }
3628
+ async getRewindInfo(params) {
3629
+ this._ensureNotClosed();
3630
+ return unwrapResponseResult(await this._client.getRewindInfo(params));
3631
+ }
3632
+ async rewind(params) {
3633
+ const { session, result } = await this._runReplacement(
3634
+ () => this._client.executeRewind(params).then(unwrapResponseResult)
3635
+ );
3636
+ const { newSessionId: _newSessionId, ...metadata } = result;
3637
+ return { session, ...metadata };
3638
+ }
3639
+ async compact(params) {
3640
+ const { session, result } = await this._runReplacement(
3641
+ () => this._client.compactSession(params ?? {}).then(unwrapResponseResult)
3642
+ );
3643
+ return { session, removedCount: result.removedCount };
3644
+ }
3645
+ async fork(params = {}) {
3646
+ const { session } = await this._runReplacement(
3647
+ () => this._client.forkSession(params).then(unwrapResponseResult)
3648
+ );
3649
+ return session;
3650
+ }
3651
+ async getContextStats() {
3652
+ this._ensureNotClosed();
3653
+ return unwrapResponseResult(await this._client.getContextStats());
3654
+ }
3655
+ async rename(params) {
3656
+ this._ensureNotClosed();
3657
+ unwrapResponseResult(await this._client.renameSession(params));
3658
+ }
3659
+ onNotification(callback, filter) {
3660
+ this._ensureNotClosed();
3661
+ const unsubscribe = this._client.onNotification(callback, filter);
3662
+ const cleanup = () => {
3663
+ this._notificationCleanups.delete(cleanup);
3664
+ unsubscribe();
3665
+ };
3666
+ this._notificationCleanups.add(cleanup);
3667
+ return cleanup;
3668
+ }
3669
+ _ensureNotClosed() {
3670
+ if (this._status === "replaced" && this._replacementSessionId) {
3671
+ throw new SessionReplacedError(
3672
+ this._sessionId,
3673
+ this._replacementSessionId
3674
+ );
3675
+ }
3676
+ if (this._status !== "active") {
3677
+ throw new ConnectionError(
3678
+ this._status === "replacing" ? "Session replacement is already in progress." : "Session has been closed. Create a new session to continue."
3679
+ );
3680
+ }
3681
+ }
3682
+ _beginReplacement() {
3683
+ this._ensureNotClosed();
3684
+ if (this._activeBridges.size > 0) {
3685
+ throw new ConcurrentStreamError(this._sessionId);
3686
+ }
3687
+ this._status = "replacing";
3688
+ }
3689
+ async _runReplacement(operation) {
3690
+ this._beginReplacement();
3691
+ let result;
3692
+ try {
3693
+ result = await operation();
3694
+ } catch (error) {
3695
+ if (this._status === "replacing") {
3696
+ this._status = "active";
3697
+ }
3698
+ throw error;
3699
+ }
3700
+ if (this._status !== "replacing") {
3701
+ throw new SessionReplacementError(this._sessionId, result.newSessionId, {
3702
+ cause: new ConnectionError(
3703
+ "Session closed while replacement was in progress."
3704
+ ),
3705
+ rollbackError: new ConnectionError(
3706
+ "The source session was already closed."
3707
+ )
3708
+ });
3709
+ }
3710
+ return {
3711
+ session: await this._loadReplacement(result.newSessionId),
3712
+ result
3713
+ };
3714
+ }
3715
+ async _loadReplacement(replacementSessionId) {
3716
+ try {
3717
+ const loadResult = unwrapResponseResult(
3718
+ await this._client.loadSession({
3719
+ ...this._runtime.loadParams,
3720
+ sessionId: replacementSessionId
3721
+ })
3722
+ );
3723
+ if (this._status !== "replacing") {
3724
+ throw new ConnectionError(
3725
+ "Session closed while replacement was loading."
3726
+ );
3727
+ }
3728
+ this._cleanupAbortSignal?.();
3729
+ this._cleanupAbortSignal = null;
3730
+ this._releaseHandleSubscriptions();
3731
+ const cleanupCallbacks = this._cleanupCallbacks;
3732
+ this._cleanupCallbacks = [];
3733
+ const replacement = new _DroidSession(
3734
+ this._client,
3735
+ replacementSessionId,
3736
+ { settings: loadResult.settings, cwd: loadResult.cwd },
3737
+ this._runtime,
3738
+ cleanupCallbacks
3739
+ );
3740
+ this._replacementSessionId = replacementSessionId;
3741
+ this._status = "replaced";
3742
+ return replacement;
3743
+ } catch (cause) {
3744
+ if (this._status !== "replacing") {
3745
+ throw new SessionReplacementError(
3746
+ this._sessionId,
3747
+ replacementSessionId,
3748
+ {
3749
+ cause,
3750
+ rollbackError: new ConnectionError(
3751
+ "The source session was closed before rollback."
3752
+ )
3753
+ }
3754
+ );
3755
+ }
3756
+ let rollbackResult;
3757
+ try {
3758
+ rollbackResult = unwrapResponseResult(
3759
+ await this._client.loadSession({
3760
+ ...this._runtime.loadParams,
3761
+ sessionId: this._sessionId
3762
+ })
3763
+ );
3764
+ } catch (rollbackError) {
3765
+ await this._disposeAfterFailedRollback();
3766
+ throw new SessionReplacementError(
3767
+ this._sessionId,
3768
+ replacementSessionId,
3769
+ { cause, rollbackError }
3770
+ );
3771
+ }
3772
+ if (this._status !== "replacing") {
3773
+ const rollbackError = new ConnectionError(
3774
+ "Session closed while replacement rollback was loading."
3775
+ );
3776
+ await this._disposeAfterFailedRollback();
3777
+ throw new SessionReplacementError(
3778
+ this._sessionId,
3779
+ replacementSessionId,
3780
+ { cause, rollbackError }
3781
+ );
3782
+ }
3783
+ this._settings = rollbackResult.settings;
3784
+ this._cwd = rollbackResult.cwd;
3785
+ this._status = "active";
3786
+ throw new SessionReplacementError(this._sessionId, replacementSessionId, {
3787
+ cause
3788
+ });
3789
+ }
3790
+ }
3791
+ _bindAbortSignal() {
3792
+ this._cleanupAbortSignal = wireAbortSignal(
3793
+ this._runtime.abortSignal,
3794
+ () => void this.close()
3795
+ );
3796
+ }
3797
+ _bindMetadataNotifications() {
3798
+ const unsubscribe = this._client.onNotification((notification) => {
3799
+ const inner = extractInnerNotification(notification);
3800
+ if (inner?.type === "settings_updated" /* SETTINGS_UPDATED */) {
3801
+ this._settings = mergeSessionSettings(this._settings, inner.settings);
3802
+ this._settingsRevision++;
3803
+ } else if (inner?.type === "session_working_directory_changed" /* SESSION_WORKING_DIRECTORY_CHANGED */) {
3804
+ this._cwd = inner.cwd;
3805
+ }
3806
+ });
3807
+ const cleanup = () => {
3808
+ this._notificationCleanups.delete(cleanup);
3809
+ unsubscribe();
3810
+ };
3811
+ this._notificationCleanups.add(cleanup);
3812
+ }
3813
+ _releaseHandleSubscriptions() {
3814
+ for (const cleanup of [...this._notificationCleanups]) cleanup();
3815
+ }
3816
+ async _disposeAfterFailedRollback() {
3817
+ this._status = "closed";
3818
+ this._cleanupAbortSignal?.();
3819
+ this._cleanupAbortSignal = null;
3820
+ this._releaseHandleSubscriptions();
3821
+ await closeQuietly(this._client);
3822
+ const cleanups = this._cleanupCallbacks.splice(0);
3823
+ await Promise.allSettled(
3824
+ cleanups.map((cleanup) => Promise.resolve().then(cleanup))
3825
+ );
3826
+ }
3827
+ };
3828
+ function createReplacementLoadParams(options, mcpServers) {
3829
+ return {
3830
+ mcpServers,
3831
+ disabledToolIds: options.disabledToolIds,
3832
+ autoRejectPermissionRequests: options.autoRejectPermissionRequests,
3833
+ disableBuiltinSkills: options.disableBuiltinSkills,
3834
+ sessionSource: options.sessionSource
3835
+ };
3836
+ }
3837
+ async function createSession(options = {}) {
3838
+ const { client } = await createConfiguredClient(options);
3839
+ let cleanupInitAbortSignal = options.abortSignal?.aborted ? () => {
3840
+ } : wireAbortSignal(options.abortSignal, () => {
3841
+ void closeQuietly(client);
3842
+ });
3843
+ let sdkMcpServers;
3844
+ try {
3845
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
3846
+ const initParams = buildInitParams({
3847
+ ...options,
3848
+ mcpServers: sdkMcpServers.mcpServers
3849
+ });
3850
+ const initResult = unwrapResponseResult(
3851
+ await client.initializeSession(initParams)
3852
+ );
3853
+ const session = new DroidSession(
3854
+ client,
3855
+ initResult.sessionId,
3856
+ {
3857
+ settings: initResult.settings,
3858
+ cwd: initResult.worktree?.path ?? initParams.cwd
3859
+ },
3860
+ {
3861
+ abortSignal: options.abortSignal,
3862
+ loadParams: createReplacementLoadParams(
3863
+ options,
3864
+ sdkMcpServers.mcpServers
3865
+ )
3866
+ },
3867
+ [sdkMcpServers.cleanup]
3868
+ );
3869
+ cleanupInitAbortSignal();
3870
+ cleanupInitAbortSignal = () => {
3871
+ };
3872
+ return session;
3873
+ } catch (error) {
3874
+ cleanupInitAbortSignal();
3875
+ await sdkMcpServers?.cleanup();
3876
+ await closeQuietly(client);
3877
+ throw error;
3878
+ }
3879
+ }
3880
+ async function resumeSession(sessionId, options = {}) {
3881
+ const { client } = await createConfiguredClient(options);
3882
+ let cleanupLoadAbortSignal = options.abortSignal?.aborted ? () => {
3883
+ } : wireAbortSignal(options.abortSignal, () => {
3884
+ void closeQuietly(client);
3885
+ });
3886
+ let sdkMcpServers;
3887
+ try {
3888
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
3889
+ const replacementLoadParams = createReplacementLoadParams(
3890
+ options,
3891
+ sdkMcpServers.mcpServers
3892
+ );
3893
+ const loadResult = unwrapResponseResult(
3894
+ await client.loadSession({ sessionId, ...replacementLoadParams })
3895
+ );
3896
+ const session = new DroidSession(
3897
+ client,
3898
+ sessionId,
3899
+ { settings: loadResult.settings, cwd: loadResult.cwd },
3900
+ {
3901
+ abortSignal: options.abortSignal,
3902
+ loadParams: replacementLoadParams
3903
+ },
3904
+ [sdkMcpServers.cleanup]
3905
+ );
3906
+ cleanupLoadAbortSignal();
3907
+ cleanupLoadAbortSignal = () => {
3908
+ };
3909
+ return session;
3910
+ } catch (error) {
3911
+ cleanupLoadAbortSignal();
3912
+ await sdkMcpServers?.cleanup();
3913
+ await closeQuietly(client);
3914
+ throw error;
3915
+ }
3916
+ }
3917
+
3918
+ // src/run.ts
3919
+ async function run(prompt, options = {}) {
3920
+ const session = await createSession(options);
3921
+ try {
3922
+ for await (const msg of session.stream(prompt, {
3923
+ ...options,
3924
+ includePartialMessages: false
3925
+ })) {
3926
+ if (msg.type === DroidMessageType.Result) {
3927
+ return msg;
3928
+ }
3929
+ }
3930
+ throw new Error("Stream completed without a result message");
3931
+ } finally {
3932
+ await session.close();
3933
+ }
3934
+ }
3935
+
3936
+ // src/session-discovery.ts
3937
+ import * as fs3 from "fs";
3938
+ import * as os from "os";
3939
+ import * as path2 from "path";
3940
+ var FAVORITES_FILE = ".favorites";
3941
+ var SESSION_EXTENSION = ".jsonl";
3942
+ var SETTINGS_SUFFIX = ".settings.json";
3943
+ var MISSION_TAG_PREFIX = "mission:";
3944
+ var MISSION_ID_METADATA_KEY = "missionId";
3945
+ var DECOMP_SESSION_TYPE_TAG = "decompSessionType";
3946
+ var DECOMP_SESSION_TYPE_METADATA_KEY = "value";
3947
+ var LF = 10;
3948
+ var CR = 13;
3949
+ var SPACE = 32;
3950
+ var TAB = 9;
3951
+ var PARSE_OVERSAMPLE = 20;
3952
+ function readFileBuffer(filePath) {
3953
+ try {
3954
+ return fs3.readFileSync(filePath);
3955
+ } catch {
3956
+ return null;
3957
+ }
3958
+ }
3959
+ function parseJsonBuffer(buf) {
3960
+ try {
3961
+ return JSON.parse(buf.toString("utf-8"));
3962
+ } catch {
3963
+ return null;
3964
+ }
3965
+ }
3966
+ function scanBufferForLines(buf) {
3967
+ let nonEmptyLineCount = 0;
3968
+ let firstLineEnd = -1;
3969
+ let currentLineHasContent = false;
3970
+ for (let i = 0; i < buf.length; i++) {
3971
+ const ch = buf[i];
3972
+ if (ch === LF) {
3973
+ if (currentLineHasContent) nonEmptyLineCount++;
3974
+ if (firstLineEnd === -1) firstLineEnd = i;
3975
+ currentLineHasContent = false;
3976
+ } else if (ch !== CR && ch !== SPACE && ch !== TAB) {
3977
+ currentLineHasContent = true;
3978
+ }
3979
+ }
3980
+ if (currentLineHasContent) nonEmptyLineCount++;
3981
+ const end = firstLineEnd === -1 ? buf.length : firstLineEnd > 0 && buf[firstLineEnd - 1] === CR ? firstLineEnd - 1 : firstLineEnd;
3982
+ return {
3983
+ firstLine: buf.subarray(0, end),
3984
+ nonEmptyLineCount
3985
+ };
3986
+ }
3987
+ function loadFavorites(sessionsDir) {
3988
+ const buf = readFileBuffer(path2.join(sessionsDir, FAVORITES_FILE));
3989
+ if (!buf) return /* @__PURE__ */ new Set();
3990
+ const parsed = parseJsonBuffer(buf);
3991
+ if (!Array.isArray(parsed)) return /* @__PURE__ */ new Set();
3992
+ return new Set(parsed.filter((id) => typeof id === "string"));
3993
+ }
3994
+ function loadSettingsFile(directory, sessionId) {
3995
+ const buf = readFileBuffer(
3996
+ path2.join(directory, `${sessionId}${SETTINGS_SUFFIX}`)
3997
+ );
3998
+ if (!buf) return null;
3999
+ const parsed = parseJsonBuffer(buf);
4000
+ if (parsed === null) return null;
4001
+ const result = SessionSettingsFileSchema.safeParse(parsed);
4002
+ return result.success ? result.data : null;
4003
+ }
4004
+ function getMissionMetadataFromTags(settings) {
4005
+ if (!settings?.tags) return {};
4006
+ const missionTag = settings.tags.find(
4007
+ (tag) => tag.name.startsWith(MISSION_TAG_PREFIX)
4008
+ );
4009
+ const roleTag = settings.tags.find(
4010
+ (tag) => tag.name === DECOMP_SESSION_TYPE_TAG
4011
+ );
4012
+ return {
4013
+ decompMissionId: missionTag?.metadata?.[MISSION_ID_METADATA_KEY],
4014
+ decompSessionType: roleTag?.metadata?.[DECOMP_SESSION_TYPE_METADATA_KEY]
4015
+ };
4016
+ }
4017
+ function parseSessionFile(candidate, ctx) {
4018
+ const buf = readFileBuffer(candidate.sessionPath);
4019
+ if (!buf) return null;
4020
+ const scanned = scanBufferForLines(buf);
4021
+ const firstParsed = parseJsonBuffer(scanned.firstLine);
4022
+ if (firstParsed === null) return null;
4023
+ const firstResult = SessionStartEventSchema.safeParse(firstParsed);
4024
+ if (!firstResult.success) return null;
4025
+ const summary = firstResult.data;
4026
+ if (ctx.requiredCwd !== void 0 && (summary.cwd === void 0 || path2.resolve(summary.cwd) !== ctx.requiredCwd)) {
4027
+ return null;
4028
+ }
4029
+ const settingsName = `${candidate.sessionId}${SETTINGS_SUFFIX}`;
4030
+ const settings = candidate.siblingNames.has(settingsName) ? loadSettingsFile(candidate.directory, candidate.sessionId) : null;
4031
+ if (settings?.archivedAt) return null;
4032
+ const tagMeta = getMissionMetadataFromTags(settings);
4033
+ const decompSessionType = summary.decompSessionType ?? SessionStartDecompSessionTypeSchema.safeParse(tagMeta.decompSessionType).data;
4034
+ const messageCount = Math.max(0, scanned.nonEmptyLineCount - 1);
4035
+ return {
4036
+ id: candidate.sessionId,
4037
+ title: summary.title,
4038
+ owner: summary.owner ?? "",
4039
+ messageCount,
4040
+ modifiedTime: candidate.stats.mtime,
4041
+ createdTime: candidate.stats.birthtime || candidate.stats.ctime,
4042
+ isFavorite: ctx.favorites.has(candidate.sessionId),
4043
+ cwd: summary.cwd,
4044
+ decompSessionType,
4045
+ decompMissionId: tagMeta.decompMissionId ?? summary.decompMissionId
4046
+ };
4047
+ }
4048
+ function readDirEntries(directory) {
4049
+ try {
4050
+ return fs3.readdirSync(directory, { withFileTypes: true });
4051
+ } catch {
4052
+ return [];
4053
+ }
4054
+ }
4055
+ function collectCandidates(directory, entries) {
4056
+ const siblingNames = new Set(entries.map((e) => e.name));
4057
+ const candidates = [];
4058
+ for (const entry of entries) {
4059
+ if (entry.isDirectory()) continue;
4060
+ if (!entry.name.endsWith(SESSION_EXTENSION)) continue;
4061
+ const sessionPath = path2.join(directory, entry.name);
4062
+ let stats;
4063
+ try {
4064
+ stats = fs3.statSync(sessionPath);
4065
+ } catch {
4066
+ continue;
4067
+ }
4068
+ candidates.push({
4069
+ sessionId: entry.name.slice(0, -SESSION_EXTENSION.length),
4070
+ sessionPath,
4071
+ directory,
4072
+ siblingNames,
4073
+ stats
4074
+ });
4075
+ }
4076
+ return candidates;
4077
+ }
4078
+ function parseUpTo(candidates, ctx, limit) {
4079
+ const out = [];
4080
+ for (const candidate of candidates) {
4081
+ if (limit !== void 0 && out.length >= limit) break;
4082
+ const metadata = parseSessionFile(candidate, ctx);
4083
+ if (metadata) out.push(metadata);
4084
+ }
4085
+ return out;
4086
+ }
4087
+ function sanitizePathToDirectoryName(cwd) {
4088
+ let expandedPath = cwd;
4089
+ if (cwd.startsWith("~/") || cwd === "~") {
4090
+ expandedPath = path2.join(os.homedir(), cwd.slice(1));
4091
+ }
4092
+ const absolutePath = path2.resolve(expandedPath);
4093
+ let canonicalPath = absolutePath;
4094
+ try {
4095
+ canonicalPath = fs3.realpathSync(absolutePath);
4096
+ } catch {
4097
+ canonicalPath = absolutePath;
4098
+ }
4099
+ const normalized = canonicalPath.replace(/[\\/]+$/, "");
4100
+ if (process.platform === "win32") {
4101
+ return `-${normalized.replace(/^([A-Z]):/i, "$1").replace(/[\\/]+/g, "-")}`;
4102
+ }
4103
+ return `-${normalized.replace(/^\/+/, "").replace(/\/+/g, "-")}`;
4104
+ }
4105
+ function getDefaultSessionsDir() {
4106
+ return path2.join(os.homedir(), ".factory", "sessions");
4107
+ }
4108
+ async function listSessions(options = {}) {
4109
+ const sessionsDir = options.sessionsDir ?? getDefaultSessionsDir();
4110
+ const favorites = loadFavorites(sessionsDir);
4111
+ const rootEntries = readDirEntries(sessionsDir);
4112
+ const legacyCandidates = collectCandidates(sessionsDir, rootEntries);
4113
+ const projectCandidates = [];
4114
+ let requiredCwd;
4115
+ if (options.fetchOutsideCWD) {
4116
+ for (const entry of rootEntries) {
4117
+ if (!entry.isDirectory()) continue;
4118
+ if (!entry.name.startsWith("-")) continue;
4119
+ const dir = path2.join(sessionsDir, entry.name);
4120
+ projectCandidates.push(...collectCandidates(dir, readDirEntries(dir)));
4121
+ }
4122
+ } else {
4123
+ const normalizedCwd = path2.resolve(options.cwd ?? process.cwd());
4124
+ requiredCwd = normalizedCwd;
4125
+ const projectDir = path2.join(
4126
+ sessionsDir,
4127
+ sanitizePathToDirectoryName(normalizedCwd)
4128
+ );
4129
+ projectCandidates.push(
4130
+ ...collectCandidates(projectDir, readDirEntries(projectDir))
4131
+ );
4132
+ }
4133
+ const byMtimeDesc = (a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime();
4134
+ projectCandidates.sort(byMtimeDesc);
4135
+ legacyCandidates.sort(byMtimeDesc);
4136
+ const parseLimit = options.limit !== void 0 && options.limit >= 0 ? options.limit + PARSE_OVERSAMPLE : void 0;
4137
+ const ctx = { favorites };
4138
+ const legacyCtx = requiredCwd !== void 0 ? { favorites, requiredCwd } : ctx;
4139
+ const projectSessions = parseUpTo(projectCandidates, ctx, parseLimit);
4140
+ const legacySessions = parseUpTo(legacyCandidates, legacyCtx, parseLimit);
4141
+ const byId = /* @__PURE__ */ new Map();
4142
+ for (const session of [...projectSessions, ...legacySessions]) {
4143
+ const existing = byId.get(session.id);
4144
+ if (!existing || session.modifiedTime.getTime() > existing.modifiedTime.getTime()) {
4145
+ byId.set(session.id, session);
4146
+ }
4147
+ }
4148
+ const sorted = Array.from(byId.values()).sort(
4149
+ (a, b) => b.modifiedTime.getTime() - a.modifiedTime.getTime()
4150
+ );
4151
+ if (options.limit !== void 0 && options.limit >= 0) {
4152
+ return sorted.slice(0, options.limit);
4153
+ }
4154
+ return sorted;
4155
+ }
4156
+ export {
4157
+ AbortError,
4158
+ AddMcpServerRequestParamsSchema,
4159
+ AddMcpServerRequestSchema,
4160
+ AddMcpServerResponseSchema,
4161
+ AddMcpServerResultSchema,
4162
+ AddUserMessageRequestParamsSchema,
4163
+ AddUserMessageRequestSchema,
4164
+ AddUserMessageResponseSchema,
4165
+ AddUserMessageResultSchema,
4166
+ ApplyPatchToolConfirmationDetailsSchema,
4167
+ AskUserCollectedAnswerSchema,
4168
+ AskUserConfirmationDetailsSchema,
4169
+ AskUserQuestionSchema,
4170
+ AskUserRequestParamsSchema,
4171
+ AskUserRequestSchema,
4172
+ AskUserResponseSchema,
4173
+ AskUserResultSchema,
4174
+ AssistantTextCompleteNotificationSchema,
4175
+ AssistantTextDeltaNotificationSchema,
4176
+ AuthenticateMcpServerRequestParamsSchema,
4177
+ AuthenticateMcpServerRequestSchema,
4178
+ AuthenticateMcpServerResponseSchema,
4179
+ AuthenticateMcpServerResultSchema,
4180
+ AutonomyLevel,
4181
+ AvailableModelConfigSchema,
4182
+ Base64ImageSourceSchema,
4183
+ BaseNotificationSchema,
4184
+ BaseRequestSchema,
4185
+ BaseResponseFailureSchema,
4186
+ BaseResponseSuccessSchema,
4187
+ CLI_JSONRPC_CHILD_SPAWN_LATENCY_METRIC,
4188
+ COMPACTION_TIMEOUT,
4189
+ CancelMcpAuthRequestParamsSchema,
4190
+ CancelMcpAuthRequestSchema,
4191
+ CancelMcpAuthResponseSchema,
4192
+ CancelMcpAuthResultSchema,
4193
+ ChangeWorkingDirectoryRequestParamsSchema,
4194
+ ChangeWorkingDirectoryRequestSchema,
4195
+ ChangeWorkingDirectoryResponseSchema,
4196
+ ChangeWorkingDirectoryResultSchema,
4197
+ ClearMcpAuthRequestParamsSchema,
4198
+ ClearMcpAuthRequestSchema,
4199
+ ClearMcpAuthResponseSchema,
4200
+ ClearMcpAuthResultSchema,
4201
+ CliRequestOrNotificationSchema,
4202
+ ClientDestroyedError,
4203
+ ClientRequestSchema,
4204
+ ClientUiSurface,
4205
+ CloseSessionRequestParamsSchema,
4206
+ CloseSessionRequestSchema,
4207
+ CloseSessionResponseSchema,
4208
+ CloseSessionResultSchema,
4209
+ CompactSessionRequestParamsSchema,
4210
+ CompactSessionRequestSchema,
4211
+ CompactSessionResponseSchema,
4212
+ CompactSessionResultSchema,
4213
+ ComputeLimitExceededError,
4214
+ ComputerConnectAttemptTrigger,
4215
+ ComputerConnectStartType,
4216
+ ComputerListResponseSchema,
4217
+ ComputerMetricSchema,
4218
+ ComputerMetricsResponseSchema,
4219
+ ComputerSchema,
4220
+ ConcurrentStreamError,
4221
+ ConnectionClosedError,
4222
+ ConnectionError,
4223
+ ConnectionFailureReason,
4224
+ ContentBlockSchema,
4225
+ ContextBreakdownCategorySchema,
4226
+ GetContextBreakdownResultSchema as ContextBreakdownResultSchema,
4227
+ ContextStatsAccuracy,
4228
+ ContextStatsSchema,
4229
+ CreateMessageNotificationSchema,
4230
+ CreateToolConfirmationDetailsSchema,
4231
+ DEFAULT_LOCAL_DAEMON_WS_URL,
4232
+ DEFAULT_REQUEST_TIMEOUT,
4233
+ DaemonAuthenticationMode,
4234
+ DaemonClient,
4235
+ MetaError as DaemonClientMetaError,
4236
+ DaemonDroidEvent,
4237
+ DaemonRequestPermissionSchema,
4238
+ DaemonSessionController,
4239
+ DecompSessionType,
4240
+ DiscoveredIssueSchema,
4241
+ DismissalRecordSchema,
4242
+ DismissalType,
4243
+ DocumentBlockSchema,
4244
+ DocumentSourceSchema,
4245
+ DroidClient,
4246
+ DroidClientError,
4247
+ DroidClientEvent,
4248
+ DroidClientMethod,
4249
+ DroidErrorType,
4250
+ DroidEvent,
4251
+ DroidHookEventSchema,
4252
+ DroidHookExecutionResultSchema,
4253
+ DroidHookOutputSchema,
4254
+ DroidHookSpecificOutputSchema,
4255
+ DroidInteractionMode,
4256
+ DroidMessageType,
4257
+ DroidProcessManager,
4258
+ DroidProcessMode,
4259
+ DroidServerMethod,
4260
+ DroidSession,
4261
+ DroidWorkingState,
4262
+ DroidWorkingStateChangedNotificationSchema,
4263
+ EditToolConfirmationDetailsSchema,
4264
+ EmptyResultSchema,
4265
+ ErrorDetailSchema,
4266
+ ErrorNotificationSchema,
4267
+ ExecToolInfoSchema,
4268
+ ExecuteRewindRequestParamsSchema,
4269
+ ExecuteRewindRequestSchema,
4270
+ ExecuteRewindResponseSchema,
4271
+ ExecuteRewindResultSchema,
4272
+ ExecuteToolConfirmationDetailsSchema,
4273
+ ExitSpecModeConfirmationDetailsSchema,
4274
+ FACTORY_CLIENT_HEADER,
4275
+ FACTORY_CLIENT_VERSION,
4276
+ FACTORY_PROTOCOL_VERSION2 as FACTORY_PROTOCOL_VERSION,
4277
+ FactoryDaemonTransport,
4278
+ FactoryDroidMessageRole,
4279
+ FactoryDroidMessageSchema,
4280
+ FeatureStatus,
4281
+ FeatureSuccessState,
4282
+ FeatureSuccessStateSchema,
4283
+ ForkSessionRequestParamsSchema,
4284
+ ForkSessionRequestSchema,
4285
+ ForkSessionResponseSchema,
4286
+ ForkSessionResultSchema,
4287
+ GetContextStatsRequestParamsSchema,
4288
+ GetContextStatsRequestSchema,
4289
+ GetContextStatsResponseSchema,
4290
+ ContextStatsSchema as GetContextStatsResultSchema,
4291
+ GetRewindInfoRequestParamsSchema,
4292
+ GetRewindInfoRequestSchema,
4293
+ GetRewindInfoResponseSchema,
4294
+ GetRewindInfoResultSchema,
4295
+ GitRepoInfoSchema,
4296
+ HandoffItemsDismissedEntrySchema,
4297
+ HandoffSchema,
4298
+ HookCommandSchema,
4299
+ HookExecutionCompletedNotificationSchema,
4300
+ HookExecutionStartedNotificationSchema,
4301
+ HookResultSchema,
4302
+ HttpHeaderSchema,
4303
+ HttpMcpSchema as HttpMcpConfigSchema,
4304
+ IPC_DAEMON_URL,
4305
+ ImageBlockSchema,
4306
+ InProcessDaemonClientTransport,
4307
+ InitializeSessionRequestParamsSchema,
4308
+ InitializeSessionRequestSchema,
4309
+ InitializeSessionResponseSchema,
4310
+ InitializeSessionResultSchema2 as InitializeSessionResultSchema,
4311
+ InteractiveCheckSchema,
4312
+ InterruptSessionRequestParamsSchema,
4313
+ InterruptSessionRequestSchema,
4314
+ InterruptSessionResponseSchema,
4315
+ InterruptSessionResultSchema,
4316
+ InvalidSessionCwdError,
4317
+ IpcDaemonClientTransport,
4318
+ IssueSeverity,
4319
+ JSONRPC_VERSION3 as JSONRPC_VERSION,
4320
+ JsonArraySchema,
4321
+ JsonObjectSchema,
4322
+ JsonRpcEnvelopeSchema,
4323
+ JsonRpcErrorCode,
4324
+ JsonRpcErrorSchema,
4325
+ JsonRpcMessageSchema,
4326
+ JsonRpcMessageType,
4327
+ JsonRpcNotificationSchema,
4328
+ JsonRpcRequestError,
4329
+ JsonRpcRequestSchema,
4330
+ JsonRpcResponseFailureSchema,
4331
+ JsonRpcResponseSchema,
4332
+ JsonRpcResponseSuccessSchema,
4333
+ JsonValueSchema,
4334
+ KillWorkerSessionRequestParamsSchema,
4335
+ KillWorkerSessionRequestSchema,
4336
+ KillWorkerSessionResponseSchema,
4337
+ KillWorkerSessionResultSchema,
4338
+ LEGACY_FACTORY_API_VERSION2 as LEGACY_FACTORY_API_VERSION,
4339
+ LOCAL_MACHINE_ID,
4340
+ ListMcpRegistryRequestParamsSchema,
4341
+ ListMcpRegistryRequestSchema,
4342
+ ListMcpRegistryResponseSchema,
4343
+ ListMcpRegistryResultSchema,
4344
+ ListMcpServersRequestParamsSchema,
4345
+ ListMcpServersRequestSchema,
4346
+ ListMcpServersResponseSchema,
4347
+ ListMcpServersResultSchema,
4348
+ ListMcpToolsRequestParamsSchema,
4349
+ ListMcpToolsRequestSchema,
4350
+ ListMcpToolsResponseSchema,
4351
+ ListMcpToolsResultSchema,
4352
+ ListSkillsRequestParamsSchema,
4353
+ ListSkillsRequestSchema,
4354
+ ListSkillsResponseSchema,
4355
+ ListSkillsResultSchema,
4356
+ ListToolsRequestParamsSchema,
4357
+ ListToolsRequestSchema,
4358
+ ListToolsResponseSchema,
4359
+ ListToolsResultSchema,
4360
+ LoadSessionRequestParamsSchema,
4361
+ LoadSessionRequestSchema,
4362
+ LoadSessionResponseSchema,
4363
+ LoadSessionResultSchema,
4364
+ MACHINE_TYPE_WEBSOCKET_OVERRIDES,
4365
+ MANAGED_COMPUTER_MAX_RETRIES,
4366
+ MCP_AUTH_TIMEOUT,
4367
+ MachineTemplateBuildStatusSchema,
4368
+ MachineTemplateListResponseSchema,
4369
+ MachineTemplateSchema,
4370
+ MachineType,
4371
+ ManagedProcessImpl,
4372
+ McpAuthCompletedNotificationSchema,
4373
+ McpAuthOutcome,
4374
+ McpAuthRequiredNotificationSchema,
4375
+ McpHttpServerConfigFieldsSchema,
4376
+ McpRegistryServerSchema,
4377
+ McpServerConfigSchema,
4378
+ McpServerStatus,
4379
+ McpServerStatusInfoSchema,
4380
+ McpServerType,
4381
+ McpSseServerConfigFieldsSchema,
4382
+ McpStatus,
4383
+ McpStatusChangedNotificationSchema,
4384
+ McpStatusSummarySchema,
4385
+ McpStdioServerConfigFieldsSchema,
4386
+ McpToolConfirmationDetailsSchema,
4387
+ McpToolInfoSchema,
4388
+ McpToolInputSchemaSchema,
4389
+ MessageVisibility,
4390
+ Metric,
4391
+ MilestoneValidationTriggeredEntrySchema,
4392
+ MissionAcceptedEntrySchema,
4393
+ MissionFeatureSchema,
4394
+ MissionFeaturesChangedNotificationSchema,
4395
+ MissionHeartbeatNotificationSchema,
4396
+ MissionPausedEntrySchema,
4397
+ MissionProgressEntryNotificationSchema,
4398
+ MissionResumedEntrySchema,
4399
+ MissionRunStartedEntrySchema,
4400
+ MissionStateSchema as MissionSnapshotSchema,
4401
+ MissionState,
4402
+ MissionStateChangedNotificationSchema,
4403
+ MissionWorkerCompletedNotificationSchema,
4404
+ MissionWorkerStartedNotificationSchema,
4405
+ ModelProvider,
4406
+ MultiMissionStateManager,
4407
+ MultiSessionStateManager,
4408
+ OtelTracing,
4409
+ OutputFormatSchema,
4410
+ OutputFormatType,
4411
+ PermissionResolvedNotificationSchema,
4412
+ ProcessExitError,
4413
+ ProcessTransport,
4414
+ ProgressLogEntrySchema,
4415
+ ProgressLogEntryType,
4416
+ ProposeMissionConfirmationDetailsSchema,
4417
+ ProtocolError,
4418
+ QueuedUserMessageDisplayGroup,
4419
+ QueuedUserMessageKind,
4420
+ REWIND_TIMEOUT,
4421
+ ReasoningEffort,
4422
+ RedactedThinkingBlockSchema,
4423
+ RefreshComputerResponseSchema,
4424
+ RelayConnectionError,
4425
+ RemoteSessionListResponseSchema,
4426
+ RemoteSessionSchema,
4427
+ RemoveMcpServerRequestParamsSchema,
4428
+ RemoveMcpServerRequestSchema,
4429
+ RemoveMcpServerResponseSchema,
4430
+ RemoveMcpServerResultSchema,
4431
+ RenameSessionRequestParamsSchema,
4432
+ RenameSessionRequestSchema,
4433
+ RenameSessionResponseSchema,
4434
+ RenameSessionResultSchema,
4435
+ RequestPermissionRequestParamsSchema,
4436
+ RequestPermissionRequestSchema,
4437
+ RequestPermissionResponseSchema,
4438
+ RequestPermissionResultSchema,
4439
+ RewindEvictedFileSchema,
4440
+ RewindFileCreationSchema,
4441
+ RewindFileSnapshotSchema,
4442
+ SDK_TAG,
4443
+ SDK_VERSION,
4444
+ SESSION_INIT_TIMEOUT,
4445
+ SLACK_DELEGATION_MAX_RETRIES,
4446
+ SdkMcpServer,
4447
+ ServerRequestHandlerType,
4448
+ SessionError,
4449
+ SessionMetadataSchema,
4450
+ SessionNotFoundError,
4451
+ SessionNotificationParamsSchema,
4452
+ SessionNotificationPayloadSchema,
4453
+ SessionNotificationSchema,
4454
+ SessionNotificationSchemaList,
4455
+ SessionNotificationType,
4456
+ SessionPlatform,
4457
+ SessionReplacedError,
4458
+ SessionReplacementError,
4459
+ SessionSettingsFileSchema,
4460
+ SessionSettingsSchema,
4461
+ SessionSourceSchema,
4462
+ SessionStartEventSchema,
4463
+ SessionTagSchema,
4464
+ SessionTitleUpdatedNotificationSchema,
4465
+ SessionTokenUsageChangedNotificationSchema,
4466
+ SetSkillDisabledRequestParamsSchema,
4467
+ SetSkillDisabledRequestSchema,
4468
+ SetSkillDisabledResponseSchema,
4469
+ SetSkillDisabledResultSchema,
4470
+ SettingsLevel,
4471
+ SettingsUpdatedNotificationSchema,
4472
+ SettingsUpdatedPayloadSchema,
4473
+ SkillDeviationSchema,
4474
+ SkillFeedbackSchema,
4475
+ SkillInfoSchema,
4476
+ SkillLocation,
4477
+ SkillResourceSchema,
4478
+ SpanAttribute,
4479
+ SpanEvent,
4480
+ SpanName,
4481
+ SseMcpSchema as SseMcpConfigSchema,
4482
+ StartMissionRunConfirmationDetailsSchema,
4483
+ StdioMcpSchema as StdioMcpConfigSchema,
4484
+ StreamStateTracker,
4485
+ StructuredOutputErrorSchema,
4486
+ StructuredOutputNotificationSchema,
4487
+ SubmitBugReportRequestParamsSchema,
4488
+ SubmitBugReportRequestSchema,
4489
+ SubmitBugReportResponseSchema,
4490
+ SubmitBugReportResultSchema,
4491
+ SubmitMcpAuthCodeRequestParamsSchema,
4492
+ SubmitMcpAuthCodeRequestSchema,
4493
+ SubmitMcpAuthCodeResponseSchema,
4494
+ SubmitMcpAuthCodeResultSchema,
4495
+ SuccessResultSchema,
4496
+ TestCaseSchema,
4497
+ TestFileSchema,
4498
+ TestsSchema,
4499
+ TextBlockSchema,
4500
+ ThinkingBlockSchema,
4501
+ ThinkingTextCompleteNotificationSchema,
4502
+ ThinkingTextDeltaNotificationSchema,
4503
+ TimeoutError,
4504
+ ToggleMcpServerRequestParamsSchema,
4505
+ ToggleMcpServerRequestSchema,
4506
+ ToggleMcpServerResponseSchema,
4507
+ ToggleMcpServerResultSchema,
4508
+ ToggleMcpToolRequestParamsSchema,
4509
+ ToggleMcpToolRequestSchema,
4510
+ ToggleMcpToolResponseSchema,
4511
+ ToggleMcpToolResultSchema,
4512
+ TokenUsageSchema,
4513
+ ToolCallNotificationSchema,
4514
+ ToolConfirmationDetailsSchema,
4515
+ ToolConfirmationInfoSchema,
4516
+ ToolConfirmationListItemSchema,
4517
+ ToolConfirmationOutcome,
4518
+ ToolConfirmationType,
4519
+ ToolProgressUpdateNotificationSchema,
4520
+ ToolProgressUpdateSchema,
4521
+ ToolResultSchema as ToolResultBlockSchema,
4522
+ ToolResultNotificationSchema,
4523
+ ToolSelectionOverridesSchema,
4524
+ ToolUseSchema as ToolUseBlockSchema,
4525
+ ToolUseSchema2 as ToolUseSchema,
4526
+ TraceContextMetaSchema,
4527
+ TransportDirection,
4528
+ TunnelConnection,
4529
+ UpdateSessionSettingsRequestParamsSchema,
4530
+ UpdateSessionSettingsRequestSchema,
4531
+ UpdateSessionSettingsResponseSchema,
4532
+ UpdateSessionSettingsResultSchema,
4533
+ VerificationCommandSchema,
4534
+ VerificationSchema,
4535
+ WINDOWS_JOB_OBJECT_ERROR_MARKER,
4536
+ WebSocketConnectionError,
4537
+ WebSocketDaemonTransport,
4538
+ WorkerCompletedEntrySchema,
4539
+ WorkerFailedEntrySchema,
4540
+ WorkerPausedEntrySchema,
4541
+ WorkerSelectedFeatureEntrySchema,
4542
+ WorkerStartedEntrySchema,
4543
+ WorkerStateInfoSchema,
4544
+ __resetTransportLoggerForTests,
4545
+ buildUserMessageContentBlocks,
4546
+ configureDaemonCoreDeps,
4547
+ connectAndAuthenticate,
4548
+ connectToDaemon,
4549
+ connectWithRetry,
4550
+ convertNotificationToStreamMessage,
4551
+ createComputer,
4552
+ createResponseSchema,
4553
+ createSdkMcpServer,
4554
+ createSession,
4555
+ createWebSocketDaemonClient,
4556
+ defaultDaemonCoreDeps,
4557
+ deleteComputer,
4558
+ filterMessagesForUI,
4559
+ getComputer,
4560
+ getComputerByName,
4561
+ getComputerMetrics,
4562
+ getMachineTemplate,
4563
+ getPermissionToolInputForDisplay,
4564
+ getQueuedUserMessageDisplayGroup,
4565
+ getQueuedUserMessageReviewPriority,
4566
+ getSubagentCallingMetadata,
4567
+ getToolResultBlocks,
4568
+ getToolResultToolUseId,
4569
+ hasDecoupledInteractionSettings,
4570
+ hasSubagentSessionTag,
4571
+ inspectJsonRpcEnvelope,
4572
+ isDaemonQueuedMessageKind,
4573
+ isPendingToolResultMarker,
4574
+ isPersistedHookMessage,
4575
+ isReviewableQueuedMessageKind,
4576
+ isTransportLoggingEnabled,
4577
+ listComputers,
4578
+ listMachineTemplates,
4579
+ listRemoteSessions,
4580
+ listSessions,
4581
+ logTransportMessage,
4582
+ machineTypeToMachineConnectionType,
4583
+ noopLogger,
4584
+ orderMessagesByParentChain,
4585
+ recordComputerConnectSli,
4586
+ refreshComputer,
4587
+ repairParentChainCorruption,
4588
+ resolveExecCoreDeps,
4589
+ restartComputer,
4590
+ resumeSession,
4591
+ retryInstallDeps,
4592
+ retryWithLogger,
4593
+ run,
4594
+ spawnWithWindowsJobObjectRetry,
4595
+ sumTokenUsage,
4596
+ summarizeSessionToolUsage,
4597
+ toError,
4598
+ tool,
4599
+ updateComputer
4600
+ };
4601
+ //# sourceMappingURL=node.mjs.map