@factory/droid-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,3832 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AddMcpServerRequestParamsSchema: () => AddMcpServerRequestParamsSchema,
34
+ AddMcpServerRequestSchema: () => AddMcpServerRequestSchema,
35
+ AddMcpServerResponseSchema: () => AddMcpServerResponseSchema,
36
+ AddMcpServerResultSchema: () => AddMcpServerResultSchema,
37
+ AddUserMessageRequestParamsSchema: () => AddUserMessageRequestParamsSchema,
38
+ AddUserMessageRequestSchema: () => AddUserMessageRequestSchema,
39
+ AddUserMessageResponseSchema: () => AddUserMessageResponseSchema,
40
+ AddUserMessageResultSchema: () => AddUserMessageResultSchema,
41
+ ApplyPatchToolConfirmationDetailsSchema: () => ApplyPatchToolConfirmationDetailsSchema,
42
+ AskUserCollectedAnswerSchema: () => AskUserCollectedAnswerSchema,
43
+ AskUserConfirmationDetailsSchema: () => AskUserConfirmationDetailsSchema,
44
+ AskUserQuestionSchema: () => AskUserQuestionSchema,
45
+ AskUserRequestParamsSchema: () => AskUserRequestParamsSchema,
46
+ AskUserRequestSchema: () => AskUserRequestSchema,
47
+ AskUserResponseSchema: () => AskUserResponseSchema,
48
+ AskUserResultSchema: () => AskUserResultSchema,
49
+ AssistantTextDeltaNotificationSchema: () => AssistantTextDeltaNotificationSchema,
50
+ AuthenticateMcpServerRequestParamsSchema: () => AuthenticateMcpServerRequestParamsSchema,
51
+ AuthenticateMcpServerRequestSchema: () => AuthenticateMcpServerRequestSchema,
52
+ AuthenticateMcpServerResponseSchema: () => AuthenticateMcpServerResponseSchema,
53
+ AuthenticateMcpServerResultSchema: () => AuthenticateMcpServerResultSchema,
54
+ AutonomyLevel: () => AutonomyLevel,
55
+ AutonomyMode: () => AutonomyMode,
56
+ AvailableModelConfigSchema: () => AvailableModelConfigSchema,
57
+ Base64ImageSourceSchema: () => Base64ImageSourceSchema,
58
+ BaseNotificationSchema: () => BaseNotificationSchema,
59
+ BaseRequestSchema: () => BaseRequestSchema,
60
+ BaseResponseFailureSchema: () => BaseResponseFailureSchema,
61
+ BaseResponseSuccessSchema: () => BaseResponseSuccessSchema,
62
+ CancelMcpAuthRequestParamsSchema: () => CancelMcpAuthRequestParamsSchema,
63
+ CancelMcpAuthRequestSchema: () => CancelMcpAuthRequestSchema,
64
+ CancelMcpAuthResponseSchema: () => CancelMcpAuthResponseSchema,
65
+ CancelMcpAuthResultSchema: () => CancelMcpAuthResultSchema,
66
+ ClearMcpAuthRequestParamsSchema: () => ClearMcpAuthRequestParamsSchema,
67
+ ClearMcpAuthRequestSchema: () => ClearMcpAuthRequestSchema,
68
+ ClearMcpAuthResponseSchema: () => ClearMcpAuthResponseSchema,
69
+ ClearMcpAuthResultSchema: () => ClearMcpAuthResultSchema,
70
+ CliRequestOrNotificationSchema: () => CliRequestOrNotificationSchema,
71
+ ClientRequestSchema: () => ClientRequestSchema,
72
+ ConnectionError: () => ConnectionError,
73
+ ContentBlockSchema: () => ContentBlockSchema,
74
+ CreateMessageNotificationSchema: () => CreateMessageNotificationSchema,
75
+ CreateToolConfirmationDetailsSchema: () => CreateToolConfirmationDetailsSchema,
76
+ DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
77
+ DecompSessionType: () => DecompSessionType,
78
+ DiscoveredIssueSchema: () => DiscoveredIssueSchema,
79
+ DismissalRecordSchema: () => DismissalRecordSchema,
80
+ DismissalType: () => DismissalType,
81
+ DocumentBlockSchema: () => DocumentBlockSchema,
82
+ DocumentSourceSchema: () => DocumentSourceSchema,
83
+ DroidClient: () => DroidClient,
84
+ DroidClientMethod: () => DroidClientMethod,
85
+ DroidErrorType: () => DroidErrorType,
86
+ DroidInteractionMode: () => DroidInteractionMode,
87
+ DroidServerMethod: () => DroidServerMethod,
88
+ DroidSession: () => DroidSession,
89
+ DroidWorkingState: () => DroidWorkingState,
90
+ DroidWorkingStateChangedNotificationSchema: () => DroidWorkingStateChangedNotificationSchema,
91
+ EditToolConfirmationDetailsSchema: () => EditToolConfirmationDetailsSchema,
92
+ ErrorDetailSchema: () => ErrorDetailSchema,
93
+ ErrorNotificationSchema: () => ErrorNotificationSchema,
94
+ ExecuteToolConfirmationDetailsSchema: () => ExecuteToolConfirmationDetailsSchema,
95
+ ExitSpecModeConfirmationDetailsSchema: () => ExitSpecModeConfirmationDetailsSchema,
96
+ FACTORY_CLIENT_HEADER: () => FACTORY_CLIENT_HEADER,
97
+ FACTORY_CLIENT_VERSION: () => FACTORY_CLIENT_VERSION,
98
+ FACTORY_PROTOCOL_VERSION: () => FACTORY_PROTOCOL_VERSION,
99
+ FactoryDroidMessageSchema: () => FactoryDroidMessageSchema,
100
+ FeatureStatus: () => FeatureStatus,
101
+ FeatureSuccessState: () => FeatureSuccessState,
102
+ FeatureSuccessStateSchema: () => FeatureSuccessStateSchema,
103
+ GitRepoInfoSchema: () => GitRepoInfoSchema,
104
+ HandoffItemsDismissedEntrySchema: () => HandoffItemsDismissedEntrySchema,
105
+ HandoffSchema: () => HandoffSchema,
106
+ HttpHeaderSchema: () => HttpHeaderSchema,
107
+ HttpMcpConfigSchema: () => HttpMcpConfigSchema,
108
+ ImageBlockSchema: () => ImageBlockSchema,
109
+ InitializeSessionRequestParamsSchema: () => InitializeSessionRequestParamsSchema,
110
+ InitializeSessionRequestSchema: () => InitializeSessionRequestSchema,
111
+ InitializeSessionResponseSchema: () => InitializeSessionResponseSchema,
112
+ InitializeSessionResultSchema: () => InitializeSessionResultSchema,
113
+ InteractiveCheckSchema: () => InteractiveCheckSchema,
114
+ InterruptSessionRequestParamsSchema: () => InterruptSessionRequestParamsSchema,
115
+ InterruptSessionRequestSchema: () => InterruptSessionRequestSchema,
116
+ InterruptSessionResponseSchema: () => InterruptSessionResponseSchema,
117
+ InterruptSessionResultSchema: () => InterruptSessionResultSchema,
118
+ IssueSeverity: () => IssueSeverity,
119
+ JSONRPC_VERSION: () => JSONRPC_VERSION,
120
+ JsonRpcEnvelopeSchema: () => JsonRpcEnvelopeSchema,
121
+ JsonRpcErrorCode: () => JsonRpcErrorCode,
122
+ JsonRpcErrorSchema: () => JsonRpcErrorSchema,
123
+ JsonRpcMessageSchema: () => JsonRpcMessageSchema,
124
+ JsonRpcMessageType: () => JsonRpcMessageType,
125
+ JsonRpcNotificationSchema: () => JsonRpcNotificationSchema,
126
+ JsonRpcRequestSchema: () => JsonRpcRequestSchema,
127
+ JsonRpcResponseFailureSchema: () => JsonRpcResponseFailureSchema,
128
+ JsonRpcResponseSchema: () => JsonRpcResponseSchema,
129
+ JsonRpcResponseSuccessSchema: () => JsonRpcResponseSuccessSchema,
130
+ KillWorkerSessionRequestParamsSchema: () => KillWorkerSessionRequestParamsSchema,
131
+ KillWorkerSessionRequestSchema: () => KillWorkerSessionRequestSchema,
132
+ KillWorkerSessionResponseSchema: () => KillWorkerSessionResponseSchema,
133
+ KillWorkerSessionResultSchema: () => KillWorkerSessionResultSchema,
134
+ LEGACY_FACTORY_API_VERSION: () => LEGACY_FACTORY_API_VERSION,
135
+ ListMcpRegistryRequestParamsSchema: () => ListMcpRegistryRequestParamsSchema,
136
+ ListMcpRegistryRequestSchema: () => ListMcpRegistryRequestSchema,
137
+ ListMcpRegistryResponseSchema: () => ListMcpRegistryResponseSchema,
138
+ ListMcpRegistryResultSchema: () => ListMcpRegistryResultSchema,
139
+ ListMcpServersRequestParamsSchema: () => ListMcpServersRequestParamsSchema,
140
+ ListMcpServersRequestSchema: () => ListMcpServersRequestSchema,
141
+ ListMcpServersResponseSchema: () => ListMcpServersResponseSchema,
142
+ ListMcpServersResultSchema: () => ListMcpServersResultSchema,
143
+ ListMcpToolsRequestParamsSchema: () => ListMcpToolsRequestParamsSchema,
144
+ ListMcpToolsRequestSchema: () => ListMcpToolsRequestSchema,
145
+ ListMcpToolsResponseSchema: () => ListMcpToolsResponseSchema,
146
+ ListMcpToolsResultSchema: () => ListMcpToolsResultSchema,
147
+ ListSkillsRequestParamsSchema: () => ListSkillsRequestParamsSchema,
148
+ ListSkillsRequestSchema: () => ListSkillsRequestSchema,
149
+ ListSkillsResponseSchema: () => ListSkillsResponseSchema,
150
+ ListSkillsResultSchema: () => ListSkillsResultSchema,
151
+ LoadSessionRequestParamsSchema: () => LoadSessionRequestParamsSchema,
152
+ LoadSessionRequestSchema: () => LoadSessionRequestSchema,
153
+ LoadSessionResponseSchema: () => LoadSessionResponseSchema,
154
+ LoadSessionResultSchema: () => LoadSessionResultSchema,
155
+ MCP_AUTH_TIMEOUT: () => MCP_AUTH_TIMEOUT,
156
+ McpAuthCompletedNotificationSchema: () => McpAuthCompletedNotificationSchema,
157
+ McpAuthOutcome: () => McpAuthOutcome,
158
+ McpAuthRequiredNotificationSchema: () => McpAuthRequiredNotificationSchema,
159
+ McpHttpServerConfigFieldsSchema: () => McpHttpServerConfigFieldsSchema,
160
+ McpRegistryServerSchema: () => McpRegistryServerSchema,
161
+ McpServerConfigSchema: () => McpServerConfigSchema,
162
+ McpServerStatus: () => McpServerStatus,
163
+ McpServerStatusInfoSchema: () => McpServerStatusInfoSchema,
164
+ McpServerType: () => McpServerType,
165
+ McpSseServerConfigFieldsSchema: () => McpSseServerConfigFieldsSchema,
166
+ McpStatus: () => McpStatus,
167
+ McpStatusChangedNotificationSchema: () => McpStatusChangedNotificationSchema,
168
+ McpStatusSummarySchema: () => McpStatusSummarySchema,
169
+ McpStdioServerConfigFieldsSchema: () => McpStdioServerConfigFieldsSchema,
170
+ McpToolConfirmationDetailsSchema: () => McpToolConfirmationDetailsSchema,
171
+ McpToolInfoSchema: () => McpToolInfoSchema,
172
+ McpToolInputSchemaSchema: () => McpToolInputSchemaSchema,
173
+ MilestoneValidationTriggeredEntrySchema: () => MilestoneValidationTriggeredEntrySchema,
174
+ MissionAcceptedEntrySchema: () => MissionAcceptedEntrySchema,
175
+ MissionFeatureSchema: () => MissionFeatureSchema,
176
+ MissionFeaturesChangedNotificationSchema: () => MissionFeaturesChangedNotificationSchema,
177
+ MissionHeartbeatNotificationSchema: () => MissionHeartbeatNotificationSchema,
178
+ MissionPausedEntrySchema: () => MissionPausedEntrySchema,
179
+ MissionProgressEntryNotificationSchema: () => MissionProgressEntryNotificationSchema,
180
+ MissionResumedEntrySchema: () => MissionResumedEntrySchema,
181
+ MissionRunStartedEntrySchema: () => MissionRunStartedEntrySchema,
182
+ MissionSnapshotSchema: () => MissionSnapshotSchema,
183
+ MissionState: () => MissionState,
184
+ MissionStateChangedNotificationSchema: () => MissionStateChangedNotificationSchema,
185
+ MissionWorkerCompletedNotificationSchema: () => MissionWorkerCompletedNotificationSchema,
186
+ MissionWorkerStartedNotificationSchema: () => MissionWorkerStartedNotificationSchema,
187
+ ModelProvider: () => ModelProvider,
188
+ PermissionResolvedNotificationSchema: () => PermissionResolvedNotificationSchema,
189
+ ProcessExitError: () => ProcessExitError,
190
+ ProcessTransport: () => ProcessTransport,
191
+ ProgressLogEntrySchema: () => ProgressLogEntrySchema,
192
+ ProgressLogEntryType: () => ProgressLogEntryType,
193
+ ProposeMissionConfirmationDetailsSchema: () => ProposeMissionConfirmationDetailsSchema,
194
+ ProtocolEngine: () => ProtocolEngine,
195
+ ProtocolError: () => ProtocolError,
196
+ ReasoningEffort: () => ReasoningEffort,
197
+ RedactedThinkingBlockSchema: () => RedactedThinkingBlockSchema,
198
+ RemoveMcpServerRequestParamsSchema: () => RemoveMcpServerRequestParamsSchema,
199
+ RemoveMcpServerRequestSchema: () => RemoveMcpServerRequestSchema,
200
+ RemoveMcpServerResponseSchema: () => RemoveMcpServerResponseSchema,
201
+ RemoveMcpServerResultSchema: () => RemoveMcpServerResultSchema,
202
+ RequestPermissionRequestParamsSchema: () => RequestPermissionRequestParamsSchema,
203
+ RequestPermissionRequestSchema: () => RequestPermissionRequestSchema,
204
+ RequestPermissionResponseSchema: () => RequestPermissionResponseSchema,
205
+ RequestPermissionResultSchema: () => RequestPermissionResultSchema,
206
+ SESSION_INIT_TIMEOUT: () => SESSION_INIT_TIMEOUT,
207
+ SessionError: () => SessionError,
208
+ SessionNotFoundError: () => SessionNotFoundError,
209
+ SessionNotificationParamsSchema: () => SessionNotificationParamsSchema,
210
+ SessionNotificationPayloadSchema: () => SessionNotificationPayloadSchema,
211
+ SessionNotificationSchema: () => SessionNotificationSchema,
212
+ SessionNotificationSchemaList: () => SessionNotificationSchemaList,
213
+ SessionNotificationType: () => SessionNotificationType,
214
+ SessionSettingsSchema: () => SessionSettingsSchema,
215
+ SessionSourceSchema: () => SessionSourceSchema,
216
+ SessionTagSchema: () => SessionTagSchema,
217
+ SessionTitleUpdatedNotificationSchema: () => SessionTitleUpdatedNotificationSchema,
218
+ SessionTokenUsageChangedNotificationSchema: () => SessionTokenUsageChangedNotificationSchema,
219
+ SettingsLevel: () => SettingsLevel,
220
+ SettingsUpdatedNotificationSchema: () => SettingsUpdatedNotificationSchema,
221
+ SettingsUpdatedPayloadSchema: () => SettingsUpdatedPayloadSchema,
222
+ SkillDeviationSchema: () => SkillDeviationSchema,
223
+ SkillFeedbackSchema: () => SkillFeedbackSchema,
224
+ SkillInfoSchema: () => SkillInfoSchema,
225
+ SkillLocation: () => SkillLocation,
226
+ SkillResourceSchema: () => SkillResourceSchema,
227
+ SseMcpConfigSchema: () => SseMcpConfigSchema,
228
+ StartMissionRunConfirmationDetailsSchema: () => StartMissionRunConfirmationDetailsSchema,
229
+ StdioMcpConfigSchema: () => StdioMcpConfigSchema,
230
+ StreamStateTracker: () => StreamStateTracker,
231
+ SubmitBugReportRequestParamsSchema: () => SubmitBugReportRequestParamsSchema,
232
+ SubmitBugReportRequestSchema: () => SubmitBugReportRequestSchema,
233
+ SubmitBugReportResponseSchema: () => SubmitBugReportResponseSchema,
234
+ SubmitBugReportResultSchema: () => SubmitBugReportResultSchema,
235
+ SubmitMcpAuthCodeRequestParamsSchema: () => SubmitMcpAuthCodeRequestParamsSchema,
236
+ SubmitMcpAuthCodeRequestSchema: () => SubmitMcpAuthCodeRequestSchema,
237
+ SubmitMcpAuthCodeResponseSchema: () => SubmitMcpAuthCodeResponseSchema,
238
+ SubmitMcpAuthCodeResultSchema: () => SubmitMcpAuthCodeResultSchema,
239
+ TestCaseSchema: () => TestCaseSchema,
240
+ TestFileSchema: () => TestFileSchema,
241
+ TestsSchema: () => TestsSchema,
242
+ TextBlockSchema: () => TextBlockSchema,
243
+ ThinkingBlockSchema: () => ThinkingBlockSchema,
244
+ ThinkingTextDeltaNotificationSchema: () => ThinkingTextDeltaNotificationSchema,
245
+ TimeoutError: () => TimeoutError,
246
+ ToggleMcpServerRequestParamsSchema: () => ToggleMcpServerRequestParamsSchema,
247
+ ToggleMcpServerRequestSchema: () => ToggleMcpServerRequestSchema,
248
+ ToggleMcpServerResponseSchema: () => ToggleMcpServerResponseSchema,
249
+ ToggleMcpServerResultSchema: () => ToggleMcpServerResultSchema,
250
+ ToggleMcpToolRequestParamsSchema: () => ToggleMcpToolRequestParamsSchema,
251
+ ToggleMcpToolRequestSchema: () => ToggleMcpToolRequestSchema,
252
+ ToggleMcpToolResponseSchema: () => ToggleMcpToolResponseSchema,
253
+ ToggleMcpToolResultSchema: () => ToggleMcpToolResultSchema,
254
+ TokenUsageSchema: () => TokenUsageSchema,
255
+ ToolConfirmationDetailsSchema: () => ToolConfirmationDetailsSchema,
256
+ ToolConfirmationInfoSchema: () => ToolConfirmationInfoSchema,
257
+ ToolConfirmationListItemSchema: () => ToolConfirmationListItemSchema,
258
+ ToolConfirmationOutcome: () => ToolConfirmationOutcome,
259
+ ToolConfirmationType: () => ToolConfirmationType,
260
+ ToolProgressUpdateNotificationSchema: () => ToolProgressUpdateNotificationSchema,
261
+ ToolProgressUpdateSchema: () => ToolProgressUpdateSchema,
262
+ ToolResultBlockSchema: () => ToolResultBlockSchema,
263
+ ToolResultNotificationSchema: () => ToolResultNotificationSchema,
264
+ ToolUseBlockSchema: () => ToolUseBlockSchema,
265
+ ToolUseSchema: () => ToolUseSchema,
266
+ TraceContextMetaSchema: () => TraceContextMetaSchema,
267
+ UpdateSessionSettingsRequestParamsSchema: () => UpdateSessionSettingsRequestParamsSchema,
268
+ UpdateSessionSettingsRequestSchema: () => UpdateSessionSettingsRequestSchema,
269
+ UpdateSessionSettingsResponseSchema: () => UpdateSessionSettingsResponseSchema,
270
+ UpdateSessionSettingsResultSchema: () => UpdateSessionSettingsResultSchema,
271
+ VerificationCommandSchema: () => VerificationCommandSchema,
272
+ VerificationSchema: () => VerificationSchema,
273
+ WorkerCompletedEntrySchema: () => WorkerCompletedEntrySchema,
274
+ WorkerFailedEntrySchema: () => WorkerFailedEntrySchema,
275
+ WorkerPausedEntrySchema: () => WorkerPausedEntrySchema,
276
+ WorkerSelectedFeatureEntrySchema: () => WorkerSelectedFeatureEntrySchema,
277
+ WorkerStartedEntrySchema: () => WorkerStartedEntrySchema,
278
+ WorkerStateInfoSchema: () => WorkerStateInfoSchema,
279
+ convertNotificationToStreamMessage: () => convertNotificationToStreamMessage,
280
+ createSession: () => createSession,
281
+ query: () => query,
282
+ resumeSession: () => resumeSession
283
+ });
284
+ module.exports = __toCommonJS(index_exports);
285
+
286
+ // src/schemas/enums.ts
287
+ var DroidServerMethod = /* @__PURE__ */ ((DroidServerMethod2) => {
288
+ DroidServerMethod2["INITIALIZE_SESSION"] = "droid.initialize_session";
289
+ DroidServerMethod2["LOAD_SESSION"] = "droid.load_session";
290
+ DroidServerMethod2["ADD_USER_MESSAGE"] = "droid.add_user_message";
291
+ DroidServerMethod2["INTERRUPT_SESSION"] = "droid.interrupt_session";
292
+ DroidServerMethod2["KILL_WORKER_SESSION"] = "droid.kill_worker_session";
293
+ DroidServerMethod2["UPDATE_SESSION_SETTINGS"] = "droid.update_session_settings";
294
+ DroidServerMethod2["TOGGLE_MCP_SERVER"] = "droid.toggle_mcp_server";
295
+ DroidServerMethod2["AUTHENTICATE_MCP_SERVER"] = "droid.authenticate_mcp_server";
296
+ DroidServerMethod2["CANCEL_MCP_AUTH"] = "droid.cancel_mcp_auth";
297
+ DroidServerMethod2["CLEAR_MCP_AUTH"] = "droid.clear_mcp_auth";
298
+ DroidServerMethod2["ADD_MCP_SERVER"] = "droid.add_mcp_server";
299
+ DroidServerMethod2["REMOVE_MCP_SERVER"] = "droid.remove_mcp_server";
300
+ DroidServerMethod2["LIST_MCP_REGISTRY"] = "droid.list_mcp_registry";
301
+ DroidServerMethod2["LIST_MCP_TOOLS"] = "droid.list_mcp_tools";
302
+ DroidServerMethod2["LIST_MCP_SERVERS"] = "droid.list_mcp_servers";
303
+ DroidServerMethod2["TOGGLE_MCP_TOOL"] = "droid.toggle_mcp_tool";
304
+ DroidServerMethod2["SUBMIT_MCP_AUTH_CODE"] = "droid.submit_mcp_auth_code";
305
+ DroidServerMethod2["LIST_SKILLS"] = "droid.list_skills";
306
+ DroidServerMethod2["SUBMIT_BUG_REPORT"] = "droid.submit_bug_report";
307
+ return DroidServerMethod2;
308
+ })(DroidServerMethod || {});
309
+ var DroidClientMethod = /* @__PURE__ */ ((DroidClientMethod2) => {
310
+ DroidClientMethod2["SESSION_NOTIFICATION"] = "droid.session_notification";
311
+ DroidClientMethod2["REQUEST_PERMISSION"] = "droid.request_permission";
312
+ DroidClientMethod2["ASK_USER"] = "droid.ask_user";
313
+ return DroidClientMethod2;
314
+ })(DroidClientMethod || {});
315
+ var SessionNotificationType = /* @__PURE__ */ ((SessionNotificationType2) => {
316
+ SessionNotificationType2["TOOL_RESULT"] = "tool_result";
317
+ SessionNotificationType2["TOOL_PROGRESS_UPDATE"] = "tool_progress_update";
318
+ SessionNotificationType2["CREATE_MESSAGE"] = "create_message";
319
+ SessionNotificationType2["ERROR"] = "error";
320
+ SessionNotificationType2["DROID_WORKING_STATE_CHANGED"] = "droid_working_state_changed";
321
+ SessionNotificationType2["PERMISSION_RESOLVED"] = "permission_resolved";
322
+ SessionNotificationType2["SETTINGS_UPDATED"] = "settings_updated";
323
+ SessionNotificationType2["SESSION_TITLE_UPDATED"] = "session_title_updated";
324
+ SessionNotificationType2["MCP_STATUS_CHANGED"] = "mcp_status_changed";
325
+ SessionNotificationType2["ASSISTANT_TEXT_DELTA"] = "assistant_text_delta";
326
+ SessionNotificationType2["THINKING_TEXT_DELTA"] = "thinking_text_delta";
327
+ SessionNotificationType2["SESSION_TOKEN_USAGE_CHANGED"] = "session_token_usage_changed";
328
+ SessionNotificationType2["MISSION_STATE_CHANGED"] = "mission_state_changed";
329
+ SessionNotificationType2["MISSION_FEATURES_CHANGED"] = "mission_features_changed";
330
+ SessionNotificationType2["MISSION_PROGRESS_ENTRY"] = "mission_progress_entry";
331
+ SessionNotificationType2["MISSION_HEARTBEAT"] = "mission_heartbeat";
332
+ SessionNotificationType2["MISSION_WORKER_STARTED"] = "mission_worker_started";
333
+ SessionNotificationType2["MISSION_WORKER_COMPLETED"] = "mission_worker_completed";
334
+ SessionNotificationType2["MCP_AUTH_REQUIRED"] = "mcp_auth_required";
335
+ SessionNotificationType2["MCP_AUTH_COMPLETED"] = "mcp_auth_completed";
336
+ return SessionNotificationType2;
337
+ })(SessionNotificationType || {});
338
+ var ToolConfirmationOutcome = /* @__PURE__ */ ((ToolConfirmationOutcome3) => {
339
+ ToolConfirmationOutcome3["ProceedOnce"] = "proceed_once";
340
+ ToolConfirmationOutcome3["ProceedAlways"] = "proceed_always";
341
+ ToolConfirmationOutcome3["ProceedAutoRun"] = "proceed_auto_run";
342
+ ToolConfirmationOutcome3["ProceedAutoRunLow"] = "proceed_auto_run_low";
343
+ ToolConfirmationOutcome3["ProceedAutoRunMedium"] = "proceed_auto_run_medium";
344
+ ToolConfirmationOutcome3["ProceedAutoRunHigh"] = "proceed_auto_run_high";
345
+ ToolConfirmationOutcome3["ProceedEdit"] = "proceed_edit";
346
+ ToolConfirmationOutcome3["Cancel"] = "cancel";
347
+ return ToolConfirmationOutcome3;
348
+ })(ToolConfirmationOutcome || {});
349
+ var ToolConfirmationType = /* @__PURE__ */ ((ToolConfirmationType2) => {
350
+ ToolConfirmationType2["Edit"] = "edit";
351
+ ToolConfirmationType2["Execute"] = "exec";
352
+ ToolConfirmationType2["Create"] = "create";
353
+ ToolConfirmationType2["AskUser"] = "ask_user";
354
+ ToolConfirmationType2["ExitSpecMode"] = "exit_spec_mode";
355
+ ToolConfirmationType2["ProposeMission"] = "propose_mission";
356
+ ToolConfirmationType2["StartMissionRun"] = "start_mission_run";
357
+ ToolConfirmationType2["ApplyPatch"] = "apply_patch";
358
+ ToolConfirmationType2["McpTool"] = "mcp_tool";
359
+ return ToolConfirmationType2;
360
+ })(ToolConfirmationType || {});
361
+ var DroidWorkingState = /* @__PURE__ */ ((DroidWorkingState2) => {
362
+ DroidWorkingState2["Idle"] = "idle";
363
+ DroidWorkingState2["StreamingAssistantMessage"] = "streaming_assistant_message";
364
+ DroidWorkingState2["WaitingForToolConfirmation"] = "waiting_for_tool_confirmation";
365
+ DroidWorkingState2["ExecutingTool"] = "executing_tool";
366
+ DroidWorkingState2["CompactingConversation"] = "compacting_conversation";
367
+ return DroidWorkingState2;
368
+ })(DroidWorkingState || {});
369
+ var DroidErrorType = /* @__PURE__ */ ((DroidErrorType2) => {
370
+ DroidErrorType2["CONNECTION_ERROR"] = "ConnectionError";
371
+ DroidErrorType2["PROTOCOL_ERROR"] = "ProtocolError";
372
+ DroidErrorType2["SESSION_ERROR"] = "SessionError";
373
+ DroidErrorType2["TIMEOUT_ERROR"] = "TimeoutError";
374
+ DroidErrorType2["DROID_CLIENT_ERROR"] = "DroidClientError";
375
+ DroidErrorType2["PROCESS_EXIT_ERROR"] = "ProcessExitError";
376
+ DroidErrorType2["ERROR"] = "Error";
377
+ return DroidErrorType2;
378
+ })(DroidErrorType || {});
379
+ var McpServerStatus = /* @__PURE__ */ ((McpServerStatus2) => {
380
+ McpServerStatus2["Connecting"] = "connecting";
381
+ McpServerStatus2["Connected"] = "connected";
382
+ McpServerStatus2["Disconnected"] = "disconnected";
383
+ McpServerStatus2["Failed"] = "failed";
384
+ McpServerStatus2["Disabled"] = "disabled";
385
+ return McpServerStatus2;
386
+ })(McpServerStatus || {});
387
+ var McpServerType = /* @__PURE__ */ ((McpServerType2) => {
388
+ McpServerType2["Stdio"] = "stdio";
389
+ McpServerType2["Http"] = "http";
390
+ McpServerType2["Sse"] = "sse";
391
+ return McpServerType2;
392
+ })(McpServerType || {});
393
+ var McpStatus = /* @__PURE__ */ ((McpStatus2) => {
394
+ McpStatus2["NotInitialized"] = "not-initialized";
395
+ McpStatus2["Initializing"] = "initializing";
396
+ McpStatus2["Ready"] = "ready";
397
+ McpStatus2["NoServers"] = "no-servers";
398
+ McpStatus2["Failed"] = "failed";
399
+ return McpStatus2;
400
+ })(McpStatus || {});
401
+ var McpAuthOutcome = /* @__PURE__ */ ((McpAuthOutcome3) => {
402
+ McpAuthOutcome3["Success"] = "success";
403
+ McpAuthOutcome3["Cancelled"] = "cancelled";
404
+ McpAuthOutcome3["Failed"] = "failed";
405
+ return McpAuthOutcome3;
406
+ })(McpAuthOutcome || {});
407
+ var DecompSessionType = /* @__PURE__ */ ((DecompSessionType2) => {
408
+ DecompSessionType2["Orchestrator"] = "orchestrator";
409
+ DecompSessionType2["Worker"] = "worker";
410
+ return DecompSessionType2;
411
+ })(DecompSessionType || {});
412
+ var MissionState = /* @__PURE__ */ ((MissionState3) => {
413
+ MissionState3["AwaitingInput"] = "awaiting_input";
414
+ MissionState3["Initializing"] = "initializing";
415
+ MissionState3["Running"] = "running";
416
+ MissionState3["Paused"] = "paused";
417
+ MissionState3["OrchestratorTurn"] = "orchestrator_turn";
418
+ MissionState3["Completed"] = "completed";
419
+ return MissionState3;
420
+ })(MissionState || {});
421
+ var FeatureStatus = /* @__PURE__ */ ((FeatureStatus2) => {
422
+ FeatureStatus2["Pending"] = "pending";
423
+ FeatureStatus2["InProgress"] = "in_progress";
424
+ FeatureStatus2["Completed"] = "completed";
425
+ FeatureStatus2["Cancelled"] = "cancelled";
426
+ return FeatureStatus2;
427
+ })(FeatureStatus || {});
428
+ var FeatureSuccessState = /* @__PURE__ */ ((FeatureSuccessState2) => {
429
+ FeatureSuccessState2["Success"] = "success";
430
+ FeatureSuccessState2["Partial"] = "partial";
431
+ FeatureSuccessState2["Failure"] = "failure";
432
+ return FeatureSuccessState2;
433
+ })(FeatureSuccessState || {});
434
+ var IssueSeverity = /* @__PURE__ */ ((IssueSeverity2) => {
435
+ IssueSeverity2["Blocking"] = "blocking";
436
+ IssueSeverity2["NonBlocking"] = "non_blocking";
437
+ IssueSeverity2["Suggestion"] = "suggestion";
438
+ return IssueSeverity2;
439
+ })(IssueSeverity || {});
440
+ var DismissalType = /* @__PURE__ */ ((DismissalType2) => {
441
+ DismissalType2["DiscoveredIssue"] = "discovered_issue";
442
+ DismissalType2["CriticalContext"] = "critical_context";
443
+ DismissalType2["IncompleteWork"] = "incomplete_work";
444
+ return DismissalType2;
445
+ })(DismissalType || {});
446
+ var ProgressLogEntryType = /* @__PURE__ */ ((ProgressLogEntryType2) => {
447
+ ProgressLogEntryType2["MissionAccepted"] = "mission_accepted";
448
+ ProgressLogEntryType2["MissionPaused"] = "mission_paused";
449
+ ProgressLogEntryType2["MissionResumed"] = "mission_resumed";
450
+ ProgressLogEntryType2["MissionRunStarted"] = "mission_run_started";
451
+ ProgressLogEntryType2["WorkerStarted"] = "worker_started";
452
+ ProgressLogEntryType2["WorkerSelectedFeature"] = "worker_selected_feature";
453
+ ProgressLogEntryType2["WorkerCompleted"] = "worker_completed";
454
+ ProgressLogEntryType2["WorkerFailed"] = "worker_failed";
455
+ ProgressLogEntryType2["WorkerPaused"] = "worker_paused";
456
+ ProgressLogEntryType2["HandoffItemsDismissed"] = "handoff_items_dismissed";
457
+ ProgressLogEntryType2["MilestoneValidationTriggered"] = "milestone_validation_triggered";
458
+ return ProgressLogEntryType2;
459
+ })(ProgressLogEntryType || {});
460
+ var DroidInteractionMode = /* @__PURE__ */ ((DroidInteractionMode2) => {
461
+ DroidInteractionMode2["Auto"] = "auto";
462
+ DroidInteractionMode2["Spec"] = "spec";
463
+ DroidInteractionMode2["AGI"] = "agi";
464
+ return DroidInteractionMode2;
465
+ })(DroidInteractionMode || {});
466
+ var AutonomyLevel = /* @__PURE__ */ ((AutonomyLevel2) => {
467
+ AutonomyLevel2["Off"] = "off";
468
+ AutonomyLevel2["Low"] = "low";
469
+ AutonomyLevel2["Medium"] = "medium";
470
+ AutonomyLevel2["High"] = "high";
471
+ return AutonomyLevel2;
472
+ })(AutonomyLevel || {});
473
+ var AutonomyMode = /* @__PURE__ */ ((AutonomyMode2) => {
474
+ AutonomyMode2["Normal"] = "normal";
475
+ AutonomyMode2["Spec"] = "spec";
476
+ AutonomyMode2["AutoLow"] = "auto-low";
477
+ AutonomyMode2["AutoMedium"] = "auto-medium";
478
+ AutonomyMode2["AutoHigh"] = "auto-high";
479
+ return AutonomyMode2;
480
+ })(AutonomyMode || {});
481
+ var ReasoningEffort = /* @__PURE__ */ ((ReasoningEffort2) => {
482
+ ReasoningEffort2["None"] = "none";
483
+ ReasoningEffort2["Dynamic"] = "dynamic";
484
+ ReasoningEffort2["Off"] = "off";
485
+ ReasoningEffort2["Minimal"] = "minimal";
486
+ ReasoningEffort2["Low"] = "low";
487
+ ReasoningEffort2["Medium"] = "medium";
488
+ ReasoningEffort2["High"] = "high";
489
+ ReasoningEffort2["ExtraHigh"] = "xhigh";
490
+ ReasoningEffort2["Max"] = "max";
491
+ return ReasoningEffort2;
492
+ })(ReasoningEffort || {});
493
+ var ModelProvider = /* @__PURE__ */ ((ModelProvider2) => {
494
+ ModelProvider2["ANTHROPIC"] = "anthropic";
495
+ ModelProvider2["OPENAI"] = "openai";
496
+ ModelProvider2["GENERIC_CHAT_COMPLETION_API"] = "generic-chat-completion-api";
497
+ ModelProvider2["FACTORY"] = "factory";
498
+ ModelProvider2["GOOGLE"] = "google";
499
+ ModelProvider2["XAI"] = "xai";
500
+ ModelProvider2["VOYAGE"] = "voyage";
501
+ return ModelProvider2;
502
+ })(ModelProvider || {});
503
+ var JsonRpcErrorCode = /* @__PURE__ */ ((JsonRpcErrorCode2) => {
504
+ JsonRpcErrorCode2[JsonRpcErrorCode2["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
505
+ JsonRpcErrorCode2[JsonRpcErrorCode2["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
506
+ JsonRpcErrorCode2[JsonRpcErrorCode2["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
507
+ JsonRpcErrorCode2[JsonRpcErrorCode2["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
508
+ JsonRpcErrorCode2[JsonRpcErrorCode2["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
509
+ JsonRpcErrorCode2[JsonRpcErrorCode2["AUTHENTICATION_ERROR"] = -32001] = "AUTHENTICATION_ERROR";
510
+ JsonRpcErrorCode2[JsonRpcErrorCode2["ENTITY_NOT_FOUND"] = -32004] = "ENTITY_NOT_FOUND";
511
+ JsonRpcErrorCode2[JsonRpcErrorCode2["SESSION_DISCONNECTED"] = -32005] = "SESSION_DISCONNECTED";
512
+ return JsonRpcErrorCode2;
513
+ })(JsonRpcErrorCode || {});
514
+ var JsonRpcMessageType = /* @__PURE__ */ ((JsonRpcMessageType2) => {
515
+ JsonRpcMessageType2["Request"] = "request";
516
+ JsonRpcMessageType2["Response"] = "response";
517
+ JsonRpcMessageType2["Notification"] = "notification";
518
+ return JsonRpcMessageType2;
519
+ })(JsonRpcMessageType || {});
520
+ var SettingsLevel = /* @__PURE__ */ ((SettingsLevel2) => {
521
+ SettingsLevel2["Org"] = "org";
522
+ SettingsLevel2["Runtime"] = "runtime";
523
+ SettingsLevel2["User"] = "user";
524
+ SettingsLevel2["Project"] = "project";
525
+ SettingsLevel2["Folder"] = "folder";
526
+ SettingsLevel2["Dynamic"] = "dynamic";
527
+ SettingsLevel2["BuiltIn"] = "builtin";
528
+ return SettingsLevel2;
529
+ })(SettingsLevel || {});
530
+ var SkillLocation = /* @__PURE__ */ ((SkillLocation2) => {
531
+ SkillLocation2["Project"] = "project";
532
+ SkillLocation2["Personal"] = "personal";
533
+ SkillLocation2["Builtin"] = "builtin";
534
+ return SkillLocation2;
535
+ })(SkillLocation || {});
536
+
537
+ // src/schemas/constants.ts
538
+ var JSONRPC_VERSION = "2.0";
539
+ var LEGACY_FACTORY_API_VERSION = "1.0.0";
540
+ var FACTORY_PROTOCOL_VERSION = "1.2.0";
541
+ var FACTORY_CLIENT_HEADER = "X-Factory-Client";
542
+ var FACTORY_CLIENT_VERSION = "X-Client-Version";
543
+ var DEFAULT_REQUEST_TIMEOUT = 3e4;
544
+ var SESSION_INIT_TIMEOUT = 6e4;
545
+ var MCP_AUTH_TIMEOUT = 3e5;
546
+
547
+ // src/schemas/shared.ts
548
+ var import_zod = require("zod");
549
+ var TraceContextMetaSchema = import_zod.z.object({
550
+ traceparent: import_zod.z.string().optional(),
551
+ tracestate: import_zod.z.string().optional()
552
+ });
553
+ var JsonRpcEnvelopeSchema = import_zod.z.object({
554
+ jsonrpc: import_zod.z.literal(JSONRPC_VERSION),
555
+ factoryApiVersion: import_zod.z.literal(LEGACY_FACTORY_API_VERSION),
556
+ factoryProtocolVersion: import_zod.z.string().optional(),
557
+ _meta: TraceContextMetaSchema.optional()
558
+ });
559
+ var JsonRpcErrorSchema = import_zod.z.object({
560
+ code: import_zod.z.nativeEnum(JsonRpcErrorCode),
561
+ message: import_zod.z.string(),
562
+ data: import_zod.z.unknown().optional()
563
+ });
564
+ var BaseRequestSchema = import_zod.z.object({
565
+ type: import_zod.z.literal("request"),
566
+ id: import_zod.z.string(),
567
+ method: import_zod.z.string(),
568
+ params: import_zod.z.unknown().optional()
569
+ });
570
+ var BaseResponseSuccessSchema = import_zod.z.object({
571
+ type: import_zod.z.literal("response"),
572
+ id: import_zod.z.string(),
573
+ result: import_zod.z.unknown()
574
+ });
575
+ var BaseResponseFailureSchema = import_zod.z.object({
576
+ type: import_zod.z.literal("response"),
577
+ id: import_zod.z.string().nullable(),
578
+ error: JsonRpcErrorSchema
579
+ });
580
+ var BaseNotificationSchema = import_zod.z.object({
581
+ type: import_zod.z.literal("notification"),
582
+ method: import_zod.z.string(),
583
+ params: import_zod.z.unknown().optional()
584
+ });
585
+ var JsonRpcRequestSchema = JsonRpcEnvelopeSchema.extend(
586
+ BaseRequestSchema.shape
587
+ );
588
+ var JsonRpcResponseSuccessSchema = JsonRpcEnvelopeSchema.extend(
589
+ BaseResponseSuccessSchema.shape
590
+ );
591
+ var JsonRpcResponseFailureSchema = JsonRpcEnvelopeSchema.extend(
592
+ BaseResponseFailureSchema.shape
593
+ );
594
+ var JsonRpcNotificationSchema = JsonRpcEnvelopeSchema.extend(
595
+ BaseNotificationSchema.shape
596
+ );
597
+ var JsonRpcResponseSchema = import_zod.z.union([
598
+ JsonRpcResponseFailureSchema,
599
+ JsonRpcResponseSuccessSchema
600
+ ]);
601
+ var JsonRpcMessageSchema = import_zod.z.discriminatedUnion("type", [
602
+ JsonRpcRequestSchema,
603
+ JsonRpcEnvelopeSchema.extend({
604
+ type: import_zod.z.literal("response"),
605
+ id: import_zod.z.string().nullable(),
606
+ result: import_zod.z.unknown().optional(),
607
+ error: JsonRpcErrorSchema.optional()
608
+ }),
609
+ JsonRpcNotificationSchema
610
+ ]);
611
+
612
+ // src/schemas/messages.ts
613
+ var import_zod2 = require("zod");
614
+ var TextBlockSchema = import_zod2.z.object({
615
+ type: import_zod2.z.literal("text"),
616
+ text: import_zod2.z.string(),
617
+ id: import_zod2.z.string().optional()
618
+ }).passthrough();
619
+ var Base64ImageSourceSchema = import_zod2.z.object({
620
+ type: import_zod2.z.literal("base64"),
621
+ data: import_zod2.z.string(),
622
+ mediaType: import_zod2.z.enum(["image/jpeg", "image/png", "image/gif", "image/webp"])
623
+ }).passthrough();
624
+ var ImageBlockSchema = import_zod2.z.object({
625
+ type: import_zod2.z.literal("image"),
626
+ source: Base64ImageSourceSchema,
627
+ id: import_zod2.z.string().optional()
628
+ }).passthrough();
629
+ var ThinkingBlockSchema = import_zod2.z.object({
630
+ type: import_zod2.z.literal("thinking"),
631
+ signature: import_zod2.z.string(),
632
+ thinking: import_zod2.z.string(),
633
+ id: import_zod2.z.string().optional(),
634
+ signatureProvider: import_zod2.z.string().optional()
635
+ }).passthrough();
636
+ var RedactedThinkingBlockSchema = import_zod2.z.object({
637
+ type: import_zod2.z.literal("redacted_thinking"),
638
+ data: import_zod2.z.string(),
639
+ id: import_zod2.z.string().optional()
640
+ }).passthrough();
641
+ var ToolUseBlockSchema = import_zod2.z.object({
642
+ type: import_zod2.z.literal("tool_use"),
643
+ id: import_zod2.z.string(),
644
+ input: import_zod2.z.record(import_zod2.z.unknown()),
645
+ name: import_zod2.z.string(),
646
+ thoughtSignature: import_zod2.z.string().optional()
647
+ }).passthrough();
648
+ var ToolResultBlockSchema = import_zod2.z.object({
649
+ type: import_zod2.z.literal("tool_result"),
650
+ toolUseId: import_zod2.z.string(),
651
+ content: import_zod2.z.union([import_zod2.z.string(), import_zod2.z.array(import_zod2.z.unknown())]).optional(),
652
+ isError: import_zod2.z.boolean().optional(),
653
+ id: import_zod2.z.string().optional()
654
+ }).passthrough();
655
+ var DocumentBlockSchema = import_zod2.z.object({
656
+ type: import_zod2.z.literal("document"),
657
+ source: import_zod2.z.record(import_zod2.z.unknown()),
658
+ id: import_zod2.z.string().optional()
659
+ }).passthrough();
660
+ var ContentBlockSchema = import_zod2.z.discriminatedUnion("type", [
661
+ TextBlockSchema,
662
+ ImageBlockSchema,
663
+ ThinkingBlockSchema,
664
+ RedactedThinkingBlockSchema,
665
+ ToolUseBlockSchema,
666
+ ToolResultBlockSchema,
667
+ DocumentBlockSchema
668
+ ]);
669
+ var FactoryDroidMessageSchema = import_zod2.z.object({
670
+ id: import_zod2.z.string(),
671
+ role: import_zod2.z.enum(["user", "assistant", "tool", "system"]),
672
+ content: import_zod2.z.array(ContentBlockSchema),
673
+ createdAt: import_zod2.z.number(),
674
+ updatedAt: import_zod2.z.number(),
675
+ parentId: import_zod2.z.string().optional(),
676
+ visibility: import_zod2.z.enum(["both", "llm_only", "user_only"]).optional(),
677
+ isError: import_zod2.z.boolean().optional()
678
+ }).passthrough();
679
+ var DocumentSourceSchema = import_zod2.z.object({
680
+ type: import_zod2.z.string(),
681
+ mediaType: import_zod2.z.string(),
682
+ data: import_zod2.z.string(),
683
+ name: import_zod2.z.string().optional(),
684
+ mime: import_zod2.z.string().optional()
685
+ }).strict();
686
+
687
+ // src/schemas/mcp.ts
688
+ var import_zod3 = require("zod");
689
+ var McpStdioServerConfigFieldsSchema = import_zod3.z.object({
690
+ command: import_zod3.z.string().optional(),
691
+ args: import_zod3.z.array(import_zod3.z.string()).optional()
692
+ });
693
+ var McpHttpServerConfigFieldsSchema = import_zod3.z.object({
694
+ url: import_zod3.z.string().optional()
695
+ });
696
+ var McpSseServerConfigFieldsSchema = import_zod3.z.object({
697
+ url: import_zod3.z.string(),
698
+ headers: import_zod3.z.record(import_zod3.z.string()).optional()
699
+ });
700
+ var McpServerStatusInfoSchema = import_zod3.z.object({
701
+ name: import_zod3.z.string(),
702
+ status: import_zod3.z.nativeEnum(McpServerStatus),
703
+ source: import_zod3.z.nativeEnum(SettingsLevel),
704
+ isManaged: import_zod3.z.boolean(),
705
+ error: import_zod3.z.string().optional(),
706
+ toolCount: import_zod3.z.number().optional(),
707
+ serverType: import_zod3.z.nativeEnum(McpServerType).optional(),
708
+ hasAuthTokens: import_zod3.z.boolean().optional()
709
+ }).passthrough();
710
+ var McpStatusSummarySchema = import_zod3.z.object({
711
+ total: import_zod3.z.number(),
712
+ connected: import_zod3.z.number(),
713
+ connecting: import_zod3.z.number(),
714
+ failed: import_zod3.z.number(),
715
+ disabled: import_zod3.z.number().optional()
716
+ }).passthrough();
717
+ var McpRegistryServerSchema = import_zod3.z.object({
718
+ name: import_zod3.z.string(),
719
+ description: import_zod3.z.string(),
720
+ type: import_zod3.z.nativeEnum(McpServerType),
721
+ // Stdio config fields
722
+ command: import_zod3.z.string().optional(),
723
+ args: import_zod3.z.array(import_zod3.z.string()).optional(),
724
+ // HTTP config fields
725
+ url: import_zod3.z.string().optional(),
726
+ // Additional metadata
727
+ note: import_zod3.z.string().optional(),
728
+ logoUrl: import_zod3.z.string().optional()
729
+ }).passthrough();
730
+ var McpToolInputSchemaSchema = import_zod3.z.object({
731
+ type: import_zod3.z.string().optional(),
732
+ properties: import_zod3.z.record(import_zod3.z.unknown()).optional(),
733
+ required: import_zod3.z.array(import_zod3.z.string()).optional()
734
+ }).passthrough();
735
+ var McpToolInfoSchema = import_zod3.z.object({
736
+ serverName: import_zod3.z.string(),
737
+ name: import_zod3.z.string(),
738
+ description: import_zod3.z.string().optional(),
739
+ isEnabled: import_zod3.z.boolean(),
740
+ isReadOnly: import_zod3.z.boolean().optional(),
741
+ inputSchema: McpToolInputSchemaSchema.optional()
742
+ }).passthrough();
743
+ var ToolConfirmationListItemSchema = import_zod3.z.object({
744
+ label: import_zod3.z.string(),
745
+ value: import_zod3.z.nativeEnum(ToolConfirmationOutcome)
746
+ }).passthrough();
747
+
748
+ // src/schemas/mission.ts
749
+ var import_zod4 = require("zod");
750
+ var MissionFeatureSchema = import_zod4.z.object({
751
+ id: import_zod4.z.string(),
752
+ description: import_zod4.z.string(),
753
+ status: import_zod4.z.nativeEnum(FeatureStatus),
754
+ skillName: import_zod4.z.string(),
755
+ preconditions: import_zod4.z.array(import_zod4.z.string()),
756
+ expectedBehavior: import_zod4.z.array(import_zod4.z.string()),
757
+ verificationSteps: import_zod4.z.array(import_zod4.z.string()),
758
+ fulfills: import_zod4.z.array(import_zod4.z.string()).optional(),
759
+ milestone: import_zod4.z.string().optional(),
760
+ workerSessionIds: import_zod4.z.array(import_zod4.z.string()).optional(),
761
+ currentWorkerSessionId: import_zod4.z.string().nullable().optional(),
762
+ completedWorkerSessionId: import_zod4.z.string().nullable().optional()
763
+ }).passthrough();
764
+ var FeatureSuccessStateSchema = import_zod4.z.nativeEnum(FeatureSuccessState);
765
+ var DiscoveredIssueSchema = import_zod4.z.object({
766
+ severity: import_zod4.z.nativeEnum(IssueSeverity),
767
+ description: import_zod4.z.string(),
768
+ suggestedFix: import_zod4.z.string().optional()
769
+ }).passthrough();
770
+ var VerificationCommandSchema = import_zod4.z.object({
771
+ command: import_zod4.z.string(),
772
+ exitCode: import_zod4.z.number(),
773
+ observation: import_zod4.z.string()
774
+ }).passthrough();
775
+ var InteractiveCheckSchema = import_zod4.z.object({
776
+ action: import_zod4.z.string(),
777
+ observed: import_zod4.z.string()
778
+ }).passthrough();
779
+ var VerificationSchema = import_zod4.z.object({
780
+ commandsRun: import_zod4.z.array(VerificationCommandSchema),
781
+ interactiveChecks: import_zod4.z.array(InteractiveCheckSchema).optional()
782
+ }).passthrough();
783
+ var TestCaseSchema = import_zod4.z.object({
784
+ name: import_zod4.z.string(),
785
+ verifies: import_zod4.z.string()
786
+ }).passthrough();
787
+ var TestFileSchema = import_zod4.z.object({
788
+ file: import_zod4.z.string(),
789
+ cases: import_zod4.z.array(TestCaseSchema)
790
+ }).passthrough();
791
+ var TestsSchema = import_zod4.z.object({
792
+ added: import_zod4.z.array(TestFileSchema),
793
+ updated: import_zod4.z.array(import_zod4.z.string()).optional(),
794
+ coverage: import_zod4.z.string()
795
+ }).passthrough();
796
+ var SkillDeviationSchema = import_zod4.z.object({
797
+ step: import_zod4.z.string(),
798
+ whatIDidInstead: import_zod4.z.string(),
799
+ why: import_zod4.z.string()
800
+ }).passthrough();
801
+ var SkillFeedbackSchema = import_zod4.z.object({
802
+ followedProcedure: import_zod4.z.boolean(),
803
+ deviations: import_zod4.z.array(SkillDeviationSchema),
804
+ suggestedChanges: import_zod4.z.array(import_zod4.z.string()).optional()
805
+ }).passthrough();
806
+ var HandoffSchema = import_zod4.z.object({
807
+ salientSummary: import_zod4.z.string().optional(),
808
+ whatWasImplemented: import_zod4.z.string(),
809
+ whatWasLeftUndone: import_zod4.z.string(),
810
+ verification: VerificationSchema,
811
+ tests: TestsSchema,
812
+ discoveredIssues: import_zod4.z.array(DiscoveredIssueSchema),
813
+ skillFeedback: SkillFeedbackSchema.optional()
814
+ }).passthrough();
815
+ var DismissalRecordSchema = import_zod4.z.object({
816
+ type: import_zod4.z.nativeEnum(DismissalType),
817
+ sourceFeatureId: import_zod4.z.string(),
818
+ summary: import_zod4.z.string(),
819
+ justification: import_zod4.z.string()
820
+ }).passthrough();
821
+ var BaseProgressLogEntrySchema = import_zod4.z.object({
822
+ timestamp: import_zod4.z.string()
823
+ });
824
+ var MissionAcceptedEntrySchema = BaseProgressLogEntrySchema.extend({
825
+ type: import_zod4.z.literal("mission_accepted" /* MissionAccepted */),
826
+ title: import_zod4.z.string()
827
+ }).passthrough();
828
+ var MissionPausedEntrySchema = BaseProgressLogEntrySchema.extend({
829
+ type: import_zod4.z.literal("mission_paused" /* MissionPaused */)
830
+ }).passthrough();
831
+ var MissionResumedEntrySchema = BaseProgressLogEntrySchema.extend({
832
+ type: import_zod4.z.literal("mission_resumed" /* MissionResumed */)
833
+ }).passthrough();
834
+ var MissionRunStartedEntrySchema = BaseProgressLogEntrySchema.extend({
835
+ type: import_zod4.z.literal("mission_run_started" /* MissionRunStarted */),
836
+ message: import_zod4.z.string().optional()
837
+ }).passthrough();
838
+ var WorkerStartedEntrySchema = BaseProgressLogEntrySchema.extend({
839
+ type: import_zod4.z.literal("worker_started" /* WorkerStarted */),
840
+ workerSessionId: import_zod4.z.string(),
841
+ spawnId: import_zod4.z.string(),
842
+ featureId: import_zod4.z.string().optional()
843
+ }).passthrough();
844
+ var WorkerSelectedFeatureEntrySchema = BaseProgressLogEntrySchema.extend({
845
+ type: import_zod4.z.literal("worker_selected_feature" /* WorkerSelectedFeature */),
846
+ workerSessionId: import_zod4.z.string(),
847
+ featureId: import_zod4.z.string()
848
+ }).passthrough();
849
+ var WorkerCompletedEntrySchema = BaseProgressLogEntrySchema.extend({
850
+ type: import_zod4.z.literal("worker_completed" /* WorkerCompleted */),
851
+ workerSessionId: import_zod4.z.string(),
852
+ featureId: import_zod4.z.string(),
853
+ successState: FeatureSuccessStateSchema,
854
+ returnToOrchestrator: import_zod4.z.boolean(),
855
+ commitId: import_zod4.z.string().optional(),
856
+ exitCode: import_zod4.z.number(),
857
+ validatorsPassed: import_zod4.z.boolean().optional(),
858
+ handoff: HandoffSchema.optional()
859
+ }).passthrough();
860
+ var WorkerFailedEntrySchema = BaseProgressLogEntrySchema.extend({
861
+ type: import_zod4.z.literal("worker_failed" /* WorkerFailed */),
862
+ workerSessionId: import_zod4.z.string().optional(),
863
+ spawnId: import_zod4.z.string(),
864
+ exitCode: import_zod4.z.number().optional(),
865
+ reason: import_zod4.z.string()
866
+ }).passthrough();
867
+ var WorkerPausedEntrySchema = BaseProgressLogEntrySchema.extend({
868
+ type: import_zod4.z.literal("worker_paused" /* WorkerPaused */),
869
+ workerSessionId: import_zod4.z.string(),
870
+ featureId: import_zod4.z.string().optional()
871
+ }).passthrough();
872
+ var HandoffItemsDismissedEntrySchema = BaseProgressLogEntrySchema.extend({
873
+ type: import_zod4.z.literal("handoff_items_dismissed" /* HandoffItemsDismissed */),
874
+ dismissals: import_zod4.z.array(DismissalRecordSchema).optional()
875
+ }).passthrough();
876
+ var MilestoneValidationTriggeredEntrySchema = BaseProgressLogEntrySchema.extend({
877
+ type: import_zod4.z.literal("milestone_validation_triggered" /* MilestoneValidationTriggered */),
878
+ milestone: import_zod4.z.string(),
879
+ featureId: import_zod4.z.string()
880
+ }).passthrough();
881
+ var ProgressLogEntrySchema = import_zod4.z.discriminatedUnion("type", [
882
+ MissionAcceptedEntrySchema,
883
+ MissionPausedEntrySchema,
884
+ MissionResumedEntrySchema,
885
+ MissionRunStartedEntrySchema,
886
+ WorkerStartedEntrySchema,
887
+ WorkerSelectedFeatureEntrySchema,
888
+ WorkerCompletedEntrySchema,
889
+ WorkerFailedEntrySchema,
890
+ WorkerPausedEntrySchema,
891
+ HandoffItemsDismissedEntrySchema,
892
+ MilestoneValidationTriggeredEntrySchema
893
+ ]);
894
+
895
+ // src/schemas/client.ts
896
+ var import_zod5 = require("zod");
897
+ var SessionTagSchema = import_zod5.z.object({
898
+ name: import_zod5.z.string(),
899
+ metadata: import_zod5.z.record(import_zod5.z.string()).optional()
900
+ }).strict();
901
+ var SessionSourceSchema = import_zod5.z.object({
902
+ platform: import_zod5.z.string()
903
+ }).passthrough();
904
+ var StdioMcpConfigSchema = import_zod5.z.object({
905
+ name: import_zod5.z.string(),
906
+ command: import_zod5.z.string(),
907
+ args: import_zod5.z.array(import_zod5.z.string()).default([]),
908
+ env: import_zod5.z.record(import_zod5.z.string()).optional().default({})
909
+ }).strict();
910
+ var HttpHeaderSchema = import_zod5.z.object({
911
+ name: import_zod5.z.string(),
912
+ value: import_zod5.z.string()
913
+ }).strict();
914
+ var HttpMcpConfigSchema = import_zod5.z.object({
915
+ type: import_zod5.z.literal("http"),
916
+ name: import_zod5.z.string(),
917
+ url: import_zod5.z.string().url(),
918
+ headers: HttpHeaderSchema.array().default([])
919
+ }).strict();
920
+ var SseMcpConfigSchema = import_zod5.z.object({
921
+ type: import_zod5.z.literal("sse"),
922
+ name: import_zod5.z.string(),
923
+ url: import_zod5.z.string().url(),
924
+ headers: HttpHeaderSchema.array().default([])
925
+ }).strict();
926
+ var McpServerConfigSchema = import_zod5.z.union([
927
+ StdioMcpConfigSchema,
928
+ HttpMcpConfigSchema,
929
+ SseMcpConfigSchema
930
+ ]);
931
+ var SessionSettingsSchema = import_zod5.z.object({
932
+ modelId: import_zod5.z.string(),
933
+ reasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort),
934
+ autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
935
+ interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
936
+ autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
937
+ specModeModelId: import_zod5.z.string().optional(),
938
+ specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional()
939
+ }).passthrough();
940
+ var GitRepoInfoSchema = import_zod5.z.object({
941
+ owner: import_zod5.z.string().optional(),
942
+ repoName: import_zod5.z.string()
943
+ }).passthrough();
944
+ var AvailableModelConfigSchema = import_zod5.z.object({
945
+ id: import_zod5.z.string(),
946
+ modelId: import_zod5.z.string().optional(),
947
+ displayName: import_zod5.z.string(),
948
+ shortDisplayName: import_zod5.z.string(),
949
+ modelProvider: import_zod5.z.nativeEnum(ModelProvider),
950
+ supportedReasoningEfforts: import_zod5.z.array(import_zod5.z.nativeEnum(ReasoningEffort)),
951
+ defaultReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort),
952
+ isCustom: import_zod5.z.boolean().default(false),
953
+ noImageSupport: import_zod5.z.boolean().optional(),
954
+ supportsPDFs: import_zod5.z.boolean().optional(),
955
+ tier: import_zod5.z.string().optional(),
956
+ tokenMultiplier: import_zod5.z.number().optional(),
957
+ promoLabel: import_zod5.z.string().optional(),
958
+ featureFlag: import_zod5.z.record(import_zod5.z.unknown()).optional(),
959
+ usesUSBasedInference: import_zod5.z.boolean().optional()
960
+ }).passthrough();
961
+ var TokenUsageSchema = import_zod5.z.object({
962
+ inputTokens: import_zod5.z.number(),
963
+ outputTokens: import_zod5.z.number(),
964
+ cacheCreationTokens: import_zod5.z.number(),
965
+ cacheReadTokens: import_zod5.z.number(),
966
+ thinkingTokens: import_zod5.z.number()
967
+ }).passthrough();
968
+ var WorkerStateInfoSchema = import_zod5.z.object({
969
+ startedAt: import_zod5.z.string(),
970
+ completedAt: import_zod5.z.string().optional(),
971
+ exitCode: import_zod5.z.number().optional()
972
+ }).passthrough();
973
+ var SkillResourceSchema = import_zod5.z.object({
974
+ name: import_zod5.z.string(),
975
+ path: import_zod5.z.string(),
976
+ type: import_zod5.z.enum(["reference", "asset"])
977
+ }).passthrough();
978
+ var SkillInfoSchema = import_zod5.z.object({
979
+ name: import_zod5.z.string(),
980
+ description: import_zod5.z.string().optional(),
981
+ location: import_zod5.z.nativeEnum(SkillLocation),
982
+ filePath: import_zod5.z.string(),
983
+ enabled: import_zod5.z.boolean().optional(),
984
+ userInvocable: import_zod5.z.boolean().optional(),
985
+ version: import_zod5.z.string().optional(),
986
+ content: import_zod5.z.string().optional(),
987
+ resources: import_zod5.z.array(SkillResourceSchema).optional()
988
+ }).passthrough();
989
+ var InitializeSessionRequestParamsSchema = import_zod5.z.object({
990
+ machineId: import_zod5.z.string(),
991
+ cwd: import_zod5.z.string(),
992
+ workspaceId: import_zod5.z.string().optional(),
993
+ sessionId: import_zod5.z.string().optional(),
994
+ mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
995
+ autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
996
+ interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
997
+ autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
998
+ modelId: import_zod5.z.string().optional(),
999
+ reasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1000
+ specModeModelId: import_zod5.z.string().optional(),
1001
+ specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1002
+ decompSessionType: import_zod5.z.nativeEnum(DecompSessionType).optional(),
1003
+ decompMissionId: import_zod5.z.string().optional(),
1004
+ skipPermissionsUnsafe: import_zod5.z.boolean().optional(),
1005
+ enabledToolIds: import_zod5.z.array(import_zod5.z.string()).optional(),
1006
+ sessionLocation: import_zod5.z.string().optional(),
1007
+ sessionSource: SessionSourceSchema.optional(),
1008
+ tags: import_zod5.z.array(SessionTagSchema).optional(),
1009
+ mcpOAuthCallbackUri: import_zod5.z.string().optional()
1010
+ }).strict();
1011
+ var LoadSessionRequestParamsSchema = import_zod5.z.object({
1012
+ sessionId: import_zod5.z.string(),
1013
+ mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1014
+ mcpOAuthCallbackUri: import_zod5.z.string().optional()
1015
+ }).strict();
1016
+ var AddUserMessageRequestParamsSchema = import_zod5.z.object({
1017
+ messageId: import_zod5.z.string().optional(),
1018
+ text: import_zod5.z.string(),
1019
+ images: import_zod5.z.array(Base64ImageSourceSchema).optional(),
1020
+ files: import_zod5.z.array(DocumentSourceSchema).optional()
1021
+ }).strict();
1022
+ var InterruptSessionRequestParamsSchema = import_zod5.z.object({}).strict();
1023
+ var KillWorkerSessionRequestParamsSchema = import_zod5.z.object({
1024
+ workerSessionId: import_zod5.z.string()
1025
+ }).strict();
1026
+ var UpdateSessionSettingsRequestParamsSchema = import_zod5.z.object({
1027
+ modelId: import_zod5.z.string().optional(),
1028
+ reasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1029
+ autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
1030
+ interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1031
+ autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1032
+ specModeModelId: import_zod5.z.string().nullable().optional(),
1033
+ specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).nullable().optional()
1034
+ }).strict();
1035
+ var ToggleMcpServerRequestParamsSchema = import_zod5.z.object({
1036
+ serverName: import_zod5.z.string(),
1037
+ enabled: import_zod5.z.boolean(),
1038
+ settingsLevel: import_zod5.z.literal("user" /* User */)
1039
+ }).strict();
1040
+ var AuthenticateMcpServerRequestParamsSchema = import_zod5.z.object({
1041
+ serverName: import_zod5.z.string()
1042
+ }).strict();
1043
+ var CancelMcpAuthRequestParamsSchema = import_zod5.z.object({
1044
+ serverName: import_zod5.z.string()
1045
+ }).strict();
1046
+ var ClearMcpAuthRequestParamsSchema = import_zod5.z.object({
1047
+ serverName: import_zod5.z.string()
1048
+ }).strict();
1049
+ var SubmitMcpAuthCodeRequestParamsSchema = import_zod5.z.object({
1050
+ serverName: import_zod5.z.string(),
1051
+ code: import_zod5.z.string(),
1052
+ state: import_zod5.z.string()
1053
+ }).strict();
1054
+ var AddMcpServerRequestParamsSchema = import_zod5.z.object({
1055
+ name: import_zod5.z.string(),
1056
+ type: import_zod5.z.nativeEnum(McpServerType),
1057
+ url: import_zod5.z.string().optional(),
1058
+ headers: import_zod5.z.record(import_zod5.z.string()).optional(),
1059
+ command: import_zod5.z.string().optional(),
1060
+ args: import_zod5.z.array(import_zod5.z.string()).optional(),
1061
+ env: import_zod5.z.record(import_zod5.z.string()).optional()
1062
+ }).strict();
1063
+ var RemoveMcpServerRequestParamsSchema = import_zod5.z.object({
1064
+ serverName: import_zod5.z.string(),
1065
+ settingsLevel: import_zod5.z.literal("user" /* User */)
1066
+ }).strict();
1067
+ var ListMcpRegistryRequestParamsSchema = import_zod5.z.object({}).strict();
1068
+ var ListMcpToolsRequestParamsSchema = import_zod5.z.object({}).strict();
1069
+ var ListMcpServersRequestParamsSchema = import_zod5.z.object({}).strict();
1070
+ var ToggleMcpToolRequestParamsSchema = import_zod5.z.object({
1071
+ serverName: import_zod5.z.string(),
1072
+ toolName: import_zod5.z.string(),
1073
+ enabled: import_zod5.z.boolean()
1074
+ }).strict();
1075
+ var ListSkillsRequestParamsSchema = import_zod5.z.object({}).strict();
1076
+ var SubmitBugReportRequestParamsSchema = import_zod5.z.object({
1077
+ userComment: import_zod5.z.string(),
1078
+ clientLogs: import_zod5.z.string().optional()
1079
+ }).strict();
1080
+ var InitializeSessionRequestSchema = JsonRpcRequestSchema.extend({
1081
+ method: import_zod5.z.literal("droid.initialize_session" /* INITIALIZE_SESSION */),
1082
+ params: InitializeSessionRequestParamsSchema
1083
+ });
1084
+ var LoadSessionRequestSchema = JsonRpcRequestSchema.extend({
1085
+ method: import_zod5.z.literal("droid.load_session" /* LOAD_SESSION */),
1086
+ params: LoadSessionRequestParamsSchema
1087
+ });
1088
+ var AddUserMessageRequestSchema = JsonRpcRequestSchema.extend({
1089
+ method: import_zod5.z.literal("droid.add_user_message" /* ADD_USER_MESSAGE */),
1090
+ params: AddUserMessageRequestParamsSchema
1091
+ });
1092
+ var InterruptSessionRequestSchema = JsonRpcRequestSchema.extend({
1093
+ method: import_zod5.z.literal("droid.interrupt_session" /* INTERRUPT_SESSION */),
1094
+ params: InterruptSessionRequestParamsSchema
1095
+ });
1096
+ var KillWorkerSessionRequestSchema = JsonRpcRequestSchema.extend({
1097
+ method: import_zod5.z.literal("droid.kill_worker_session" /* KILL_WORKER_SESSION */),
1098
+ params: KillWorkerSessionRequestParamsSchema
1099
+ });
1100
+ var UpdateSessionSettingsRequestSchema = JsonRpcRequestSchema.extend({
1101
+ method: import_zod5.z.literal("droid.update_session_settings" /* UPDATE_SESSION_SETTINGS */),
1102
+ params: UpdateSessionSettingsRequestParamsSchema
1103
+ });
1104
+ var ToggleMcpServerRequestSchema = JsonRpcRequestSchema.extend({
1105
+ method: import_zod5.z.literal("droid.toggle_mcp_server" /* TOGGLE_MCP_SERVER */),
1106
+ params: ToggleMcpServerRequestParamsSchema
1107
+ });
1108
+ var AuthenticateMcpServerRequestSchema = JsonRpcRequestSchema.extend({
1109
+ method: import_zod5.z.literal("droid.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */),
1110
+ params: AuthenticateMcpServerRequestParamsSchema
1111
+ });
1112
+ var CancelMcpAuthRequestSchema = JsonRpcRequestSchema.extend({
1113
+ method: import_zod5.z.literal("droid.cancel_mcp_auth" /* CANCEL_MCP_AUTH */),
1114
+ params: CancelMcpAuthRequestParamsSchema
1115
+ });
1116
+ var ClearMcpAuthRequestSchema = JsonRpcRequestSchema.extend({
1117
+ method: import_zod5.z.literal("droid.clear_mcp_auth" /* CLEAR_MCP_AUTH */),
1118
+ params: ClearMcpAuthRequestParamsSchema
1119
+ });
1120
+ var SubmitMcpAuthCodeRequestSchema = JsonRpcRequestSchema.extend({
1121
+ method: import_zod5.z.literal("droid.submit_mcp_auth_code" /* SUBMIT_MCP_AUTH_CODE */),
1122
+ params: SubmitMcpAuthCodeRequestParamsSchema
1123
+ });
1124
+ var AddMcpServerRequestSchema = JsonRpcRequestSchema.extend({
1125
+ method: import_zod5.z.literal("droid.add_mcp_server" /* ADD_MCP_SERVER */),
1126
+ params: AddMcpServerRequestParamsSchema
1127
+ });
1128
+ var RemoveMcpServerRequestSchema = JsonRpcRequestSchema.extend({
1129
+ method: import_zod5.z.literal("droid.remove_mcp_server" /* REMOVE_MCP_SERVER */),
1130
+ params: RemoveMcpServerRequestParamsSchema
1131
+ });
1132
+ var ListMcpRegistryRequestSchema = JsonRpcRequestSchema.extend({
1133
+ method: import_zod5.z.literal("droid.list_mcp_registry" /* LIST_MCP_REGISTRY */),
1134
+ params: ListMcpRegistryRequestParamsSchema
1135
+ });
1136
+ var ListMcpToolsRequestSchema = JsonRpcRequestSchema.extend({
1137
+ method: import_zod5.z.literal("droid.list_mcp_tools" /* LIST_MCP_TOOLS */),
1138
+ params: ListMcpToolsRequestParamsSchema
1139
+ });
1140
+ var ListMcpServersRequestSchema = JsonRpcRequestSchema.extend({
1141
+ method: import_zod5.z.literal("droid.list_mcp_servers" /* LIST_MCP_SERVERS */),
1142
+ params: ListMcpServersRequestParamsSchema
1143
+ });
1144
+ var ToggleMcpToolRequestSchema = JsonRpcRequestSchema.extend({
1145
+ method: import_zod5.z.literal("droid.toggle_mcp_tool" /* TOGGLE_MCP_TOOL */),
1146
+ params: ToggleMcpToolRequestParamsSchema
1147
+ });
1148
+ var ListSkillsRequestSchema = JsonRpcRequestSchema.extend({
1149
+ method: import_zod5.z.literal("droid.list_skills" /* LIST_SKILLS */),
1150
+ params: ListSkillsRequestParamsSchema
1151
+ });
1152
+ var SubmitBugReportRequestSchema = JsonRpcRequestSchema.extend({
1153
+ method: import_zod5.z.literal("droid.submit_bug_report" /* SUBMIT_BUG_REPORT */),
1154
+ params: SubmitBugReportRequestParamsSchema
1155
+ });
1156
+ var ClientRequestSchema = import_zod5.z.discriminatedUnion("method", [
1157
+ InitializeSessionRequestSchema,
1158
+ LoadSessionRequestSchema,
1159
+ AddUserMessageRequestSchema,
1160
+ InterruptSessionRequestSchema,
1161
+ KillWorkerSessionRequestSchema,
1162
+ UpdateSessionSettingsRequestSchema,
1163
+ ToggleMcpServerRequestSchema,
1164
+ AuthenticateMcpServerRequestSchema,
1165
+ CancelMcpAuthRequestSchema,
1166
+ ClearMcpAuthRequestSchema,
1167
+ SubmitMcpAuthCodeRequestSchema,
1168
+ AddMcpServerRequestSchema,
1169
+ RemoveMcpServerRequestSchema,
1170
+ ListMcpRegistryRequestSchema,
1171
+ ListMcpToolsRequestSchema,
1172
+ ListMcpServersRequestSchema,
1173
+ ToggleMcpToolRequestSchema,
1174
+ ListSkillsRequestSchema,
1175
+ SubmitBugReportRequestSchema
1176
+ ]);
1177
+ var MissionSnapshotSchema = import_zod5.z.object({
1178
+ state: import_zod5.z.nativeEnum(MissionState),
1179
+ features: import_zod5.z.array(MissionFeatureSchema),
1180
+ progressLog: import_zod5.z.array(ProgressLogEntrySchema),
1181
+ workerSessionIds: import_zod5.z.array(import_zod5.z.string()),
1182
+ workerStates: import_zod5.z.record(WorkerStateInfoSchema).optional(),
1183
+ tokenUsage: TokenUsageSchema.optional(),
1184
+ tokenUsageBySessionId: import_zod5.z.record(TokenUsageSchema).optional()
1185
+ }).passthrough();
1186
+ var InitializeSessionResultSchema = import_zod5.z.object({
1187
+ sessionId: import_zod5.z.string(),
1188
+ session: import_zod5.z.record(import_zod5.z.unknown()),
1189
+ mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1190
+ settings: SessionSettingsSchema,
1191
+ gitRepo: GitRepoInfoSchema.optional(),
1192
+ availableModels: import_zod5.z.array(AvailableModelConfigSchema).optional()
1193
+ }).passthrough();
1194
+ var LoadSessionResultSchema = import_zod5.z.object({
1195
+ session: import_zod5.z.record(import_zod5.z.unknown()),
1196
+ mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1197
+ pendingPermissions: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1198
+ pendingAskUserRequests: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1199
+ settings: SessionSettingsSchema,
1200
+ isAgentLoopInProgress: import_zod5.z.boolean().optional(),
1201
+ queuedMessages: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1202
+ gitRepo: GitRepoInfoSchema.optional(),
1203
+ cwd: import_zod5.z.string().optional(),
1204
+ callingSessionId: import_zod5.z.string().optional(),
1205
+ callingToolUseId: import_zod5.z.string().optional(),
1206
+ availableModels: import_zod5.z.array(AvailableModelConfigSchema).optional(),
1207
+ tokenUsage: TokenUsageSchema.optional(),
1208
+ mission: MissionSnapshotSchema.optional(),
1209
+ decompSessionType: import_zod5.z.nativeEnum(DecompSessionType).optional()
1210
+ }).passthrough();
1211
+ var AddUserMessageResultSchema = import_zod5.z.object({}).passthrough();
1212
+ var InterruptSessionResultSchema = import_zod5.z.object({}).passthrough();
1213
+ var KillWorkerSessionResultSchema = import_zod5.z.object({}).passthrough();
1214
+ var UpdateSessionSettingsResultSchema = import_zod5.z.object({}).passthrough();
1215
+ var ToggleMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1216
+ var AuthenticateMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1217
+ var CancelMcpAuthResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1218
+ var ClearMcpAuthResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1219
+ var SubmitMcpAuthCodeResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1220
+ var AddMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1221
+ var RemoveMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1222
+ var ListMcpRegistryResultSchema = import_zod5.z.object({ servers: import_zod5.z.array(McpRegistryServerSchema) }).passthrough();
1223
+ var ListMcpToolsResultSchema = import_zod5.z.object({ tools: import_zod5.z.array(McpToolInfoSchema) }).passthrough();
1224
+ var ListMcpServersResultSchema = import_zod5.z.object({
1225
+ servers: import_zod5.z.array(McpServerStatusInfoSchema),
1226
+ summary: McpStatusSummarySchema
1227
+ }).passthrough();
1228
+ var ToggleMcpToolResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1229
+ var ListSkillsResultSchema = import_zod5.z.object({ skills: import_zod5.z.array(SkillInfoSchema) }).passthrough();
1230
+ var SubmitBugReportResultSchema = import_zod5.z.object({ bugReportId: import_zod5.z.string() }).passthrough();
1231
+ var InitializeSessionResponseSchema = import_zod5.z.union([
1232
+ JsonRpcResponseSuccessSchema.extend({
1233
+ result: InitializeSessionResultSchema
1234
+ }),
1235
+ JsonRpcResponseFailureSchema
1236
+ ]);
1237
+ var _LoadSessionResponseSchema = import_zod5.z.union([
1238
+ JsonRpcResponseSuccessSchema.extend({ result: LoadSessionResultSchema }),
1239
+ JsonRpcResponseFailureSchema
1240
+ ]);
1241
+ var LoadSessionResponseSchema = _LoadSessionResponseSchema;
1242
+ var AddUserMessageResponseSchema = import_zod5.z.union([
1243
+ JsonRpcResponseSuccessSchema.extend({ result: AddUserMessageResultSchema }),
1244
+ JsonRpcResponseFailureSchema
1245
+ ]);
1246
+ var InterruptSessionResponseSchema = import_zod5.z.union([
1247
+ JsonRpcResponseSuccessSchema.extend({
1248
+ result: InterruptSessionResultSchema
1249
+ }),
1250
+ JsonRpcResponseFailureSchema
1251
+ ]);
1252
+ var KillWorkerSessionResponseSchema = import_zod5.z.union([
1253
+ JsonRpcResponseSuccessSchema.extend({
1254
+ result: KillWorkerSessionResultSchema
1255
+ }),
1256
+ JsonRpcResponseFailureSchema
1257
+ ]);
1258
+ var UpdateSessionSettingsResponseSchema = import_zod5.z.union([
1259
+ JsonRpcResponseSuccessSchema.extend({
1260
+ result: UpdateSessionSettingsResultSchema
1261
+ }),
1262
+ JsonRpcResponseFailureSchema
1263
+ ]);
1264
+ var ToggleMcpServerResponseSchema = import_zod5.z.union([
1265
+ JsonRpcResponseSuccessSchema.extend({
1266
+ result: ToggleMcpServerResultSchema
1267
+ }),
1268
+ JsonRpcResponseFailureSchema
1269
+ ]);
1270
+ var AuthenticateMcpServerResponseSchema = import_zod5.z.union([
1271
+ JsonRpcResponseSuccessSchema.extend({
1272
+ result: AuthenticateMcpServerResultSchema
1273
+ }),
1274
+ JsonRpcResponseFailureSchema
1275
+ ]);
1276
+ var CancelMcpAuthResponseSchema = import_zod5.z.union([
1277
+ JsonRpcResponseSuccessSchema.extend({ result: CancelMcpAuthResultSchema }),
1278
+ JsonRpcResponseFailureSchema
1279
+ ]);
1280
+ var ClearMcpAuthResponseSchema = import_zod5.z.union([
1281
+ JsonRpcResponseSuccessSchema.extend({ result: ClearMcpAuthResultSchema }),
1282
+ JsonRpcResponseFailureSchema
1283
+ ]);
1284
+ var SubmitMcpAuthCodeResponseSchema = import_zod5.z.union([
1285
+ JsonRpcResponseSuccessSchema.extend({
1286
+ result: SubmitMcpAuthCodeResultSchema
1287
+ }),
1288
+ JsonRpcResponseFailureSchema
1289
+ ]);
1290
+ var AddMcpServerResponseSchema = import_zod5.z.union([
1291
+ JsonRpcResponseSuccessSchema.extend({ result: AddMcpServerResultSchema }),
1292
+ JsonRpcResponseFailureSchema
1293
+ ]);
1294
+ var RemoveMcpServerResponseSchema = import_zod5.z.union([
1295
+ JsonRpcResponseSuccessSchema.extend({ result: RemoveMcpServerResultSchema }),
1296
+ JsonRpcResponseFailureSchema
1297
+ ]);
1298
+ var ListMcpRegistryResponseSchema = import_zod5.z.union([
1299
+ JsonRpcResponseSuccessSchema.extend({
1300
+ result: ListMcpRegistryResultSchema
1301
+ }),
1302
+ JsonRpcResponseFailureSchema
1303
+ ]);
1304
+ var ListMcpToolsResponseSchema = import_zod5.z.union([
1305
+ JsonRpcResponseSuccessSchema.extend({ result: ListMcpToolsResultSchema }),
1306
+ JsonRpcResponseFailureSchema
1307
+ ]);
1308
+ var ListMcpServersResponseSchema = import_zod5.z.union([
1309
+ JsonRpcResponseSuccessSchema.extend({ result: ListMcpServersResultSchema }),
1310
+ JsonRpcResponseFailureSchema
1311
+ ]);
1312
+ var ToggleMcpToolResponseSchema = import_zod5.z.union([
1313
+ JsonRpcResponseSuccessSchema.extend({ result: ToggleMcpToolResultSchema }),
1314
+ JsonRpcResponseFailureSchema
1315
+ ]);
1316
+ var ListSkillsResponseSchema = import_zod5.z.union([
1317
+ JsonRpcResponseSuccessSchema.extend({ result: ListSkillsResultSchema }),
1318
+ JsonRpcResponseFailureSchema
1319
+ ]);
1320
+ var SubmitBugReportResponseSchema = import_zod5.z.union([
1321
+ JsonRpcResponseSuccessSchema.extend({ result: SubmitBugReportResultSchema }),
1322
+ JsonRpcResponseFailureSchema
1323
+ ]);
1324
+
1325
+ // src/schemas/server.ts
1326
+ var import_zod6 = require("zod");
1327
+ var ToolUseSchema = import_zod6.z.object({
1328
+ type: import_zod6.z.literal("tool_use"),
1329
+ id: import_zod6.z.string(),
1330
+ input: import_zod6.z.record(import_zod6.z.unknown()),
1331
+ name: import_zod6.z.string(),
1332
+ thoughtSignature: import_zod6.z.string().optional()
1333
+ }).passthrough();
1334
+ var ErrorDetailSchema = import_zod6.z.object({
1335
+ name: import_zod6.z.string(),
1336
+ message: import_zod6.z.string()
1337
+ }).passthrough();
1338
+ var ToolProgressUpdateSchema = import_zod6.z.object({
1339
+ type: import_zod6.z.enum(["tool_call", "tool_result", "error", "status", "message"]),
1340
+ toolName: import_zod6.z.string().optional(),
1341
+ status: import_zod6.z.string().optional(),
1342
+ details: import_zod6.z.string().optional(),
1343
+ text: import_zod6.z.string().optional(),
1344
+ error: import_zod6.z.string().optional(),
1345
+ timestamp: import_zod6.z.number().optional(),
1346
+ parameters: import_zod6.z.record(import_zod6.z.unknown()).optional(),
1347
+ valueSnippet: import_zod6.z.string().optional(),
1348
+ subagentSessionId: import_zod6.z.string().optional()
1349
+ }).passthrough();
1350
+ var SettingsUpdatedPayloadSchema = import_zod6.z.object({
1351
+ autonomyMode: import_zod6.z.nativeEnum(AutonomyMode).optional(),
1352
+ interactionMode: import_zod6.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1353
+ autonomyLevel: import_zod6.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1354
+ modelId: import_zod6.z.string().optional(),
1355
+ reasoningEffort: import_zod6.z.nativeEnum(ReasoningEffort).optional(),
1356
+ specModeModelId: import_zod6.z.string().optional(),
1357
+ specModeReasoningEffort: import_zod6.z.nativeEnum(ReasoningEffort).optional()
1358
+ }).passthrough();
1359
+ var ToolResultNotificationSchema = import_zod6.z.object({
1360
+ type: import_zod6.z.literal("tool_result" /* TOOL_RESULT */),
1361
+ messageId: import_zod6.z.string(),
1362
+ toolUseId: import_zod6.z.string(),
1363
+ content: import_zod6.z.unknown().optional(),
1364
+ isError: import_zod6.z.boolean().optional(),
1365
+ id: import_zod6.z.string().optional()
1366
+ }).passthrough();
1367
+ var ToolProgressUpdateNotificationSchema = import_zod6.z.object({
1368
+ type: import_zod6.z.literal("tool_progress_update" /* TOOL_PROGRESS_UPDATE */),
1369
+ toolUseId: import_zod6.z.string(),
1370
+ toolName: import_zod6.z.string(),
1371
+ update: ToolProgressUpdateSchema
1372
+ }).passthrough();
1373
+ var CreateMessageNotificationSchema = import_zod6.z.object({
1374
+ type: import_zod6.z.literal("create_message" /* CREATE_MESSAGE */),
1375
+ message: FactoryDroidMessageSchema,
1376
+ parentId: import_zod6.z.string().optional(),
1377
+ requestId: import_zod6.z.string().optional()
1378
+ }).passthrough();
1379
+ var ErrorNotificationSchema = import_zod6.z.object({
1380
+ type: import_zod6.z.literal("error" /* ERROR */),
1381
+ message: import_zod6.z.string(),
1382
+ errorType: import_zod6.z.nativeEnum(DroidErrorType),
1383
+ timestamp: import_zod6.z.string(),
1384
+ error: ErrorDetailSchema.optional()
1385
+ }).passthrough();
1386
+ var DroidWorkingStateChangedNotificationSchema = import_zod6.z.object({
1387
+ type: import_zod6.z.literal("droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */),
1388
+ newState: import_zod6.z.nativeEnum(DroidWorkingState)
1389
+ }).passthrough();
1390
+ var PermissionResolvedNotificationSchema = import_zod6.z.object({
1391
+ type: import_zod6.z.literal("permission_resolved" /* PERMISSION_RESOLVED */),
1392
+ requestId: import_zod6.z.string(),
1393
+ toolUseIds: import_zod6.z.array(import_zod6.z.string()),
1394
+ selectedOption: import_zod6.z.nativeEnum(ToolConfirmationOutcome)
1395
+ }).passthrough();
1396
+ var SettingsUpdatedNotificationSchema = import_zod6.z.object({
1397
+ type: import_zod6.z.literal("settings_updated" /* SETTINGS_UPDATED */),
1398
+ settings: SettingsUpdatedPayloadSchema
1399
+ }).passthrough();
1400
+ var SessionTitleUpdatedNotificationSchema = import_zod6.z.object({
1401
+ type: import_zod6.z.literal("session_title_updated" /* SESSION_TITLE_UPDATED */),
1402
+ title: import_zod6.z.string()
1403
+ }).passthrough();
1404
+ var McpStatusChangedNotificationSchema = import_zod6.z.object({
1405
+ type: import_zod6.z.literal("mcp_status_changed" /* MCP_STATUS_CHANGED */),
1406
+ servers: import_zod6.z.array(McpServerStatusInfoSchema),
1407
+ summary: McpStatusSummarySchema
1408
+ }).passthrough();
1409
+ var AssistantTextDeltaNotificationSchema = import_zod6.z.object({
1410
+ type: import_zod6.z.literal("assistant_text_delta" /* ASSISTANT_TEXT_DELTA */),
1411
+ messageId: import_zod6.z.string(),
1412
+ blockIndex: import_zod6.z.number(),
1413
+ textDelta: import_zod6.z.string()
1414
+ }).passthrough();
1415
+ var ThinkingTextDeltaNotificationSchema = import_zod6.z.object({
1416
+ type: import_zod6.z.literal("thinking_text_delta" /* THINKING_TEXT_DELTA */),
1417
+ messageId: import_zod6.z.string(),
1418
+ blockIndex: import_zod6.z.number(),
1419
+ textDelta: import_zod6.z.string()
1420
+ }).passthrough();
1421
+ var SessionTokenUsageChangedNotificationSchema = import_zod6.z.object({
1422
+ type: import_zod6.z.literal("session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */),
1423
+ sessionId: import_zod6.z.string(),
1424
+ tokenUsage: TokenUsageSchema
1425
+ }).passthrough();
1426
+ var MissionStateChangedNotificationSchema = import_zod6.z.object({
1427
+ type: import_zod6.z.literal("mission_state_changed" /* MISSION_STATE_CHANGED */),
1428
+ state: import_zod6.z.nativeEnum(MissionState)
1429
+ }).passthrough();
1430
+ var MissionFeaturesChangedNotificationSchema = import_zod6.z.object({
1431
+ type: import_zod6.z.literal("mission_features_changed" /* MISSION_FEATURES_CHANGED */),
1432
+ features: import_zod6.z.array(MissionFeatureSchema)
1433
+ }).passthrough();
1434
+ var MissionProgressEntryNotificationSchema = import_zod6.z.object({
1435
+ type: import_zod6.z.literal("mission_progress_entry" /* MISSION_PROGRESS_ENTRY */),
1436
+ progressLog: import_zod6.z.array(ProgressLogEntrySchema)
1437
+ }).passthrough();
1438
+ var MissionHeartbeatNotificationSchema = import_zod6.z.object({
1439
+ type: import_zod6.z.literal("mission_heartbeat" /* MISSION_HEARTBEAT */),
1440
+ timestamp: import_zod6.z.string()
1441
+ }).passthrough();
1442
+ var MissionWorkerStartedNotificationSchema = import_zod6.z.object({
1443
+ type: import_zod6.z.literal("mission_worker_started" /* MISSION_WORKER_STARTED */),
1444
+ workerSessionId: import_zod6.z.string()
1445
+ }).passthrough();
1446
+ var MissionWorkerCompletedNotificationSchema = import_zod6.z.object({
1447
+ type: import_zod6.z.literal("mission_worker_completed" /* MISSION_WORKER_COMPLETED */),
1448
+ workerSessionId: import_zod6.z.string(),
1449
+ exitCode: import_zod6.z.number()
1450
+ }).passthrough();
1451
+ var McpAuthRequiredNotificationSchema = import_zod6.z.object({
1452
+ type: import_zod6.z.literal("mcp_auth_required" /* MCP_AUTH_REQUIRED */),
1453
+ serverName: import_zod6.z.string(),
1454
+ authUrl: import_zod6.z.string(),
1455
+ message: import_zod6.z.string(),
1456
+ state: import_zod6.z.string()
1457
+ }).passthrough();
1458
+ var McpAuthCompletedNotificationSchema = import_zod6.z.object({
1459
+ type: import_zod6.z.literal("mcp_auth_completed" /* MCP_AUTH_COMPLETED */),
1460
+ serverName: import_zod6.z.string(),
1461
+ outcome: import_zod6.z.nativeEnum(McpAuthOutcome),
1462
+ message: import_zod6.z.string()
1463
+ }).passthrough();
1464
+ var SessionNotificationSchemaList = [
1465
+ ToolResultNotificationSchema,
1466
+ ToolProgressUpdateNotificationSchema,
1467
+ CreateMessageNotificationSchema,
1468
+ ErrorNotificationSchema,
1469
+ DroidWorkingStateChangedNotificationSchema,
1470
+ PermissionResolvedNotificationSchema,
1471
+ SettingsUpdatedNotificationSchema,
1472
+ SessionTitleUpdatedNotificationSchema,
1473
+ McpStatusChangedNotificationSchema,
1474
+ AssistantTextDeltaNotificationSchema,
1475
+ ThinkingTextDeltaNotificationSchema,
1476
+ SessionTokenUsageChangedNotificationSchema,
1477
+ MissionStateChangedNotificationSchema,
1478
+ MissionFeaturesChangedNotificationSchema,
1479
+ MissionProgressEntryNotificationSchema,
1480
+ MissionHeartbeatNotificationSchema,
1481
+ MissionWorkerStartedNotificationSchema,
1482
+ MissionWorkerCompletedNotificationSchema,
1483
+ McpAuthRequiredNotificationSchema,
1484
+ McpAuthCompletedNotificationSchema
1485
+ ];
1486
+ var SessionNotificationPayloadSchema = import_zod6.z.discriminatedUnion(
1487
+ "type",
1488
+ SessionNotificationSchemaList
1489
+ );
1490
+ var SessionNotificationParamsSchema = import_zod6.z.object({
1491
+ notification: SessionNotificationPayloadSchema
1492
+ }).passthrough();
1493
+ var SessionNotificationSchema = JsonRpcNotificationSchema.extend({
1494
+ method: import_zod6.z.literal("droid.session_notification" /* SESSION_NOTIFICATION */),
1495
+ params: SessionNotificationParamsSchema
1496
+ });
1497
+ var EditToolConfirmationDetailsSchema = import_zod6.z.object({
1498
+ type: import_zod6.z.literal("edit" /* Edit */),
1499
+ filePath: import_zod6.z.string(),
1500
+ fileName: import_zod6.z.string(),
1501
+ oldContent: import_zod6.z.string().optional(),
1502
+ newContent: import_zod6.z.string().optional()
1503
+ }).passthrough();
1504
+ var ExecuteToolConfirmationDetailsSchema = import_zod6.z.object({
1505
+ type: import_zod6.z.literal("exec" /* Execute */),
1506
+ fullCommand: import_zod6.z.string(),
1507
+ command: import_zod6.z.string(),
1508
+ extractedCommands: import_zod6.z.array(import_zod6.z.string()).optional(),
1509
+ impactLevel: import_zod6.z.string().optional()
1510
+ }).passthrough();
1511
+ var CreateToolConfirmationDetailsSchema = import_zod6.z.object({
1512
+ type: import_zod6.z.literal("create" /* Create */),
1513
+ filePath: import_zod6.z.string(),
1514
+ fileName: import_zod6.z.string(),
1515
+ content: import_zod6.z.string()
1516
+ }).passthrough();
1517
+ var AskUserQuestionSchema = import_zod6.z.object({
1518
+ index: import_zod6.z.number(),
1519
+ topic: import_zod6.z.string(),
1520
+ question: import_zod6.z.string(),
1521
+ options: import_zod6.z.array(import_zod6.z.string())
1522
+ }).passthrough();
1523
+ var AskUserConfirmationDetailsSchema = import_zod6.z.object({
1524
+ type: import_zod6.z.literal("ask_user" /* AskUser */),
1525
+ questionnaire: import_zod6.z.string(),
1526
+ parsed: import_zod6.z.object({
1527
+ questions: import_zod6.z.array(AskUserQuestionSchema)
1528
+ }).optional(),
1529
+ parseError: import_zod6.z.object({
1530
+ message: import_zod6.z.string(),
1531
+ line: import_zod6.z.number().optional()
1532
+ }).optional()
1533
+ }).passthrough();
1534
+ var ExitSpecModeConfirmationDetailsSchema = import_zod6.z.object({
1535
+ type: import_zod6.z.literal("exit_spec_mode" /* ExitSpecMode */),
1536
+ plan: import_zod6.z.string(),
1537
+ title: import_zod6.z.string().optional(),
1538
+ optionNames: import_zod6.z.array(import_zod6.z.string()).optional()
1539
+ }).passthrough();
1540
+ var ProposeMissionConfirmationDetailsSchema = import_zod6.z.object({
1541
+ type: import_zod6.z.literal("propose_mission" /* ProposeMission */),
1542
+ proposal: import_zod6.z.string(),
1543
+ title: import_zod6.z.string().optional()
1544
+ }).passthrough();
1545
+ var StartMissionRunConfirmationDetailsSchema = import_zod6.z.object({
1546
+ type: import_zod6.z.literal("start_mission_run" /* StartMissionRun */),
1547
+ runningMissionCount: import_zod6.z.number(),
1548
+ runningMissionSessionIds: import_zod6.z.array(import_zod6.z.string())
1549
+ }).passthrough();
1550
+ var ApplyPatchToolConfirmationDetailsSchema = import_zod6.z.object({
1551
+ type: import_zod6.z.literal("apply_patch" /* ApplyPatch */),
1552
+ filePath: import_zod6.z.string(),
1553
+ fileName: import_zod6.z.string(),
1554
+ patchContent: import_zod6.z.string(),
1555
+ oldContent: import_zod6.z.string().optional(),
1556
+ newContent: import_zod6.z.string().optional()
1557
+ }).passthrough();
1558
+ var McpToolConfirmationDetailsSchema = import_zod6.z.object({
1559
+ type: import_zod6.z.literal("mcp_tool" /* McpTool */),
1560
+ toolName: import_zod6.z.string(),
1561
+ impactLevel: import_zod6.z.string()
1562
+ }).passthrough();
1563
+ var ToolConfirmationDetailsSchema = import_zod6.z.discriminatedUnion("type", [
1564
+ EditToolConfirmationDetailsSchema,
1565
+ ExecuteToolConfirmationDetailsSchema,
1566
+ CreateToolConfirmationDetailsSchema,
1567
+ AskUserConfirmationDetailsSchema,
1568
+ ExitSpecModeConfirmationDetailsSchema,
1569
+ ProposeMissionConfirmationDetailsSchema,
1570
+ StartMissionRunConfirmationDetailsSchema,
1571
+ ApplyPatchToolConfirmationDetailsSchema,
1572
+ McpToolConfirmationDetailsSchema
1573
+ ]);
1574
+ var ToolConfirmationInfoSchema = import_zod6.z.object({
1575
+ toolUse: ToolUseSchema,
1576
+ confirmationType: import_zod6.z.nativeEnum(ToolConfirmationType),
1577
+ details: ToolConfirmationDetailsSchema
1578
+ }).passthrough();
1579
+ var RequestPermissionRequestParamsSchema = import_zod6.z.object({
1580
+ toolUses: import_zod6.z.array(ToolConfirmationInfoSchema),
1581
+ options: import_zod6.z.array(ToolConfirmationListItemSchema)
1582
+ }).passthrough();
1583
+ var RequestPermissionRequestSchema = JsonRpcRequestSchema.extend({
1584
+ method: import_zod6.z.literal("droid.request_permission" /* REQUEST_PERMISSION */),
1585
+ params: RequestPermissionRequestParamsSchema
1586
+ });
1587
+ var RequestPermissionResultSchema = import_zod6.z.object({
1588
+ selectedOption: import_zod6.z.nativeEnum(ToolConfirmationOutcome)
1589
+ }).strict();
1590
+ var RequestPermissionResponseSchema = import_zod6.z.union([
1591
+ JsonRpcResponseSuccessSchema.extend({
1592
+ result: RequestPermissionResultSchema
1593
+ }),
1594
+ JsonRpcResponseFailureSchema
1595
+ ]);
1596
+ var AskUserRequestParamsSchema = import_zod6.z.object({
1597
+ toolCallId: import_zod6.z.string(),
1598
+ questions: import_zod6.z.array(AskUserQuestionSchema)
1599
+ }).passthrough();
1600
+ var AskUserRequestSchema = JsonRpcRequestSchema.extend({
1601
+ method: import_zod6.z.literal("droid.ask_user" /* ASK_USER */),
1602
+ params: AskUserRequestParamsSchema
1603
+ });
1604
+ var AskUserCollectedAnswerSchema = import_zod6.z.object({
1605
+ index: import_zod6.z.number(),
1606
+ question: import_zod6.z.string(),
1607
+ answer: import_zod6.z.string()
1608
+ }).strict();
1609
+ var AskUserResultSchema = import_zod6.z.object({
1610
+ cancelled: import_zod6.z.boolean().optional(),
1611
+ answers: import_zod6.z.array(AskUserCollectedAnswerSchema)
1612
+ }).strict();
1613
+ var AskUserResponseSchema = import_zod6.z.union([
1614
+ JsonRpcResponseSuccessSchema.extend({ result: AskUserResultSchema }),
1615
+ JsonRpcResponseFailureSchema
1616
+ ]);
1617
+ var CliRequestOrNotificationSchema = import_zod6.z.union([
1618
+ SessionNotificationSchema,
1619
+ RequestPermissionRequestSchema,
1620
+ AskUserRequestSchema
1621
+ ]);
1622
+
1623
+ // src/errors.ts
1624
+ var ConnectionError = class _ConnectionError extends Error {
1625
+ /** The working directory used when spawning the process. */
1626
+ cwd;
1627
+ /** The executable path used when spawning the process. */
1628
+ execPath;
1629
+ constructor(message, options) {
1630
+ super(message);
1631
+ this.name = "ConnectionError";
1632
+ this.cwd = options?.cwd ?? "";
1633
+ this.execPath = options?.execPath ?? "";
1634
+ Object.setPrototypeOf(this, _ConnectionError.prototype);
1635
+ }
1636
+ };
1637
+ var ProtocolError = class _ProtocolError extends Error {
1638
+ /** The JSON-RPC error code, if available. */
1639
+ code;
1640
+ /** Additional error data from the JSON-RPC response. */
1641
+ data;
1642
+ constructor(message, options) {
1643
+ super(message);
1644
+ this.name = "ProtocolError";
1645
+ this.code = options?.code;
1646
+ this.data = options?.data;
1647
+ Object.setPrototypeOf(this, _ProtocolError.prototype);
1648
+ }
1649
+ };
1650
+ var SessionError = class _SessionError extends Error {
1651
+ constructor(message) {
1652
+ super(message);
1653
+ this.name = "SessionError";
1654
+ Object.setPrototypeOf(this, _SessionError.prototype);
1655
+ }
1656
+ };
1657
+ var SessionNotFoundError = class _SessionNotFoundError extends SessionError {
1658
+ /** The ID of the session that was not found. */
1659
+ sessionId;
1660
+ constructor(sessionId) {
1661
+ super(`Session not found: ${sessionId}`);
1662
+ this.name = "SessionNotFoundError";
1663
+ this.sessionId = sessionId;
1664
+ Object.setPrototypeOf(this, _SessionNotFoundError.prototype);
1665
+ }
1666
+ };
1667
+ var TimeoutError = class _TimeoutError extends Error {
1668
+ constructor(message) {
1669
+ super(message);
1670
+ this.name = "TimeoutError";
1671
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
1672
+ }
1673
+ };
1674
+ var ProcessExitError = class _ProcessExitError extends Error {
1675
+ /** The exit code of the process, or null if terminated by signal. */
1676
+ exitCode;
1677
+ /** The signal that terminated the process, or null if exited normally. */
1678
+ signal;
1679
+ constructor(message, options) {
1680
+ super(message);
1681
+ this.name = "ProcessExitError";
1682
+ this.exitCode = options?.exitCode ?? null;
1683
+ this.signal = options?.signal ?? null;
1684
+ Object.setPrototypeOf(this, _ProcessExitError.prototype);
1685
+ }
1686
+ };
1687
+
1688
+ // src/transport.ts
1689
+ var import_node_child_process = require("child_process");
1690
+ var readline = __toESM(require("readline"), 1);
1691
+ var DEFAULT_EXEC_ARGS = [
1692
+ "exec",
1693
+ "--input-format",
1694
+ "stream-jsonrpc",
1695
+ "--output-format",
1696
+ "stream-jsonrpc"
1697
+ ];
1698
+ var DEFAULT_GRACE_PERIOD_MS = 5e3;
1699
+ var ProcessTransport = class {
1700
+ execPath;
1701
+ execArgs;
1702
+ cwd;
1703
+ env;
1704
+ gracePeriodMs;
1705
+ childProcess = null;
1706
+ readlineInterface = null;
1707
+ messageHandler = null;
1708
+ errorHandler = null;
1709
+ /**
1710
+ * Sticky error from a process error or unexpected exit. Once set,
1711
+ * all subsequent `send()` calls throw immediately.
1712
+ */
1713
+ processError = null;
1714
+ /** Promise-chain serializer for stdin writes. */
1715
+ writeChain = Promise.resolve();
1716
+ _isConnected = false;
1717
+ isClosing = false;
1718
+ constructor(options = {}) {
1719
+ this.execPath = options.execPath ?? "droid";
1720
+ this.execArgs = options.execArgs ? [...options.execArgs] : [...DEFAULT_EXEC_ARGS];
1721
+ this.cwd = options.cwd;
1722
+ this.env = options.env;
1723
+ this.gracePeriodMs = (options.gracePeriod ?? DEFAULT_GRACE_PERIOD_MS / 1e3) * 1e3;
1724
+ }
1725
+ // -----------------------------------------------------------------------
1726
+ // DroidClientTransport interface
1727
+ // -----------------------------------------------------------------------
1728
+ get isConnected() {
1729
+ return this._isConnected;
1730
+ }
1731
+ async connect() {
1732
+ if (this._isConnected) {
1733
+ throw new ConnectionError("Transport already connected", {
1734
+ execPath: this.execPath
1735
+ });
1736
+ }
1737
+ this.processError = null;
1738
+ this.isClosing = false;
1739
+ this.writeChain = Promise.resolve();
1740
+ const mergedEnv = this.env ? { ...process.env, ...this.env } : void 0;
1741
+ try {
1742
+ this.childProcess = (0, import_node_child_process.spawn)(this.execPath, this.execArgs, {
1743
+ stdio: ["pipe", "pipe", "pipe"],
1744
+ cwd: this.cwd,
1745
+ env: mergedEnv
1746
+ });
1747
+ } catch (err) {
1748
+ const message = err instanceof Error ? `Failed to start droid process: ${err.message}` : "Failed to start droid process";
1749
+ throw new ConnectionError(message, {
1750
+ execPath: this.execPath,
1751
+ cwd: this.cwd
1752
+ });
1753
+ }
1754
+ this._isConnected = true;
1755
+ this.setupHandlers();
1756
+ }
1757
+ send(message) {
1758
+ if (this.processError) {
1759
+ throw this.processError;
1760
+ }
1761
+ if (!this._isConnected || !this.childProcess || !this.childProcess.stdin) {
1762
+ throw new ConnectionError("Transport not connected", {
1763
+ execPath: this.execPath
1764
+ });
1765
+ }
1766
+ const line = JSON.stringify(message) + "\n";
1767
+ const previousChain = this.writeChain;
1768
+ this.writeChain = (async () => {
1769
+ await previousChain.catch(() => {
1770
+ });
1771
+ if (!this.childProcess || !this.childProcess.stdin || this.childProcess.killed || this.isClosing) {
1772
+ throw new ConnectionError("Process disconnected before write", {
1773
+ execPath: this.execPath
1774
+ });
1775
+ }
1776
+ if (this.processError) {
1777
+ throw this.processError;
1778
+ }
1779
+ await new Promise((resolve, reject) => {
1780
+ if (!this.childProcess || !this.childProcess.stdin) {
1781
+ reject(
1782
+ new ConnectionError("Process stdin unavailable", {
1783
+ execPath: this.execPath
1784
+ })
1785
+ );
1786
+ return;
1787
+ }
1788
+ const stdin = this.childProcess.stdin;
1789
+ if ("writable" in stdin && !stdin.writable) {
1790
+ reject(
1791
+ new ConnectionError("Process stdin is not writable", {
1792
+ execPath: this.execPath
1793
+ })
1794
+ );
1795
+ return;
1796
+ }
1797
+ stdin.write(line, (error) => {
1798
+ if (error) {
1799
+ const msg = error.message || String(error);
1800
+ if (msg.includes("EPIPE") || msg.includes("ECONNRESET")) {
1801
+ reject(
1802
+ new ConnectionError("Process stdin closed during write", {
1803
+ execPath: this.execPath
1804
+ })
1805
+ );
1806
+ } else {
1807
+ reject(
1808
+ new ConnectionError(
1809
+ `Failed to write to process stdin: ${msg}`,
1810
+ { execPath: this.execPath }
1811
+ )
1812
+ );
1813
+ }
1814
+ } else {
1815
+ resolve();
1816
+ }
1817
+ });
1818
+ });
1819
+ })();
1820
+ }
1821
+ onMessage(callback) {
1822
+ this.messageHandler = callback;
1823
+ }
1824
+ onError(callback) {
1825
+ this.errorHandler = callback;
1826
+ }
1827
+ async close() {
1828
+ if (this.isClosing) {
1829
+ return;
1830
+ }
1831
+ this.isClosing = true;
1832
+ this._isConnected = false;
1833
+ const proc = this.childProcess;
1834
+ this.childProcess = null;
1835
+ if (this.readlineInterface) {
1836
+ this.readlineInterface.close();
1837
+ this.readlineInterface = null;
1838
+ }
1839
+ if (proc && proc.exitCode === null && !proc.killed) {
1840
+ await new Promise((resolve) => {
1841
+ const timeout = setTimeout(() => {
1842
+ if (proc.exitCode === null && !proc.killed) {
1843
+ try {
1844
+ proc.kill("SIGKILL");
1845
+ } catch {
1846
+ }
1847
+ }
1848
+ }, this.gracePeriodMs);
1849
+ proc.once("exit", () => {
1850
+ clearTimeout(timeout);
1851
+ resolve();
1852
+ });
1853
+ if (proc.stdin) {
1854
+ try {
1855
+ proc.stdin.end();
1856
+ } catch {
1857
+ }
1858
+ }
1859
+ try {
1860
+ proc.kill("SIGTERM");
1861
+ } catch {
1862
+ clearTimeout(timeout);
1863
+ resolve();
1864
+ }
1865
+ });
1866
+ }
1867
+ this.isClosing = false;
1868
+ }
1869
+ // -----------------------------------------------------------------------
1870
+ // Private helpers
1871
+ // -----------------------------------------------------------------------
1872
+ setupHandlers() {
1873
+ const proc = this.childProcess;
1874
+ if (!proc || !proc.stdout) {
1875
+ return;
1876
+ }
1877
+ this.readlineInterface = readline.createInterface({
1878
+ input: proc.stdout,
1879
+ crlfDelay: Infinity
1880
+ });
1881
+ this.readlineInterface.on("line", (line) => {
1882
+ const trimmed = line.trim();
1883
+ if (!trimmed) {
1884
+ return;
1885
+ }
1886
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1887
+ try {
1888
+ const parsed = JSON.parse(trimmed);
1889
+ if (this.messageHandler && typeof parsed === "object" && parsed !== null) {
1890
+ this.messageHandler(parsed);
1891
+ }
1892
+ } catch {
1893
+ }
1894
+ }
1895
+ });
1896
+ proc.on("error", (error) => {
1897
+ this.processError = new ConnectionError(
1898
+ `Failed to start droid process: ${error.message}`,
1899
+ {
1900
+ execPath: this.execPath,
1901
+ cwd: this.cwd
1902
+ }
1903
+ );
1904
+ this._isConnected = false;
1905
+ if (!this.isClosing && this.errorHandler) {
1906
+ this.errorHandler(this.processError);
1907
+ }
1908
+ });
1909
+ proc.on("exit", (code, signal) => {
1910
+ if (this.readlineInterface) {
1911
+ this.readlineInterface.close();
1912
+ this.readlineInterface = null;
1913
+ }
1914
+ this._isConnected = false;
1915
+ if (!this.isClosing) {
1916
+ const exitCode = code ?? null;
1917
+ const exitSignal = signal ?? null;
1918
+ let message;
1919
+ if (exitSignal) {
1920
+ message = `Droid process was killed (${exitSignal})`;
1921
+ } else if (exitCode !== null && exitCode !== 0) {
1922
+ message = `Droid process exited unexpectedly (exit code ${exitCode})`;
1923
+ } else if (exitCode === 0) {
1924
+ message = "Droid process exited normally";
1925
+ } else {
1926
+ message = "Droid process exited unexpectedly";
1927
+ }
1928
+ this.processError = new ProcessExitError(message, {
1929
+ exitCode,
1930
+ signal: exitSignal
1931
+ });
1932
+ if (this.errorHandler) {
1933
+ this.errorHandler(this.processError);
1934
+ }
1935
+ }
1936
+ });
1937
+ }
1938
+ };
1939
+
1940
+ // src/protocol.ts
1941
+ var import_uuid = require("uuid");
1942
+ var ProtocolEngine = class {
1943
+ _transport;
1944
+ _defaultTimeout;
1945
+ /** Pending requests keyed by UUID string. */
1946
+ _pendingRequests = /* @__PURE__ */ new Map();
1947
+ /** Notification listener registry. */
1948
+ _notificationListeners = /* @__PURE__ */ new Set();
1949
+ /** Server→client request handlers. */
1950
+ _permissionHandler = null;
1951
+ _askUserHandler = null;
1952
+ /** Sticky transport error — once set, all requests fail immediately. */
1953
+ _transportError = null;
1954
+ /** Closed flag — once true, new requests are rejected. */
1955
+ _closed = false;
1956
+ /**
1957
+ * Create a new ProtocolEngine.
1958
+ *
1959
+ * @param options.transport - A connected DroidClientTransport implementation.
1960
+ * @param options.defaultTimeout - Default timeout in ms for sendRequest (default 30 000).
1961
+ */
1962
+ constructor(options) {
1963
+ this._transport = options.transport;
1964
+ this._defaultTimeout = options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1965
+ this._transport.onMessage((message) => {
1966
+ this._handleMessage(message);
1967
+ });
1968
+ this._transport.onError((error) => {
1969
+ this._handleTransportError(error);
1970
+ });
1971
+ }
1972
+ // ------------------------------------------------------------------
1973
+ // Public API: Sending requests
1974
+ // ------------------------------------------------------------------
1975
+ /**
1976
+ * Send a JSON-RPC request and wait for the response.
1977
+ *
1978
+ * Constructs the full envelope, registers a pending promise, sends
1979
+ * via transport, and returns the parsed response `result` field.
1980
+ *
1981
+ * @param method - The RPC method name (e.g. `"droid.list_skills"`).
1982
+ * @param params - Method parameters object.
1983
+ * @param timeout - Timeout in ms. Defaults to `defaultTimeout`.
1984
+ * @returns The `result` field from the JSON-RPC success response.
1985
+ * @throws {ConnectionError} If the engine is closed.
1986
+ * @throws {ConnectionError} If the transport has a sticky error.
1987
+ * @throws {TimeoutError} If no response arrives within the timeout.
1988
+ * @throws {ProtocolError} If the response contains a protocol error.
1989
+ * @throws {SessionNotFoundError} If error code is ENTITY_NOT_FOUND.
1990
+ */
1991
+ async sendRequest(method, params, timeout) {
1992
+ if (this._closed) {
1993
+ throw new ConnectionError("Protocol engine is closed");
1994
+ }
1995
+ if (this._transportError !== null) {
1996
+ throw new ConnectionError(
1997
+ `Transport error: ${this._transportError.message}`
1998
+ );
1999
+ }
2000
+ const effectiveTimeout = timeout ?? this._defaultTimeout;
2001
+ const requestId = (0, import_uuid.v4)();
2002
+ const envelope = {
2003
+ jsonrpc: JSONRPC_VERSION,
2004
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2005
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2006
+ type: "request",
2007
+ id: requestId,
2008
+ method,
2009
+ params
2010
+ };
2011
+ return new Promise((resolve, reject) => {
2012
+ const timer = setTimeout(() => {
2013
+ this._pendingRequests.delete(requestId);
2014
+ reject(
2015
+ new TimeoutError(
2016
+ `Request ${method} timed out after ${effectiveTimeout}ms`
2017
+ )
2018
+ );
2019
+ }, effectiveTimeout);
2020
+ const pending = {
2021
+ method,
2022
+ requestId,
2023
+ params,
2024
+ resolve,
2025
+ reject,
2026
+ timer
2027
+ };
2028
+ this._pendingRequests.set(requestId, pending);
2029
+ try {
2030
+ this._transport.send(envelope);
2031
+ } catch (sendError) {
2032
+ clearTimeout(timer);
2033
+ this._pendingRequests.delete(requestId);
2034
+ if (sendError instanceof Error) {
2035
+ reject(
2036
+ new ConnectionError(`Failed to send request: ${sendError.message}`)
2037
+ );
2038
+ } else {
2039
+ reject(new ConnectionError("Failed to send request"));
2040
+ }
2041
+ }
2042
+ });
2043
+ }
2044
+ // ------------------------------------------------------------------
2045
+ // Public API: Notification listeners
2046
+ // ------------------------------------------------------------------
2047
+ /**
2048
+ * Register a callback for incoming notification messages.
2049
+ *
2050
+ * Multiple listeners can be registered. Each receives the full
2051
+ * parsed notification object.
2052
+ *
2053
+ * @param callback - Invoked with the notification object.
2054
+ * @param filter - Optional filter to only receive specific notification types.
2055
+ * @returns An unsubscribe function. Calling it again is safe (no-op).
2056
+ */
2057
+ onNotification(callback, filter) {
2058
+ const listener = { callback, filter };
2059
+ this._notificationListeners.add(listener);
2060
+ let unsubscribed = false;
2061
+ return () => {
2062
+ if (!unsubscribed) {
2063
+ unsubscribed = true;
2064
+ this._notificationListeners.delete(listener);
2065
+ }
2066
+ };
2067
+ }
2068
+ // ------------------------------------------------------------------
2069
+ // Public API: Server→client request handlers
2070
+ // ------------------------------------------------------------------
2071
+ /**
2072
+ * Register a handler for server→client permission requests.
2073
+ *
2074
+ * The handler receives the request params and should return a
2075
+ * ToolConfirmationOutcome string value.
2076
+ *
2077
+ * Replaces any previously registered handler.
2078
+ */
2079
+ setPermissionHandler(handler) {
2080
+ this._permissionHandler = handler;
2081
+ }
2082
+ /**
2083
+ * Remove the permission request handler (restores default Cancel).
2084
+ */
2085
+ clearPermissionHandler() {
2086
+ this._permissionHandler = null;
2087
+ }
2088
+ /**
2089
+ * Register a handler for server→client ask-user requests.
2090
+ *
2091
+ * The handler receives the request params and should return
2092
+ * a result object with `cancelled` and `answers` keys.
2093
+ *
2094
+ * Replaces any previously registered handler.
2095
+ */
2096
+ setAskUserHandler(handler) {
2097
+ this._askUserHandler = handler;
2098
+ }
2099
+ /**
2100
+ * Remove the ask-user request handler (restores default cancelled=true).
2101
+ */
2102
+ clearAskUserHandler() {
2103
+ this._askUserHandler = null;
2104
+ }
2105
+ // ------------------------------------------------------------------
2106
+ // Public API: Health check
2107
+ // ------------------------------------------------------------------
2108
+ /**
2109
+ * Whether the engine is in a healthy state — not closed and no
2110
+ * sticky transport error.
2111
+ */
2112
+ get isHealthy() {
2113
+ return !this._closed && this._transportError === null;
2114
+ }
2115
+ // ------------------------------------------------------------------
2116
+ // Public API: Close
2117
+ // ------------------------------------------------------------------
2118
+ /**
2119
+ * Close the protocol engine.
2120
+ *
2121
+ * Rejects all pending requests, closes the transport, and prevents
2122
+ * new requests. Idempotent — safe to call multiple times.
2123
+ */
2124
+ async close() {
2125
+ if (this._closed) {
2126
+ return;
2127
+ }
2128
+ this._closed = true;
2129
+ const error = new ConnectionError(
2130
+ "Protocol engine closed: pending requests cancelled"
2131
+ );
2132
+ this._rejectAllPending(error);
2133
+ this._permissionHandler = null;
2134
+ this._askUserHandler = null;
2135
+ this._notificationListeners.clear();
2136
+ await this._transport.close();
2137
+ }
2138
+ // ------------------------------------------------------------------
2139
+ // Internal: Message handling
2140
+ // ------------------------------------------------------------------
2141
+ /**
2142
+ * Handle an incoming parsed message from the transport.
2143
+ * Dispatches to response handler, notification handler, or
2144
+ * server→client request handler based on message type.
2145
+ */
2146
+ _handleMessage(parsed) {
2147
+ const msgType = parsed["type"];
2148
+ if (msgType === "response") {
2149
+ this._handleResponse(parsed);
2150
+ } else if (msgType === "notification") {
2151
+ this._handleNotification(parsed);
2152
+ } else if (msgType === "request") {
2153
+ void this._handleServerRequest(parsed);
2154
+ } else {
2155
+ if ("result" in parsed || "error" in parsed) {
2156
+ this._handleResponse(parsed);
2157
+ } else if ("method" in parsed && !("id" in parsed)) {
2158
+ this._handleNotification(parsed);
2159
+ } else if ("method" in parsed && "id" in parsed) {
2160
+ void this._handleServerRequest(parsed);
2161
+ }
2162
+ }
2163
+ }
2164
+ /**
2165
+ * Handle an incoming response message.
2166
+ * Matches by ID to resolve the correct pending Promise.
2167
+ */
2168
+ _handleResponse(response) {
2169
+ const responseId = response["id"];
2170
+ if (responseId == null) {
2171
+ return;
2172
+ }
2173
+ const pending = this._pendingRequests.get(responseId);
2174
+ if (pending == null) {
2175
+ return;
2176
+ }
2177
+ this._pendingRequests.delete(responseId);
2178
+ clearTimeout(pending.timer);
2179
+ const errorObj = response["error"];
2180
+ if (errorObj != null && typeof errorObj === "object") {
2181
+ const error = errorObj;
2182
+ const code = error["code"];
2183
+ const message = error["message"] ?? "Unknown error";
2184
+ const data = error["data"];
2185
+ if (code === -32004 /* ENTITY_NOT_FOUND */) {
2186
+ const sessionId = String(
2187
+ pending.params["sessionId"] ?? pending.requestId
2188
+ );
2189
+ pending.reject(new SessionNotFoundError(sessionId));
2190
+ return;
2191
+ }
2192
+ pending.reject(new ProtocolError(message, { code, data }));
2193
+ return;
2194
+ }
2195
+ pending.resolve(response);
2196
+ }
2197
+ /**
2198
+ * Handle an incoming notification message.
2199
+ * Dispatches to all registered notification listeners that match.
2200
+ */
2201
+ _handleNotification(notification) {
2202
+ const params = notification["params"];
2203
+ const innerNotification = params?.["notification"];
2204
+ const notificationType = innerNotification?.["type"];
2205
+ for (const listener of this._notificationListeners) {
2206
+ if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2207
+ continue;
2208
+ }
2209
+ try {
2210
+ listener.callback(notification);
2211
+ } catch {
2212
+ }
2213
+ }
2214
+ }
2215
+ /**
2216
+ * Handle an incoming server→client request.
2217
+ * Dispatches to the appropriate handler based on the method field.
2218
+ */
2219
+ async _handleServerRequest(request) {
2220
+ const method = request["method"];
2221
+ const requestId = request["id"];
2222
+ const params = request["params"] ?? {};
2223
+ if (method === "droid.request_permission" /* REQUEST_PERMISSION */) {
2224
+ await this._handlePermissionRequest(requestId, params);
2225
+ } else if (method === "droid.ask_user" /* ASK_USER */) {
2226
+ await this._handleAskUserRequest(requestId, params);
2227
+ }
2228
+ }
2229
+ /**
2230
+ * Handle droid.request_permission server→client request.
2231
+ */
2232
+ async _handlePermissionRequest(requestId, params) {
2233
+ const handler = this._permissionHandler;
2234
+ if (handler == null) {
2235
+ this._sendResponse(requestId, { selectedOption: "cancel" });
2236
+ return;
2237
+ }
2238
+ try {
2239
+ const selectedOption = await Promise.resolve(handler(params));
2240
+ this._sendResponse(requestId, { selectedOption });
2241
+ } catch (exc) {
2242
+ const errorMessage = exc instanceof Error ? exc.message : String(exc);
2243
+ this._sendErrorResponse(
2244
+ requestId,
2245
+ -32603 /* INTERNAL_ERROR */,
2246
+ "Failed to handle permission request",
2247
+ errorMessage
2248
+ );
2249
+ }
2250
+ }
2251
+ /**
2252
+ * Handle droid.ask_user server→client request.
2253
+ */
2254
+ async _handleAskUserRequest(requestId, params) {
2255
+ const handler = this._askUserHandler;
2256
+ if (handler == null) {
2257
+ this._sendResponse(requestId, { cancelled: true, answers: [] });
2258
+ return;
2259
+ }
2260
+ try {
2261
+ const result = await Promise.resolve(handler(params));
2262
+ this._sendResponse(requestId, result);
2263
+ } catch (exc) {
2264
+ const errorMessage = exc instanceof Error ? exc.message : String(exc);
2265
+ this._sendErrorResponse(
2266
+ requestId,
2267
+ -32603 /* INTERNAL_ERROR */,
2268
+ "Failed to handle ask-user request",
2269
+ errorMessage
2270
+ );
2271
+ }
2272
+ }
2273
+ // ------------------------------------------------------------------
2274
+ // Internal: Transport error handling
2275
+ // ------------------------------------------------------------------
2276
+ /**
2277
+ * Handle a transport error.
2278
+ * Sets the sticky transport error and rejects all pending requests.
2279
+ * The original error is preserved as `cause` on the ConnectionError.
2280
+ */
2281
+ _handleTransportError(error) {
2282
+ this._transportError = error;
2283
+ const connectionError = new ConnectionError(
2284
+ `Transport error: ${error.message}`
2285
+ );
2286
+ connectionError.cause = error;
2287
+ this._rejectAllPending(connectionError);
2288
+ }
2289
+ // ------------------------------------------------------------------
2290
+ // Internal: Response helpers
2291
+ // ------------------------------------------------------------------
2292
+ /**
2293
+ * Send a JSON-RPC success response back to the server.
2294
+ */
2295
+ _sendResponse(requestId, result) {
2296
+ const response = {
2297
+ jsonrpc: JSONRPC_VERSION,
2298
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2299
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2300
+ type: "response",
2301
+ id: requestId,
2302
+ result
2303
+ };
2304
+ try {
2305
+ this._transport.send(response);
2306
+ } catch {
2307
+ }
2308
+ }
2309
+ /**
2310
+ * Send a JSON-RPC error response back to the server.
2311
+ */
2312
+ _sendErrorResponse(requestId, code, message, data) {
2313
+ const errorObj = { code, message };
2314
+ if (data !== void 0) {
2315
+ errorObj["data"] = data;
2316
+ }
2317
+ const response = {
2318
+ jsonrpc: JSONRPC_VERSION,
2319
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2320
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2321
+ type: "response",
2322
+ id: requestId,
2323
+ error: errorObj
2324
+ };
2325
+ try {
2326
+ this._transport.send(response);
2327
+ } catch {
2328
+ }
2329
+ }
2330
+ /**
2331
+ * Reject all pending requests with the given error.
2332
+ */
2333
+ _rejectAllPending(error) {
2334
+ const pending = new Map(this._pendingRequests);
2335
+ this._pendingRequests.clear();
2336
+ for (const req of pending.values()) {
2337
+ clearTimeout(req.timer);
2338
+ req.reject(error);
2339
+ }
2340
+ }
2341
+ };
2342
+
2343
+ // src/client.ts
2344
+ var DroidClient = class {
2345
+ _engine;
2346
+ _sessionId = null;
2347
+ _closed = false;
2348
+ /**
2349
+ * Client-level notification listeners.
2350
+ * Each entry is [callback, optional type filter string].
2351
+ */
2352
+ _notificationListeners = [];
2353
+ /** Client-level permission handler. */
2354
+ _permissionHandler = null;
2355
+ /** Client-level ask-user handler. */
2356
+ _askUserHandler = null;
2357
+ constructor(options) {
2358
+ this._engine = new ProtocolEngine({
2359
+ transport: options.transport,
2360
+ defaultTimeout: options.defaultTimeout
2361
+ });
2362
+ this._engine.onNotification((notification) => {
2363
+ this._dispatchNotification(notification);
2364
+ });
2365
+ this._engine.setPermissionHandler(
2366
+ (params) => this._dispatchPermissionRequest(params)
2367
+ );
2368
+ this._engine.setAskUserHandler(
2369
+ (params) => this._dispatchAskUserRequest(params)
2370
+ );
2371
+ }
2372
+ // ------------------------------------------------------------------
2373
+ // Properties
2374
+ // ------------------------------------------------------------------
2375
+ /**
2376
+ * Current session ID, or `null` if no session is active.
2377
+ */
2378
+ get sessionId() {
2379
+ return this._sessionId;
2380
+ }
2381
+ /**
2382
+ * Whether the client is in a healthy state — not closed and no
2383
+ * transport errors have occurred. Returns false after transport
2384
+ * disconnect/error.
2385
+ */
2386
+ get isConnected() {
2387
+ return !this._closed && this._engine.isHealthy;
2388
+ }
2389
+ // ------------------------------------------------------------------
2390
+ // Session lifecycle methods
2391
+ // ------------------------------------------------------------------
2392
+ /**
2393
+ * Initialize a new session.
2394
+ *
2395
+ * Sends `droid.initialize_session` with extended timeout. On success,
2396
+ * stores the session ID internally and returns the typed result.
2397
+ */
2398
+ async initializeSession(params) {
2399
+ this._ensureNotClosed();
2400
+ const response = await this._engine.sendRequest(
2401
+ "droid.initialize_session" /* INITIALIZE_SESSION */,
2402
+ params,
2403
+ SESSION_INIT_TIMEOUT
2404
+ );
2405
+ const result = response["result"];
2406
+ if (result) {
2407
+ this._sessionId = result.sessionId;
2408
+ return result;
2409
+ }
2410
+ if ("sessionId" in response) {
2411
+ this._sessionId = response["sessionId"];
2412
+ return response;
2413
+ }
2414
+ return response;
2415
+ }
2416
+ /**
2417
+ * Load an existing session.
2418
+ *
2419
+ * Sends `droid.load_session`. SessionNotFoundError is thrown for
2420
+ * non-existent sessions (mapped from ENTITY_NOT_FOUND by the protocol engine).
2421
+ */
2422
+ async loadSession(params) {
2423
+ this._ensureNotClosed();
2424
+ const response = await this._engine.sendRequest(
2425
+ "droid.load_session" /* LOAD_SESSION */,
2426
+ params,
2427
+ SESSION_INIT_TIMEOUT
2428
+ );
2429
+ const result = response["result"];
2430
+ if (result) {
2431
+ this._sessionId = params.sessionId;
2432
+ return result;
2433
+ }
2434
+ this._sessionId = params.sessionId;
2435
+ return response;
2436
+ }
2437
+ /**
2438
+ * Add a user message to the active session.
2439
+ *
2440
+ * Sends `droid.add_user_message` with text and optional images/files.
2441
+ */
2442
+ async addUserMessage(params) {
2443
+ this._ensureNotClosed();
2444
+ this._ensureSession();
2445
+ const response = await this._engine.sendRequest(
2446
+ "droid.add_user_message" /* ADD_USER_MESSAGE */,
2447
+ params
2448
+ );
2449
+ const result = response["result"];
2450
+ return result ?? response;
2451
+ }
2452
+ /**
2453
+ * Interrupt the current session.
2454
+ *
2455
+ * Sends `droid.interrupt_session` with empty params.
2456
+ */
2457
+ async interruptSession() {
2458
+ this._ensureNotClosed();
2459
+ this._ensureSession();
2460
+ const response = await this._engine.sendRequest(
2461
+ "droid.interrupt_session" /* INTERRUPT_SESSION */,
2462
+ {}
2463
+ );
2464
+ const result = response["result"];
2465
+ return result ?? response;
2466
+ }
2467
+ /**
2468
+ * Kill a worker session.
2469
+ *
2470
+ * Sends `droid.kill_worker_session`.
2471
+ */
2472
+ async killWorkerSession(params) {
2473
+ this._ensureNotClosed();
2474
+ this._ensureSession();
2475
+ const response = await this._engine.sendRequest(
2476
+ "droid.kill_worker_session" /* KILL_WORKER_SESSION */,
2477
+ params
2478
+ );
2479
+ const result = response["result"];
2480
+ return result ?? response;
2481
+ }
2482
+ /**
2483
+ * Update session settings.
2484
+ *
2485
+ * Sends `droid.update_session_settings` with the provided partial settings.
2486
+ */
2487
+ async updateSessionSettings(params) {
2488
+ this._ensureNotClosed();
2489
+ this._ensureSession();
2490
+ const response = await this._engine.sendRequest(
2491
+ "droid.update_session_settings" /* UPDATE_SESSION_SETTINGS */,
2492
+ params
2493
+ );
2494
+ const result = response["result"];
2495
+ return result ?? response;
2496
+ }
2497
+ // ------------------------------------------------------------------
2498
+ // MCP methods
2499
+ // ------------------------------------------------------------------
2500
+ /**
2501
+ * Toggle an MCP server on or off.
2502
+ */
2503
+ async toggleMcpServer(params) {
2504
+ this._ensureNotClosed();
2505
+ this._ensureSession();
2506
+ const response = await this._engine.sendRequest(
2507
+ "droid.toggle_mcp_server" /* TOGGLE_MCP_SERVER */,
2508
+ params
2509
+ );
2510
+ const result = response["result"];
2511
+ return result ?? response;
2512
+ }
2513
+ /**
2514
+ * Authenticate an MCP server (OAuth flow).
2515
+ * Uses extended timeout (300s) since OAuth requires user interaction.
2516
+ */
2517
+ async authenticateMcpServer(params) {
2518
+ this._ensureNotClosed();
2519
+ this._ensureSession();
2520
+ const response = await this._engine.sendRequest(
2521
+ "droid.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */,
2522
+ params,
2523
+ MCP_AUTH_TIMEOUT
2524
+ );
2525
+ const result = response["result"];
2526
+ return result ?? response;
2527
+ }
2528
+ /**
2529
+ * Cancel an in-progress MCP authentication.
2530
+ */
2531
+ async cancelMcpAuth(params) {
2532
+ this._ensureNotClosed();
2533
+ this._ensureSession();
2534
+ const response = await this._engine.sendRequest(
2535
+ "droid.cancel_mcp_auth" /* CANCEL_MCP_AUTH */,
2536
+ params
2537
+ );
2538
+ const result = response["result"];
2539
+ return result ?? response;
2540
+ }
2541
+ /**
2542
+ * Clear stored MCP authentication tokens.
2543
+ */
2544
+ async clearMcpAuth(params) {
2545
+ this._ensureNotClosed();
2546
+ this._ensureSession();
2547
+ const response = await this._engine.sendRequest(
2548
+ "droid.clear_mcp_auth" /* CLEAR_MCP_AUTH */,
2549
+ params
2550
+ );
2551
+ const result = response["result"];
2552
+ return result ?? response;
2553
+ }
2554
+ /**
2555
+ * Submit an MCP authentication code (OAuth callback).
2556
+ */
2557
+ async submitMcpAuthCode(params) {
2558
+ this._ensureNotClosed();
2559
+ this._ensureSession();
2560
+ const response = await this._engine.sendRequest(
2561
+ "droid.submit_mcp_auth_code" /* SUBMIT_MCP_AUTH_CODE */,
2562
+ params
2563
+ );
2564
+ const result = response["result"];
2565
+ return result ?? response;
2566
+ }
2567
+ /**
2568
+ * Add an MCP server.
2569
+ */
2570
+ async addMcpServer(params) {
2571
+ this._ensureNotClosed();
2572
+ this._ensureSession();
2573
+ const response = await this._engine.sendRequest(
2574
+ "droid.add_mcp_server" /* ADD_MCP_SERVER */,
2575
+ params
2576
+ );
2577
+ const result = response["result"];
2578
+ return result ?? response;
2579
+ }
2580
+ /**
2581
+ * Remove an MCP server.
2582
+ */
2583
+ async removeMcpServer(params) {
2584
+ this._ensureNotClosed();
2585
+ this._ensureSession();
2586
+ const response = await this._engine.sendRequest(
2587
+ "droid.remove_mcp_server" /* REMOVE_MCP_SERVER */,
2588
+ params
2589
+ );
2590
+ const result = response["result"];
2591
+ return result ?? response;
2592
+ }
2593
+ /**
2594
+ * List available MCP registry servers.
2595
+ */
2596
+ async listMcpRegistry() {
2597
+ this._ensureNotClosed();
2598
+ this._ensureSession();
2599
+ const response = await this._engine.sendRequest(
2600
+ "droid.list_mcp_registry" /* LIST_MCP_REGISTRY */,
2601
+ {}
2602
+ );
2603
+ const result = response["result"];
2604
+ return result ?? response;
2605
+ }
2606
+ /**
2607
+ * List available MCP tools.
2608
+ */
2609
+ async listMcpTools() {
2610
+ this._ensureNotClosed();
2611
+ this._ensureSession();
2612
+ const response = await this._engine.sendRequest(
2613
+ "droid.list_mcp_tools" /* LIST_MCP_TOOLS */,
2614
+ {}
2615
+ );
2616
+ const result = response["result"];
2617
+ return result ?? response;
2618
+ }
2619
+ /**
2620
+ * List MCP servers with status and summary.
2621
+ */
2622
+ async listMcpServers() {
2623
+ this._ensureNotClosed();
2624
+ this._ensureSession();
2625
+ const response = await this._engine.sendRequest(
2626
+ "droid.list_mcp_servers" /* LIST_MCP_SERVERS */,
2627
+ {}
2628
+ );
2629
+ const result = response["result"];
2630
+ return result ?? response;
2631
+ }
2632
+ /**
2633
+ * Toggle an MCP tool on or off.
2634
+ */
2635
+ async toggleMcpTool(params) {
2636
+ this._ensureNotClosed();
2637
+ this._ensureSession();
2638
+ const response = await this._engine.sendRequest(
2639
+ "droid.toggle_mcp_tool" /* TOGGLE_MCP_TOOL */,
2640
+ params
2641
+ );
2642
+ const result = response["result"];
2643
+ return result ?? response;
2644
+ }
2645
+ // ------------------------------------------------------------------
2646
+ // Skills and bug report methods
2647
+ // ------------------------------------------------------------------
2648
+ /**
2649
+ * List available skills.
2650
+ */
2651
+ async listSkills() {
2652
+ this._ensureNotClosed();
2653
+ this._ensureSession();
2654
+ const response = await this._engine.sendRequest(
2655
+ "droid.list_skills" /* LIST_SKILLS */,
2656
+ {}
2657
+ );
2658
+ const result = response["result"];
2659
+ return result ?? response;
2660
+ }
2661
+ /**
2662
+ * Submit a bug report.
2663
+ */
2664
+ async submitBugReport(params) {
2665
+ this._ensureNotClosed();
2666
+ this._ensureSession();
2667
+ const response = await this._engine.sendRequest(
2668
+ "droid.submit_bug_report" /* SUBMIT_BUG_REPORT */,
2669
+ params
2670
+ );
2671
+ const result = response["result"];
2672
+ return result ?? response;
2673
+ }
2674
+ // ------------------------------------------------------------------
2675
+ // Notification subscription
2676
+ // ------------------------------------------------------------------
2677
+ /**
2678
+ * Register a callback for incoming notification messages.
2679
+ *
2680
+ * Multiple listeners can be registered. Each receives the full parsed
2681
+ * notification object. Optionally filter by notification type.
2682
+ *
2683
+ * Listener exceptions are isolated — if one raises, others still receive
2684
+ * the event and the engine continues.
2685
+ *
2686
+ * @param callback - Invoked with the notification object.
2687
+ * @param filter - Optional filter to only receive specific notification types.
2688
+ * @returns An unsubscribe function. Calling it again is safe (no-op).
2689
+ */
2690
+ onNotification(callback, filter) {
2691
+ const entry = {
2692
+ callback,
2693
+ typeFilter: filter?.type
2694
+ };
2695
+ this._notificationListeners.push(entry);
2696
+ let unsubscribed = false;
2697
+ return () => {
2698
+ if (!unsubscribed) {
2699
+ unsubscribed = true;
2700
+ const idx = this._notificationListeners.indexOf(entry);
2701
+ if (idx !== -1) {
2702
+ this._notificationListeners.splice(idx, 1);
2703
+ }
2704
+ }
2705
+ };
2706
+ }
2707
+ // ------------------------------------------------------------------
2708
+ // Permission/ask-user handler registration
2709
+ // ------------------------------------------------------------------
2710
+ /**
2711
+ * Register a handler for server→client permission requests.
2712
+ *
2713
+ * The handler receives the request params and should return a
2714
+ * ToolConfirmationOutcome string value. Async handlers are awaited.
2715
+ * Replaces any previously registered handler.
2716
+ */
2717
+ setPermissionHandler(handler) {
2718
+ this._permissionHandler = handler;
2719
+ }
2720
+ /**
2721
+ * Remove the permission request handler.
2722
+ * Restores default behavior: return "cancel".
2723
+ */
2724
+ clearPermissionHandler() {
2725
+ this._permissionHandler = null;
2726
+ }
2727
+ /**
2728
+ * Register a handler for server→client ask-user requests.
2729
+ *
2730
+ * The handler receives the request params and should return a result
2731
+ * object with `cancelled` and `answers` keys. Async handlers are awaited.
2732
+ * Replaces any previously registered handler.
2733
+ */
2734
+ setAskUserHandler(handler) {
2735
+ this._askUserHandler = handler;
2736
+ }
2737
+ /**
2738
+ * Remove the ask-user request handler.
2739
+ * Restores default behavior: return `{ cancelled: true, answers: [] }`.
2740
+ */
2741
+ clearAskUserHandler() {
2742
+ this._askUserHandler = null;
2743
+ }
2744
+ // ------------------------------------------------------------------
2745
+ // Lifecycle
2746
+ // ------------------------------------------------------------------
2747
+ /**
2748
+ * Close the client and release all resources.
2749
+ *
2750
+ * Rejects pending requests, clears handlers and listeners, and closes
2751
+ * the protocol engine. Idempotent — safe to call multiple times.
2752
+ *
2753
+ * After close, all method calls throw ConnectionError immediately.
2754
+ */
2755
+ async close() {
2756
+ if (this._closed) {
2757
+ return;
2758
+ }
2759
+ this._closed = true;
2760
+ this._notificationListeners.length = 0;
2761
+ this._permissionHandler = null;
2762
+ this._askUserHandler = null;
2763
+ await this._engine.close();
2764
+ }
2765
+ // ------------------------------------------------------------------
2766
+ // Internal: dispatch methods
2767
+ // ------------------------------------------------------------------
2768
+ /**
2769
+ * Dispatch a notification to all registered client-level listeners.
2770
+ * Filters by notification type if a type filter is set.
2771
+ * Exception in one listener does not affect others.
2772
+ */
2773
+ _dispatchNotification(notification) {
2774
+ const params = notification["params"];
2775
+ const innerNotification = params?.["notification"];
2776
+ const notificationType = innerNotification?.["type"];
2777
+ const listeners = [...this._notificationListeners];
2778
+ for (const listener of listeners) {
2779
+ if (listener.typeFilter != null && listener.typeFilter !== notificationType) {
2780
+ continue;
2781
+ }
2782
+ try {
2783
+ listener.callback(notification);
2784
+ } catch {
2785
+ }
2786
+ }
2787
+ }
2788
+ /**
2789
+ * Dispatch to the client-level permission handler.
2790
+ * If no handler is set, returns the default "cancel" outcome.
2791
+ * If handler throws, the error propagates to the protocol engine
2792
+ * which sends an error response.
2793
+ */
2794
+ _dispatchPermissionRequest(params) {
2795
+ const handler = this._permissionHandler;
2796
+ if (handler == null) {
2797
+ return "cancel";
2798
+ }
2799
+ return handler(params);
2800
+ }
2801
+ /**
2802
+ * Dispatch to the client-level ask-user handler.
2803
+ * If no handler is set, returns the default cancelled response.
2804
+ * If handler throws, the error propagates to the protocol engine
2805
+ * which sends an error response.
2806
+ */
2807
+ _dispatchAskUserRequest(params) {
2808
+ const handler = this._askUserHandler;
2809
+ if (handler == null) {
2810
+ return { cancelled: true, answers: [] };
2811
+ }
2812
+ return handler(params);
2813
+ }
2814
+ // ------------------------------------------------------------------
2815
+ // Internal: guards
2816
+ // ------------------------------------------------------------------
2817
+ /**
2818
+ * Throw ConnectionError if the client has been closed.
2819
+ */
2820
+ _ensureNotClosed() {
2821
+ if (this._closed) {
2822
+ throw new ConnectionError(
2823
+ "Client has been closed. Create a new DroidClient instance to reconnect."
2824
+ );
2825
+ }
2826
+ }
2827
+ /**
2828
+ * Throw SessionError if no active session.
2829
+ */
2830
+ _ensureSession() {
2831
+ if (this._sessionId == null) {
2832
+ throw new SessionError(
2833
+ "No active session. Call initializeSession or loadSession first."
2834
+ );
2835
+ }
2836
+ }
2837
+ };
2838
+
2839
+ // src/stream.ts
2840
+ function convertNotificationToStreamMessage(notification) {
2841
+ switch (notification.type) {
2842
+ case "assistant_text_delta" /* ASSISTANT_TEXT_DELTA */:
2843
+ return {
2844
+ type: "assistant_text_delta",
2845
+ messageId: notification.messageId,
2846
+ blockIndex: notification.blockIndex,
2847
+ text: notification.textDelta
2848
+ };
2849
+ case "thinking_text_delta" /* THINKING_TEXT_DELTA */:
2850
+ return {
2851
+ type: "thinking_text_delta",
2852
+ messageId: notification.messageId,
2853
+ blockIndex: notification.blockIndex,
2854
+ text: notification.textDelta
2855
+ };
2856
+ case "tool_result" /* TOOL_RESULT */:
2857
+ return {
2858
+ type: "tool_result",
2859
+ toolUseId: notification.toolUseId,
2860
+ content: normalizeToolResultContent(notification.content),
2861
+ isError: Boolean(notification.isError)
2862
+ };
2863
+ case "tool_progress_update" /* TOOL_PROGRESS_UPDATE */: {
2864
+ const update = notification.update;
2865
+ const text = update?.text ?? update?.status ?? update?.details ?? "";
2866
+ return {
2867
+ type: "tool_progress",
2868
+ toolUseId: notification.toolUseId,
2869
+ toolName: notification.toolName,
2870
+ content: text,
2871
+ update
2872
+ };
2873
+ }
2874
+ case "droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */:
2875
+ return {
2876
+ type: "working_state_changed",
2877
+ state: notification.newState
2878
+ };
2879
+ case "session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */: {
2880
+ const tu = notification.tokenUsage;
2881
+ return {
2882
+ type: "token_usage_update",
2883
+ inputTokens: tu.inputTokens,
2884
+ outputTokens: tu.outputTokens,
2885
+ cacheReadTokens: tu.cacheReadTokens,
2886
+ cacheWriteTokens: tu.cacheCreationTokens,
2887
+ thinkingTokens: tu.thinkingTokens
2888
+ };
2889
+ }
2890
+ case "create_message" /* CREATE_MESSAGE */: {
2891
+ const msg = notification.message;
2892
+ const messages = [];
2893
+ if (msg.content && Array.isArray(msg.content)) {
2894
+ for (const block of msg.content) {
2895
+ if (block.type === "tool_use") {
2896
+ messages.push({
2897
+ type: "tool_use",
2898
+ toolName: block.name,
2899
+ toolInput: block.input ?? {},
2900
+ toolUseId: block.id
2901
+ });
2902
+ }
2903
+ }
2904
+ }
2905
+ messages.push({
2906
+ type: "create_message",
2907
+ messageId: msg.id,
2908
+ role: msg.role,
2909
+ content: msg.content ?? [],
2910
+ parentId: notification.parentId
2911
+ });
2912
+ return messages;
2913
+ }
2914
+ case "error" /* ERROR */:
2915
+ return {
2916
+ type: "error",
2917
+ message: notification.message,
2918
+ errorType: notification.errorType,
2919
+ timestamp: notification.timestamp
2920
+ };
2921
+ case "permission_resolved" /* PERMISSION_RESOLVED */:
2922
+ return {
2923
+ type: "permission_resolved",
2924
+ requestId: notification.requestId,
2925
+ toolUseIds: notification.toolUseIds,
2926
+ selectedOption: notification.selectedOption
2927
+ };
2928
+ case "settings_updated" /* SETTINGS_UPDATED */:
2929
+ return {
2930
+ type: "settings_updated",
2931
+ settings: notification.settings
2932
+ };
2933
+ case "session_title_updated" /* SESSION_TITLE_UPDATED */:
2934
+ return {
2935
+ type: "session_title_updated",
2936
+ title: notification.title
2937
+ };
2938
+ case "mcp_status_changed" /* MCP_STATUS_CHANGED */:
2939
+ return {
2940
+ type: "mcp_status_changed",
2941
+ servers: notification.servers,
2942
+ summary: notification.summary
2943
+ };
2944
+ case "mission_state_changed" /* MISSION_STATE_CHANGED */:
2945
+ return {
2946
+ type: "mission_state_changed",
2947
+ state: notification.state
2948
+ };
2949
+ case "mission_features_changed" /* MISSION_FEATURES_CHANGED */:
2950
+ return {
2951
+ type: "mission_features_changed",
2952
+ features: notification.features
2953
+ };
2954
+ case "mission_progress_entry" /* MISSION_PROGRESS_ENTRY */:
2955
+ return {
2956
+ type: "mission_progress_entry",
2957
+ progressLog: notification.progressLog
2958
+ };
2959
+ case "mission_heartbeat" /* MISSION_HEARTBEAT */:
2960
+ return {
2961
+ type: "mission_heartbeat",
2962
+ timestamp: notification.timestamp
2963
+ };
2964
+ case "mission_worker_started" /* MISSION_WORKER_STARTED */:
2965
+ return {
2966
+ type: "mission_worker_started",
2967
+ workerSessionId: notification.workerSessionId
2968
+ };
2969
+ case "mission_worker_completed" /* MISSION_WORKER_COMPLETED */:
2970
+ return {
2971
+ type: "mission_worker_completed",
2972
+ workerSessionId: notification.workerSessionId,
2973
+ exitCode: notification.exitCode
2974
+ };
2975
+ case "mcp_auth_required" /* MCP_AUTH_REQUIRED */:
2976
+ return {
2977
+ type: "mcp_auth_required",
2978
+ serverName: notification.serverName,
2979
+ authUrl: notification.authUrl,
2980
+ message: notification.message,
2981
+ state: notification.state
2982
+ };
2983
+ case "mcp_auth_completed" /* MCP_AUTH_COMPLETED */:
2984
+ return {
2985
+ type: "mcp_auth_completed",
2986
+ serverName: notification.serverName,
2987
+ outcome: notification.outcome,
2988
+ message: notification.message
2989
+ };
2990
+ default:
2991
+ console.warn(
2992
+ `[droid-sdk] Unknown notification type: ${String(notification.type)}`
2993
+ );
2994
+ return null;
2995
+ }
2996
+ }
2997
+ var StreamStateTracker = class {
2998
+ /** Whether we have ever seen a non-idle state. */
2999
+ hasBeenNonIdle = false;
3000
+ /** Last-seen token usage update (to attach to TurnComplete). */
3001
+ lastTokenUsage = null;
3002
+ /**
3003
+ * Process a DroidMessage and return any additional messages that should be
3004
+ * emitted (e.g. TurnComplete sentinel).
3005
+ *
3006
+ * @param message - The DroidMessage to process.
3007
+ * @returns An array of additional messages to emit (may be empty).
3008
+ */
3009
+ processMessage(message) {
3010
+ const additional = [];
3011
+ if (message.type === "token_usage_update") {
3012
+ this.lastTokenUsage = message;
3013
+ }
3014
+ if (message.type === "working_state_changed") {
3015
+ if (message.state !== "idle" /* Idle */) {
3016
+ this.hasBeenNonIdle = true;
3017
+ } else if (this.hasBeenNonIdle) {
3018
+ additional.push({
3019
+ type: "turn_complete",
3020
+ tokenUsage: this.lastTokenUsage
3021
+ });
3022
+ this.hasBeenNonIdle = false;
3023
+ }
3024
+ }
3025
+ return additional;
3026
+ }
3027
+ /**
3028
+ * Reset the tracker for a new turn/stream call.
3029
+ */
3030
+ reset() {
3031
+ this.hasBeenNonIdle = false;
3032
+ this.lastTokenUsage = null;
3033
+ }
3034
+ };
3035
+ function normalizeToolResultContent(content) {
3036
+ if (content == null) {
3037
+ return "";
3038
+ }
3039
+ if (typeof content === "string") {
3040
+ return content;
3041
+ }
3042
+ if (Array.isArray(content)) {
3043
+ return content;
3044
+ }
3045
+ return String(content);
3046
+ }
3047
+
3048
+ // src/query.ts
3049
+ function query(options) {
3050
+ let transport = null;
3051
+ let client = null;
3052
+ let sessionId = null;
3053
+ let aborted = false;
3054
+ const messageQueue = [];
3055
+ let resolveWaiting = null;
3056
+ let streamDone = false;
3057
+ function enqueueMessage(msg) {
3058
+ messageQueue.push(msg);
3059
+ if (resolveWaiting) {
3060
+ const resolve = resolveWaiting;
3061
+ resolveWaiting = null;
3062
+ resolve();
3063
+ }
3064
+ }
3065
+ function signalDone() {
3066
+ streamDone = true;
3067
+ if (resolveWaiting) {
3068
+ const resolve = resolveWaiting;
3069
+ resolveWaiting = null;
3070
+ resolve();
3071
+ }
3072
+ }
3073
+ async function* generateMessages() {
3074
+ if (options.transport) {
3075
+ transport = options.transport;
3076
+ } else {
3077
+ const transportOptions = {
3078
+ execPath: options.execPath,
3079
+ execArgs: options.execArgs,
3080
+ cwd: options.cwd,
3081
+ env: options.env
3082
+ };
3083
+ const processTransport = new ProcessTransport(transportOptions);
3084
+ await processTransport.connect();
3085
+ transport = processTransport;
3086
+ }
3087
+ client = new DroidClient({ transport });
3088
+ if (options.permissionHandler) {
3089
+ client.setPermissionHandler(options.permissionHandler);
3090
+ }
3091
+ if (options.askUserHandler) {
3092
+ client.setAskUserHandler(options.askUserHandler);
3093
+ }
3094
+ const stateTracker = new StreamStateTracker();
3095
+ client.onNotification((notification) => {
3096
+ const params = notification["params"];
3097
+ const innerNotification = params?.["notification"];
3098
+ if (!innerNotification) {
3099
+ return;
3100
+ }
3101
+ const converted = convertNotificationToStreamMessage(
3102
+ innerNotification
3103
+ );
3104
+ if (converted === null) {
3105
+ return;
3106
+ }
3107
+ const messages = Array.isArray(converted) ? converted : [converted];
3108
+ for (const msg of messages) {
3109
+ enqueueMessage(msg);
3110
+ const additional = stateTracker.processMessage(msg);
3111
+ for (const extra of additional) {
3112
+ enqueueMessage(extra);
3113
+ if (extra.type === "turn_complete") {
3114
+ signalDone();
3115
+ }
3116
+ }
3117
+ }
3118
+ });
3119
+ const initParams = {
3120
+ machineId: options.machineId ?? "default",
3121
+ cwd: options.cwd ?? "."
3122
+ };
3123
+ if (options.modelId !== void 0) {
3124
+ initParams.modelId = options.modelId;
3125
+ }
3126
+ if (options.autonomyLevel !== void 0) {
3127
+ initParams.autonomyLevel = options.autonomyLevel;
3128
+ }
3129
+ if (options.interactionMode !== void 0) {
3130
+ initParams.interactionMode = options.interactionMode;
3131
+ }
3132
+ if (options.reasoningEffort !== void 0) {
3133
+ initParams.reasoningEffort = options.reasoningEffort;
3134
+ }
3135
+ if (options.mcpServers !== void 0) {
3136
+ initParams.mcpServers = options.mcpServers;
3137
+ }
3138
+ if (options.enabledToolIds !== void 0) {
3139
+ initParams.enabledToolIds = options.enabledToolIds;
3140
+ }
3141
+ const initResult = await client.initializeSession(
3142
+ initParams
3143
+ );
3144
+ sessionId = initResult.sessionId;
3145
+ await client.addUserMessage({ text: options.prompt });
3146
+ try {
3147
+ while (true) {
3148
+ if (aborted) {
3149
+ return;
3150
+ }
3151
+ while (messageQueue.length > 0) {
3152
+ const msg = messageQueue.shift();
3153
+ yield msg;
3154
+ if (msg.type === "turn_complete") {
3155
+ return;
3156
+ }
3157
+ }
3158
+ if (streamDone && messageQueue.length === 0) {
3159
+ return;
3160
+ }
3161
+ await new Promise((resolve) => {
3162
+ resolveWaiting = resolve;
3163
+ });
3164
+ }
3165
+ } finally {
3166
+ }
3167
+ }
3168
+ const generator = generateMessages();
3169
+ async function* wrappedGenerator() {
3170
+ try {
3171
+ yield* generator;
3172
+ } finally {
3173
+ if (client) {
3174
+ try {
3175
+ await client.close();
3176
+ } catch {
3177
+ }
3178
+ client = null;
3179
+ } else if (transport) {
3180
+ try {
3181
+ await transport.close();
3182
+ } catch {
3183
+ }
3184
+ }
3185
+ transport = null;
3186
+ }
3187
+ }
3188
+ const wrapped = wrappedGenerator();
3189
+ const droidQuery = wrapped;
3190
+ Object.defineProperties(droidQuery, {
3191
+ interrupt: {
3192
+ value: async function interrupt() {
3193
+ if (client && !aborted) {
3194
+ await client.interruptSession();
3195
+ }
3196
+ },
3197
+ writable: false,
3198
+ enumerable: true
3199
+ },
3200
+ abort: {
3201
+ value: function abort() {
3202
+ aborted = true;
3203
+ signalDone();
3204
+ if (client) {
3205
+ void client.close().catch(() => {
3206
+ });
3207
+ client = null;
3208
+ } else if (transport) {
3209
+ void transport.close().catch(() => {
3210
+ });
3211
+ }
3212
+ transport = null;
3213
+ },
3214
+ writable: false,
3215
+ enumerable: true
3216
+ },
3217
+ sessionId: {
3218
+ get() {
3219
+ return sessionId;
3220
+ },
3221
+ enumerable: true
3222
+ }
3223
+ });
3224
+ return droidQuery;
3225
+ }
3226
+
3227
+ // src/session.ts
3228
+ var DroidSession = class {
3229
+ _client;
3230
+ _sessionId;
3231
+ _initResult;
3232
+ _closed = false;
3233
+ /** @internal */
3234
+ constructor(client, sessionId, initResult) {
3235
+ this._client = client;
3236
+ this._sessionId = sessionId;
3237
+ this._initResult = initResult;
3238
+ }
3239
+ // ------------------------------------------------------------------
3240
+ // Properties
3241
+ // ------------------------------------------------------------------
3242
+ /** The session ID. */
3243
+ get sessionId() {
3244
+ return this._sessionId;
3245
+ }
3246
+ /** The result from session initialization or loading. */
3247
+ get initResult() {
3248
+ return this._initResult;
3249
+ }
3250
+ // ------------------------------------------------------------------
3251
+ // Messaging
3252
+ // ------------------------------------------------------------------
3253
+ /**
3254
+ * Send a message and return a streaming async generator of DroidMessage events.
3255
+ *
3256
+ * The generator yields messages until a TurnComplete event is received,
3257
+ * signaling the end of the agent's turn.
3258
+ *
3259
+ * @param text - The user message text.
3260
+ * @param options - Optional images/files to include.
3261
+ * @returns An async generator yielding DroidMessage events.
3262
+ */
3263
+ async *stream(text, options) {
3264
+ this._ensureNotClosed();
3265
+ const messageQueue = [];
3266
+ let resolveWaiting = null;
3267
+ let streamDone = false;
3268
+ function enqueueMessage(msg) {
3269
+ messageQueue.push(msg);
3270
+ if (resolveWaiting) {
3271
+ const resolve = resolveWaiting;
3272
+ resolveWaiting = null;
3273
+ resolve();
3274
+ }
3275
+ }
3276
+ function signalDone() {
3277
+ streamDone = true;
3278
+ if (resolveWaiting) {
3279
+ const resolve = resolveWaiting;
3280
+ resolveWaiting = null;
3281
+ resolve();
3282
+ }
3283
+ }
3284
+ const stateTracker = new StreamStateTracker();
3285
+ const unsubscribe = this._client.onNotification((notification) => {
3286
+ const params = notification["params"];
3287
+ const innerNotification = params?.["notification"];
3288
+ if (!innerNotification) {
3289
+ return;
3290
+ }
3291
+ const converted = convertNotificationToStreamMessage(
3292
+ innerNotification
3293
+ );
3294
+ if (converted === null) {
3295
+ return;
3296
+ }
3297
+ const messages = Array.isArray(converted) ? converted : [converted];
3298
+ for (const msg of messages) {
3299
+ enqueueMessage(msg);
3300
+ const additional = stateTracker.processMessage(msg);
3301
+ for (const extra of additional) {
3302
+ enqueueMessage(extra);
3303
+ if (extra.type === "turn_complete") {
3304
+ signalDone();
3305
+ }
3306
+ }
3307
+ }
3308
+ });
3309
+ try {
3310
+ await this._client.addUserMessage({
3311
+ text,
3312
+ images: options?.images,
3313
+ files: options?.files
3314
+ });
3315
+ while (true) {
3316
+ while (messageQueue.length > 0) {
3317
+ const msg = messageQueue.shift();
3318
+ yield msg;
3319
+ if (msg.type === "turn_complete") {
3320
+ return;
3321
+ }
3322
+ }
3323
+ if (streamDone && messageQueue.length === 0) {
3324
+ return;
3325
+ }
3326
+ await new Promise((resolve) => {
3327
+ resolveWaiting = resolve;
3328
+ });
3329
+ }
3330
+ } finally {
3331
+ unsubscribe();
3332
+ }
3333
+ }
3334
+ /**
3335
+ * Send a message and collect the complete response (non-streaming).
3336
+ *
3337
+ * Internally consumes all stream messages and returns an aggregated
3338
+ * {@link DroidResult} with the concatenated text, all messages, and
3339
+ * final token usage.
3340
+ *
3341
+ * @param text - The user message text.
3342
+ * @param options - Optional images/files to include.
3343
+ * @returns Aggregated result with text, messages, and token usage.
3344
+ */
3345
+ async send(text, options) {
3346
+ this._ensureNotClosed();
3347
+ const messages = [];
3348
+ let fullText = "";
3349
+ let lastTokenUsage = null;
3350
+ for await (const msg of this.stream(text, options)) {
3351
+ messages.push(msg);
3352
+ if (msg.type === "assistant_text_delta") {
3353
+ fullText += msg.text;
3354
+ }
3355
+ if (msg.type === "token_usage_update") {
3356
+ lastTokenUsage = msg;
3357
+ }
3358
+ if (msg.type === "turn_complete" && msg.tokenUsage) {
3359
+ lastTokenUsage = msg.tokenUsage;
3360
+ }
3361
+ }
3362
+ return {
3363
+ text: fullText,
3364
+ messages,
3365
+ tokenUsage: lastTokenUsage
3366
+ };
3367
+ }
3368
+ // ------------------------------------------------------------------
3369
+ // Session control
3370
+ // ------------------------------------------------------------------
3371
+ /**
3372
+ * Interrupt the current agent turn.
3373
+ *
3374
+ * Sends an interrupt request. The agent will stop after completing
3375
+ * its current operation.
3376
+ */
3377
+ async interrupt() {
3378
+ this._ensureNotClosed();
3379
+ await this._client.interruptSession();
3380
+ }
3381
+ /**
3382
+ * Close the session and release all resources.
3383
+ *
3384
+ * Closes the underlying transport and rejects any pending requests.
3385
+ * After close, the session cannot be used.
3386
+ */
3387
+ async close() {
3388
+ if (this._closed) {
3389
+ return;
3390
+ }
3391
+ this._closed = true;
3392
+ await this._client.close();
3393
+ }
3394
+ // ------------------------------------------------------------------
3395
+ // Settings
3396
+ // ------------------------------------------------------------------
3397
+ /**
3398
+ * Update session settings (model, reasoning effort, autonomy, etc.).
3399
+ *
3400
+ * @param params - Partial settings to update.
3401
+ */
3402
+ async updateSettings(params) {
3403
+ this._ensureNotClosed();
3404
+ return this._client.updateSessionSettings(params);
3405
+ }
3406
+ // ------------------------------------------------------------------
3407
+ // MCP methods
3408
+ // ------------------------------------------------------------------
3409
+ /**
3410
+ * Add an MCP server to the session.
3411
+ */
3412
+ async addMcpServer(params) {
3413
+ this._ensureNotClosed();
3414
+ return this._client.addMcpServer(params);
3415
+ }
3416
+ /**
3417
+ * Remove an MCP server from the session.
3418
+ */
3419
+ async removeMcpServer(params) {
3420
+ this._ensureNotClosed();
3421
+ return this._client.removeMcpServer(params);
3422
+ }
3423
+ /**
3424
+ * Toggle an MCP server on or off.
3425
+ */
3426
+ async toggleMcpServer(params) {
3427
+ this._ensureNotClosed();
3428
+ return this._client.toggleMcpServer(params);
3429
+ }
3430
+ /**
3431
+ * List MCP servers and their status.
3432
+ */
3433
+ async listMcpServers() {
3434
+ this._ensureNotClosed();
3435
+ return this._client.listMcpServers();
3436
+ }
3437
+ /**
3438
+ * List available MCP tools.
3439
+ */
3440
+ async listMcpTools() {
3441
+ this._ensureNotClosed();
3442
+ return this._client.listMcpTools();
3443
+ }
3444
+ /**
3445
+ * Authenticate an MCP server (OAuth flow).
3446
+ */
3447
+ async authenticateMcpServer(params) {
3448
+ this._ensureNotClosed();
3449
+ return this._client.authenticateMcpServer(params);
3450
+ }
3451
+ // ------------------------------------------------------------------
3452
+ // Skills
3453
+ // ------------------------------------------------------------------
3454
+ /**
3455
+ * List available skills.
3456
+ */
3457
+ async listSkills() {
3458
+ this._ensureNotClosed();
3459
+ return this._client.listSkills();
3460
+ }
3461
+ // ------------------------------------------------------------------
3462
+ // Notification subscription
3463
+ // ------------------------------------------------------------------
3464
+ /**
3465
+ * Register a callback for incoming notification messages.
3466
+ *
3467
+ * @param callback - Invoked with the notification object.
3468
+ * @param filter - Optional filter to only receive specific notification types.
3469
+ * @returns An unsubscribe function.
3470
+ */
3471
+ onNotification(callback, filter) {
3472
+ return this._client.onNotification(callback, filter);
3473
+ }
3474
+ // ------------------------------------------------------------------
3475
+ // Internal
3476
+ // ------------------------------------------------------------------
3477
+ _ensureNotClosed() {
3478
+ if (this._closed) {
3479
+ throw new ConnectionError(
3480
+ "Session has been closed. Create a new session to continue."
3481
+ );
3482
+ }
3483
+ }
3484
+ };
3485
+ async function createSession(options = {}) {
3486
+ let transport;
3487
+ if (options.transport) {
3488
+ transport = options.transport;
3489
+ } else {
3490
+ const transportOptions = {
3491
+ execPath: options.execPath,
3492
+ execArgs: options.execArgs,
3493
+ cwd: options.cwd,
3494
+ env: options.env
3495
+ };
3496
+ const processTransport = new ProcessTransport(transportOptions);
3497
+ await processTransport.connect();
3498
+ transport = processTransport;
3499
+ }
3500
+ const client = new DroidClient({ transport });
3501
+ if (options.permissionHandler) {
3502
+ client.setPermissionHandler(options.permissionHandler);
3503
+ }
3504
+ if (options.askUserHandler) {
3505
+ client.setAskUserHandler(options.askUserHandler);
3506
+ }
3507
+ const initParams = {
3508
+ machineId: options.machineId ?? "default",
3509
+ cwd: options.cwd ?? "."
3510
+ };
3511
+ if (options.modelId !== void 0) {
3512
+ initParams.modelId = options.modelId;
3513
+ }
3514
+ if (options.autonomyLevel !== void 0) {
3515
+ initParams.autonomyLevel = options.autonomyLevel;
3516
+ }
3517
+ if (options.interactionMode !== void 0) {
3518
+ initParams.interactionMode = options.interactionMode;
3519
+ }
3520
+ if (options.reasoningEffort !== void 0) {
3521
+ initParams.reasoningEffort = options.reasoningEffort;
3522
+ }
3523
+ if (options.mcpServers !== void 0) {
3524
+ initParams.mcpServers = options.mcpServers;
3525
+ }
3526
+ if (options.enabledToolIds !== void 0) {
3527
+ initParams.enabledToolIds = options.enabledToolIds;
3528
+ }
3529
+ try {
3530
+ const initResult = await client.initializeSession(
3531
+ initParams
3532
+ );
3533
+ return new DroidSession(client, initResult.sessionId, initResult);
3534
+ } catch (error) {
3535
+ try {
3536
+ await client.close();
3537
+ } catch {
3538
+ }
3539
+ throw error;
3540
+ }
3541
+ }
3542
+ async function resumeSession(sessionId, options = {}) {
3543
+ let transport;
3544
+ if (options.transport) {
3545
+ transport = options.transport;
3546
+ } else {
3547
+ const transportOptions = {
3548
+ execPath: options.execPath,
3549
+ execArgs: options.execArgs,
3550
+ cwd: options.cwd,
3551
+ env: options.env
3552
+ };
3553
+ const processTransport = new ProcessTransport(transportOptions);
3554
+ await processTransport.connect();
3555
+ transport = processTransport;
3556
+ }
3557
+ const client = new DroidClient({ transport });
3558
+ if (options.permissionHandler) {
3559
+ client.setPermissionHandler(options.permissionHandler);
3560
+ }
3561
+ if (options.askUserHandler) {
3562
+ client.setAskUserHandler(options.askUserHandler);
3563
+ }
3564
+ const loadParams = {
3565
+ sessionId,
3566
+ mcpServers: options.mcpServers
3567
+ };
3568
+ try {
3569
+ const loadResult = await client.loadSession(loadParams);
3570
+ return new DroidSession(client, sessionId, loadResult);
3571
+ } catch (error) {
3572
+ try {
3573
+ await client.close();
3574
+ } catch {
3575
+ }
3576
+ throw error;
3577
+ }
3578
+ }
3579
+ // Annotate the CommonJS export names for ESM import in node:
3580
+ 0 && (module.exports = {
3581
+ AddMcpServerRequestParamsSchema,
3582
+ AddMcpServerRequestSchema,
3583
+ AddMcpServerResponseSchema,
3584
+ AddMcpServerResultSchema,
3585
+ AddUserMessageRequestParamsSchema,
3586
+ AddUserMessageRequestSchema,
3587
+ AddUserMessageResponseSchema,
3588
+ AddUserMessageResultSchema,
3589
+ ApplyPatchToolConfirmationDetailsSchema,
3590
+ AskUserCollectedAnswerSchema,
3591
+ AskUserConfirmationDetailsSchema,
3592
+ AskUserQuestionSchema,
3593
+ AskUserRequestParamsSchema,
3594
+ AskUserRequestSchema,
3595
+ AskUserResponseSchema,
3596
+ AskUserResultSchema,
3597
+ AssistantTextDeltaNotificationSchema,
3598
+ AuthenticateMcpServerRequestParamsSchema,
3599
+ AuthenticateMcpServerRequestSchema,
3600
+ AuthenticateMcpServerResponseSchema,
3601
+ AuthenticateMcpServerResultSchema,
3602
+ AutonomyLevel,
3603
+ AutonomyMode,
3604
+ AvailableModelConfigSchema,
3605
+ Base64ImageSourceSchema,
3606
+ BaseNotificationSchema,
3607
+ BaseRequestSchema,
3608
+ BaseResponseFailureSchema,
3609
+ BaseResponseSuccessSchema,
3610
+ CancelMcpAuthRequestParamsSchema,
3611
+ CancelMcpAuthRequestSchema,
3612
+ CancelMcpAuthResponseSchema,
3613
+ CancelMcpAuthResultSchema,
3614
+ ClearMcpAuthRequestParamsSchema,
3615
+ ClearMcpAuthRequestSchema,
3616
+ ClearMcpAuthResponseSchema,
3617
+ ClearMcpAuthResultSchema,
3618
+ CliRequestOrNotificationSchema,
3619
+ ClientRequestSchema,
3620
+ ConnectionError,
3621
+ ContentBlockSchema,
3622
+ CreateMessageNotificationSchema,
3623
+ CreateToolConfirmationDetailsSchema,
3624
+ DEFAULT_REQUEST_TIMEOUT,
3625
+ DecompSessionType,
3626
+ DiscoveredIssueSchema,
3627
+ DismissalRecordSchema,
3628
+ DismissalType,
3629
+ DocumentBlockSchema,
3630
+ DocumentSourceSchema,
3631
+ DroidClient,
3632
+ DroidClientMethod,
3633
+ DroidErrorType,
3634
+ DroidInteractionMode,
3635
+ DroidServerMethod,
3636
+ DroidSession,
3637
+ DroidWorkingState,
3638
+ DroidWorkingStateChangedNotificationSchema,
3639
+ EditToolConfirmationDetailsSchema,
3640
+ ErrorDetailSchema,
3641
+ ErrorNotificationSchema,
3642
+ ExecuteToolConfirmationDetailsSchema,
3643
+ ExitSpecModeConfirmationDetailsSchema,
3644
+ FACTORY_CLIENT_HEADER,
3645
+ FACTORY_CLIENT_VERSION,
3646
+ FACTORY_PROTOCOL_VERSION,
3647
+ FactoryDroidMessageSchema,
3648
+ FeatureStatus,
3649
+ FeatureSuccessState,
3650
+ FeatureSuccessStateSchema,
3651
+ GitRepoInfoSchema,
3652
+ HandoffItemsDismissedEntrySchema,
3653
+ HandoffSchema,
3654
+ HttpHeaderSchema,
3655
+ HttpMcpConfigSchema,
3656
+ ImageBlockSchema,
3657
+ InitializeSessionRequestParamsSchema,
3658
+ InitializeSessionRequestSchema,
3659
+ InitializeSessionResponseSchema,
3660
+ InitializeSessionResultSchema,
3661
+ InteractiveCheckSchema,
3662
+ InterruptSessionRequestParamsSchema,
3663
+ InterruptSessionRequestSchema,
3664
+ InterruptSessionResponseSchema,
3665
+ InterruptSessionResultSchema,
3666
+ IssueSeverity,
3667
+ JSONRPC_VERSION,
3668
+ JsonRpcEnvelopeSchema,
3669
+ JsonRpcErrorCode,
3670
+ JsonRpcErrorSchema,
3671
+ JsonRpcMessageSchema,
3672
+ JsonRpcMessageType,
3673
+ JsonRpcNotificationSchema,
3674
+ JsonRpcRequestSchema,
3675
+ JsonRpcResponseFailureSchema,
3676
+ JsonRpcResponseSchema,
3677
+ JsonRpcResponseSuccessSchema,
3678
+ KillWorkerSessionRequestParamsSchema,
3679
+ KillWorkerSessionRequestSchema,
3680
+ KillWorkerSessionResponseSchema,
3681
+ KillWorkerSessionResultSchema,
3682
+ LEGACY_FACTORY_API_VERSION,
3683
+ ListMcpRegistryRequestParamsSchema,
3684
+ ListMcpRegistryRequestSchema,
3685
+ ListMcpRegistryResponseSchema,
3686
+ ListMcpRegistryResultSchema,
3687
+ ListMcpServersRequestParamsSchema,
3688
+ ListMcpServersRequestSchema,
3689
+ ListMcpServersResponseSchema,
3690
+ ListMcpServersResultSchema,
3691
+ ListMcpToolsRequestParamsSchema,
3692
+ ListMcpToolsRequestSchema,
3693
+ ListMcpToolsResponseSchema,
3694
+ ListMcpToolsResultSchema,
3695
+ ListSkillsRequestParamsSchema,
3696
+ ListSkillsRequestSchema,
3697
+ ListSkillsResponseSchema,
3698
+ ListSkillsResultSchema,
3699
+ LoadSessionRequestParamsSchema,
3700
+ LoadSessionRequestSchema,
3701
+ LoadSessionResponseSchema,
3702
+ LoadSessionResultSchema,
3703
+ MCP_AUTH_TIMEOUT,
3704
+ McpAuthCompletedNotificationSchema,
3705
+ McpAuthOutcome,
3706
+ McpAuthRequiredNotificationSchema,
3707
+ McpHttpServerConfigFieldsSchema,
3708
+ McpRegistryServerSchema,
3709
+ McpServerConfigSchema,
3710
+ McpServerStatus,
3711
+ McpServerStatusInfoSchema,
3712
+ McpServerType,
3713
+ McpSseServerConfigFieldsSchema,
3714
+ McpStatus,
3715
+ McpStatusChangedNotificationSchema,
3716
+ McpStatusSummarySchema,
3717
+ McpStdioServerConfigFieldsSchema,
3718
+ McpToolConfirmationDetailsSchema,
3719
+ McpToolInfoSchema,
3720
+ McpToolInputSchemaSchema,
3721
+ MilestoneValidationTriggeredEntrySchema,
3722
+ MissionAcceptedEntrySchema,
3723
+ MissionFeatureSchema,
3724
+ MissionFeaturesChangedNotificationSchema,
3725
+ MissionHeartbeatNotificationSchema,
3726
+ MissionPausedEntrySchema,
3727
+ MissionProgressEntryNotificationSchema,
3728
+ MissionResumedEntrySchema,
3729
+ MissionRunStartedEntrySchema,
3730
+ MissionSnapshotSchema,
3731
+ MissionState,
3732
+ MissionStateChangedNotificationSchema,
3733
+ MissionWorkerCompletedNotificationSchema,
3734
+ MissionWorkerStartedNotificationSchema,
3735
+ ModelProvider,
3736
+ PermissionResolvedNotificationSchema,
3737
+ ProcessExitError,
3738
+ ProcessTransport,
3739
+ ProgressLogEntrySchema,
3740
+ ProgressLogEntryType,
3741
+ ProposeMissionConfirmationDetailsSchema,
3742
+ ProtocolEngine,
3743
+ ProtocolError,
3744
+ ReasoningEffort,
3745
+ RedactedThinkingBlockSchema,
3746
+ RemoveMcpServerRequestParamsSchema,
3747
+ RemoveMcpServerRequestSchema,
3748
+ RemoveMcpServerResponseSchema,
3749
+ RemoveMcpServerResultSchema,
3750
+ RequestPermissionRequestParamsSchema,
3751
+ RequestPermissionRequestSchema,
3752
+ RequestPermissionResponseSchema,
3753
+ RequestPermissionResultSchema,
3754
+ SESSION_INIT_TIMEOUT,
3755
+ SessionError,
3756
+ SessionNotFoundError,
3757
+ SessionNotificationParamsSchema,
3758
+ SessionNotificationPayloadSchema,
3759
+ SessionNotificationSchema,
3760
+ SessionNotificationSchemaList,
3761
+ SessionNotificationType,
3762
+ SessionSettingsSchema,
3763
+ SessionSourceSchema,
3764
+ SessionTagSchema,
3765
+ SessionTitleUpdatedNotificationSchema,
3766
+ SessionTokenUsageChangedNotificationSchema,
3767
+ SettingsLevel,
3768
+ SettingsUpdatedNotificationSchema,
3769
+ SettingsUpdatedPayloadSchema,
3770
+ SkillDeviationSchema,
3771
+ SkillFeedbackSchema,
3772
+ SkillInfoSchema,
3773
+ SkillLocation,
3774
+ SkillResourceSchema,
3775
+ SseMcpConfigSchema,
3776
+ StartMissionRunConfirmationDetailsSchema,
3777
+ StdioMcpConfigSchema,
3778
+ StreamStateTracker,
3779
+ SubmitBugReportRequestParamsSchema,
3780
+ SubmitBugReportRequestSchema,
3781
+ SubmitBugReportResponseSchema,
3782
+ SubmitBugReportResultSchema,
3783
+ SubmitMcpAuthCodeRequestParamsSchema,
3784
+ SubmitMcpAuthCodeRequestSchema,
3785
+ SubmitMcpAuthCodeResponseSchema,
3786
+ SubmitMcpAuthCodeResultSchema,
3787
+ TestCaseSchema,
3788
+ TestFileSchema,
3789
+ TestsSchema,
3790
+ TextBlockSchema,
3791
+ ThinkingBlockSchema,
3792
+ ThinkingTextDeltaNotificationSchema,
3793
+ TimeoutError,
3794
+ ToggleMcpServerRequestParamsSchema,
3795
+ ToggleMcpServerRequestSchema,
3796
+ ToggleMcpServerResponseSchema,
3797
+ ToggleMcpServerResultSchema,
3798
+ ToggleMcpToolRequestParamsSchema,
3799
+ ToggleMcpToolRequestSchema,
3800
+ ToggleMcpToolResponseSchema,
3801
+ ToggleMcpToolResultSchema,
3802
+ TokenUsageSchema,
3803
+ ToolConfirmationDetailsSchema,
3804
+ ToolConfirmationInfoSchema,
3805
+ ToolConfirmationListItemSchema,
3806
+ ToolConfirmationOutcome,
3807
+ ToolConfirmationType,
3808
+ ToolProgressUpdateNotificationSchema,
3809
+ ToolProgressUpdateSchema,
3810
+ ToolResultBlockSchema,
3811
+ ToolResultNotificationSchema,
3812
+ ToolUseBlockSchema,
3813
+ ToolUseSchema,
3814
+ TraceContextMetaSchema,
3815
+ UpdateSessionSettingsRequestParamsSchema,
3816
+ UpdateSessionSettingsRequestSchema,
3817
+ UpdateSessionSettingsResponseSchema,
3818
+ UpdateSessionSettingsResultSchema,
3819
+ VerificationCommandSchema,
3820
+ VerificationSchema,
3821
+ WorkerCompletedEntrySchema,
3822
+ WorkerFailedEntrySchema,
3823
+ WorkerPausedEntrySchema,
3824
+ WorkerSelectedFeatureEntrySchema,
3825
+ WorkerStartedEntrySchema,
3826
+ WorkerStateInfoSchema,
3827
+ convertNotificationToStreamMessage,
3828
+ createSession,
3829
+ query,
3830
+ resumeSession
3831
+ });
3832
+ //# sourceMappingURL=index.cjs.map