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