@factory/droid-sdk 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +239 -47
  2. package/dist/index.cjs +1869 -1296
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +6734 -4444
  5. package/dist/index.d.ts +6734 -4444
  6. package/dist/index.js +1815 -1298
  7. package/dist/index.js.map +1 -1
  8. package/docs/examples/init-metadata.md +79 -0
  9. package/docs/examples/list-sessions.md +64 -0
  10. package/docs/examples/multi-turn-session.md +77 -0
  11. package/docs/examples/one-shot-query.md +73 -0
  12. package/docs/examples/permission-handler.md +102 -0
  13. package/docs/examples/run.md +52 -0
  14. package/docs/examples/spec-mode.md +101 -0
  15. package/docs/examples/tool-controls.md +90 -0
  16. package/docs/typescript-sdk-reference.md +372 -0
  17. package/examples/.gitkeep +1 -0
  18. package/examples/abort-session-stream.ts +67 -0
  19. package/examples/droid-dev-structured-output.ts +44 -0
  20. package/examples/fork-session.ts +42 -0
  21. package/examples/init-metadata.ts +76 -0
  22. package/examples/interrupt-session.ts +67 -0
  23. package/examples/list-sessions.ts +65 -0
  24. package/examples/multi-turn-session.ts +67 -0
  25. package/examples/permission-handler.ts +98 -0
  26. package/examples/result-metadata.ts +62 -0
  27. package/examples/run.ts +38 -0
  28. package/examples/sdk-mcp-tool.ts +38 -0
  29. package/examples/simple-query.ts +53 -0
  30. package/examples/spec-mode-new-session.ts +121 -0
  31. package/examples/spec-mode-same-session.ts +133 -0
  32. package/examples/structured-output.ts +53 -0
  33. package/examples/test-compact.ts +60 -0
  34. package/examples/test-rewind.ts +155 -0
  35. package/examples/tool-controls.ts +69 -0
  36. package/package.json +26 -4
package/dist/index.cjs CHANGED
@@ -59,6 +59,7 @@ __export(index_exports, {
59
59
  BaseRequestSchema: () => BaseRequestSchema,
60
60
  BaseResponseFailureSchema: () => BaseResponseFailureSchema,
61
61
  BaseResponseSuccessSchema: () => BaseResponseSuccessSchema,
62
+ COMPACTION_TIMEOUT: () => COMPACTION_TIMEOUT,
62
63
  CancelMcpAuthRequestParamsSchema: () => CancelMcpAuthRequestParamsSchema,
63
64
  CancelMcpAuthRequestSchema: () => CancelMcpAuthRequestSchema,
64
65
  CancelMcpAuthResponseSchema: () => CancelMcpAuthResponseSchema,
@@ -69,8 +70,14 @@ __export(index_exports, {
69
70
  ClearMcpAuthResultSchema: () => ClearMcpAuthResultSchema,
70
71
  CliRequestOrNotificationSchema: () => CliRequestOrNotificationSchema,
71
72
  ClientRequestSchema: () => ClientRequestSchema,
73
+ CompactSessionRequestParamsSchema: () => CompactSessionRequestParamsSchema,
74
+ CompactSessionRequestSchema: () => CompactSessionRequestSchema,
75
+ CompactSessionResponseSchema: () => CompactSessionResponseSchema,
76
+ CompactSessionResultSchema: () => CompactSessionResultSchema,
72
77
  ConnectionError: () => ConnectionError,
73
78
  ContentBlockSchema: () => ContentBlockSchema,
79
+ ContextStatsAccuracy: () => ContextStatsAccuracy,
80
+ ContextStatsSchema: () => ContextStatsSchema,
74
81
  CreateMessageNotificationSchema: () => CreateMessageNotificationSchema,
75
82
  CreateToolConfirmationDetailsSchema: () => CreateToolConfirmationDetailsSchema,
76
83
  DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
@@ -84,22 +91,42 @@ __export(index_exports, {
84
91
  DroidClientMethod: () => DroidClientMethod,
85
92
  DroidErrorType: () => DroidErrorType,
86
93
  DroidInteractionMode: () => DroidInteractionMode,
94
+ DroidMessageType: () => DroidMessageType,
87
95
  DroidServerMethod: () => DroidServerMethod,
88
96
  DroidSession: () => DroidSession,
89
97
  DroidWorkingState: () => DroidWorkingState,
90
98
  DroidWorkingStateChangedNotificationSchema: () => DroidWorkingStateChangedNotificationSchema,
91
99
  EditToolConfirmationDetailsSchema: () => EditToolConfirmationDetailsSchema,
100
+ EmptyResultSchema: () => EmptyResultSchema,
92
101
  ErrorDetailSchema: () => ErrorDetailSchema,
93
102
  ErrorNotificationSchema: () => ErrorNotificationSchema,
103
+ ExecToolInfoSchema: () => ExecToolInfoSchema,
104
+ ExecuteRewindRequestParamsSchema: () => ExecuteRewindRequestParamsSchema,
105
+ ExecuteRewindRequestSchema: () => ExecuteRewindRequestSchema,
106
+ ExecuteRewindResponseSchema: () => ExecuteRewindResponseSchema,
107
+ ExecuteRewindResultSchema: () => ExecuteRewindResultSchema,
94
108
  ExecuteToolConfirmationDetailsSchema: () => ExecuteToolConfirmationDetailsSchema,
95
109
  ExitSpecModeConfirmationDetailsSchema: () => ExitSpecModeConfirmationDetailsSchema,
96
110
  FACTORY_CLIENT_HEADER: () => FACTORY_CLIENT_HEADER,
97
111
  FACTORY_CLIENT_VERSION: () => FACTORY_CLIENT_VERSION,
98
112
  FACTORY_PROTOCOL_VERSION: () => FACTORY_PROTOCOL_VERSION,
113
+ FactoryDroidMessageRole: () => FactoryDroidMessageRole,
99
114
  FactoryDroidMessageSchema: () => FactoryDroidMessageSchema,
100
115
  FeatureStatus: () => FeatureStatus,
101
116
  FeatureSuccessState: () => FeatureSuccessState,
102
117
  FeatureSuccessStateSchema: () => FeatureSuccessStateSchema,
118
+ ForkSessionRequestParamsSchema: () => ForkSessionRequestParamsSchema,
119
+ ForkSessionRequestSchema: () => ForkSessionRequestSchema,
120
+ ForkSessionResponseSchema: () => ForkSessionResponseSchema,
121
+ ForkSessionResultSchema: () => ForkSessionResultSchema,
122
+ GetContextStatsRequestParamsSchema: () => GetContextStatsRequestParamsSchema,
123
+ GetContextStatsRequestSchema: () => GetContextStatsRequestSchema,
124
+ GetContextStatsResponseSchema: () => GetContextStatsResponseSchema,
125
+ GetContextStatsResultSchema: () => GetContextStatsResultSchema,
126
+ GetRewindInfoRequestParamsSchema: () => GetRewindInfoRequestParamsSchema,
127
+ GetRewindInfoRequestSchema: () => GetRewindInfoRequestSchema,
128
+ GetRewindInfoResponseSchema: () => GetRewindInfoResponseSchema,
129
+ GetRewindInfoResultSchema: () => GetRewindInfoResultSchema,
103
130
  GitRepoInfoSchema: () => GitRepoInfoSchema,
104
131
  HandoffItemsDismissedEntrySchema: () => HandoffItemsDismissedEntrySchema,
105
132
  HandoffSchema: () => HandoffSchema,
@@ -117,6 +144,8 @@ __export(index_exports, {
117
144
  InterruptSessionResultSchema: () => InterruptSessionResultSchema,
118
145
  IssueSeverity: () => IssueSeverity,
119
146
  JSONRPC_VERSION: () => JSONRPC_VERSION,
147
+ JsonArraySchema: () => JsonArraySchema,
148
+ JsonObjectSchema: () => JsonObjectSchema,
120
149
  JsonRpcEnvelopeSchema: () => JsonRpcEnvelopeSchema,
121
150
  JsonRpcErrorCode: () => JsonRpcErrorCode,
122
151
  JsonRpcErrorSchema: () => JsonRpcErrorSchema,
@@ -127,6 +156,7 @@ __export(index_exports, {
127
156
  JsonRpcResponseFailureSchema: () => JsonRpcResponseFailureSchema,
128
157
  JsonRpcResponseSchema: () => JsonRpcResponseSchema,
129
158
  JsonRpcResponseSuccessSchema: () => JsonRpcResponseSuccessSchema,
159
+ JsonValueSchema: () => JsonValueSchema,
130
160
  KillWorkerSessionRequestParamsSchema: () => KillWorkerSessionRequestParamsSchema,
131
161
  KillWorkerSessionRequestSchema: () => KillWorkerSessionRequestSchema,
132
162
  KillWorkerSessionResponseSchema: () => KillWorkerSessionResponseSchema,
@@ -148,6 +178,10 @@ __export(index_exports, {
148
178
  ListSkillsRequestSchema: () => ListSkillsRequestSchema,
149
179
  ListSkillsResponseSchema: () => ListSkillsResponseSchema,
150
180
  ListSkillsResultSchema: () => ListSkillsResultSchema,
181
+ ListToolsRequestParamsSchema: () => ListToolsRequestParamsSchema,
182
+ ListToolsRequestSchema: () => ListToolsRequestSchema,
183
+ ListToolsResponseSchema: () => ListToolsResponseSchema,
184
+ ListToolsResultSchema: () => ListToolsResultSchema,
151
185
  LoadSessionRequestParamsSchema: () => LoadSessionRequestParamsSchema,
152
186
  LoadSessionRequestSchema: () => LoadSessionRequestSchema,
153
187
  LoadSessionResponseSchema: () => LoadSessionResponseSchema,
@@ -185,6 +219,8 @@ __export(index_exports, {
185
219
  MissionWorkerCompletedNotificationSchema: () => MissionWorkerCompletedNotificationSchema,
186
220
  MissionWorkerStartedNotificationSchema: () => MissionWorkerStartedNotificationSchema,
187
221
  ModelProvider: () => ModelProvider,
222
+ OutputFormatSchema: () => OutputFormatSchema,
223
+ OutputFormatType: () => OutputFormatType,
188
224
  PermissionResolvedNotificationSchema: () => PermissionResolvedNotificationSchema,
189
225
  ProcessExitError: () => ProcessExitError,
190
226
  ProcessTransport: () => ProcessTransport,
@@ -193,26 +229,40 @@ __export(index_exports, {
193
229
  ProposeMissionConfirmationDetailsSchema: () => ProposeMissionConfirmationDetailsSchema,
194
230
  ProtocolEngine: () => ProtocolEngine,
195
231
  ProtocolError: () => ProtocolError,
232
+ REWIND_TIMEOUT: () => REWIND_TIMEOUT,
196
233
  ReasoningEffort: () => ReasoningEffort,
197
234
  RedactedThinkingBlockSchema: () => RedactedThinkingBlockSchema,
198
235
  RemoveMcpServerRequestParamsSchema: () => RemoveMcpServerRequestParamsSchema,
199
236
  RemoveMcpServerRequestSchema: () => RemoveMcpServerRequestSchema,
200
237
  RemoveMcpServerResponseSchema: () => RemoveMcpServerResponseSchema,
201
238
  RemoveMcpServerResultSchema: () => RemoveMcpServerResultSchema,
239
+ RenameSessionRequestParamsSchema: () => RenameSessionRequestParamsSchema,
240
+ RenameSessionRequestSchema: () => RenameSessionRequestSchema,
241
+ RenameSessionResponseSchema: () => RenameSessionResponseSchema,
242
+ RenameSessionResultSchema: () => RenameSessionResultSchema,
202
243
  RequestPermissionRequestParamsSchema: () => RequestPermissionRequestParamsSchema,
203
244
  RequestPermissionRequestSchema: () => RequestPermissionRequestSchema,
204
245
  RequestPermissionResponseSchema: () => RequestPermissionResponseSchema,
205
246
  RequestPermissionResultSchema: () => RequestPermissionResultSchema,
247
+ RewindEvictedFileSchema: () => RewindEvictedFileSchema,
248
+ RewindFileCreationSchema: () => RewindFileCreationSchema,
249
+ RewindFileSnapshotSchema: () => RewindFileSnapshotSchema,
250
+ SDK_TAG: () => SDK_TAG,
251
+ SDK_VERSION: () => SDK_VERSION,
206
252
  SESSION_INIT_TIMEOUT: () => SESSION_INIT_TIMEOUT,
253
+ SdkMcpServer: () => SdkMcpServer,
207
254
  SessionError: () => SessionError,
255
+ SessionMetadataSchema: () => SessionMetadataSchema,
208
256
  SessionNotFoundError: () => SessionNotFoundError,
209
257
  SessionNotificationParamsSchema: () => SessionNotificationParamsSchema,
210
258
  SessionNotificationPayloadSchema: () => SessionNotificationPayloadSchema,
211
259
  SessionNotificationSchema: () => SessionNotificationSchema,
212
260
  SessionNotificationSchemaList: () => SessionNotificationSchemaList,
213
261
  SessionNotificationType: () => SessionNotificationType,
262
+ SessionSettingsFileSchema: () => SessionSettingsFileSchema,
214
263
  SessionSettingsSchema: () => SessionSettingsSchema,
215
264
  SessionSourceSchema: () => SessionSourceSchema,
265
+ SessionStartEventSchema: () => SessionStartEventSchema,
216
266
  SessionTagSchema: () => SessionTagSchema,
217
267
  SessionTitleUpdatedNotificationSchema: () => SessionTitleUpdatedNotificationSchema,
218
268
  SessionTokenUsageChangedNotificationSchema: () => SessionTokenUsageChangedNotificationSchema,
@@ -236,6 +286,7 @@ __export(index_exports, {
236
286
  SubmitMcpAuthCodeRequestSchema: () => SubmitMcpAuthCodeRequestSchema,
237
287
  SubmitMcpAuthCodeResponseSchema: () => SubmitMcpAuthCodeResponseSchema,
238
288
  SubmitMcpAuthCodeResultSchema: () => SubmitMcpAuthCodeResultSchema,
289
+ SuccessResultSchema: () => SuccessResultSchema,
239
290
  TestCaseSchema: () => TestCaseSchema,
240
291
  TestFileSchema: () => TestFileSchema,
241
292
  TestsSchema: () => TestsSchema,
@@ -261,6 +312,7 @@ __export(index_exports, {
261
312
  ToolProgressUpdateSchema: () => ToolProgressUpdateSchema,
262
313
  ToolResultBlockSchema: () => ToolResultBlockSchema,
263
314
  ToolResultNotificationSchema: () => ToolResultNotificationSchema,
315
+ ToolSelectionOverridesSchema: () => ToolSelectionOverridesSchema,
264
316
  ToolUseBlockSchema: () => ToolUseBlockSchema,
265
317
  ToolUseSchema: () => ToolUseSchema,
266
318
  TraceContextMetaSchema: () => TraceContextMetaSchema,
@@ -277,9 +329,13 @@ __export(index_exports, {
277
329
  WorkerStartedEntrySchema: () => WorkerStartedEntrySchema,
278
330
  WorkerStateInfoSchema: () => WorkerStateInfoSchema,
279
331
  convertNotificationToStreamMessage: () => convertNotificationToStreamMessage,
332
+ createSdkMcpServer: () => createSdkMcpServer,
280
333
  createSession: () => createSession,
334
+ listSessions: () => listSessions,
281
335
  query: () => query,
282
- resumeSession: () => resumeSession
336
+ resumeSession: () => resumeSession,
337
+ run: () => run,
338
+ tool: () => tool
283
339
  });
284
340
  module.exports = __toCommonJS(index_exports);
285
341
 
@@ -299,11 +355,18 @@ var DroidServerMethod = /* @__PURE__ */ ((DroidServerMethod2) => {
299
355
  DroidServerMethod2["REMOVE_MCP_SERVER"] = "droid.remove_mcp_server";
300
356
  DroidServerMethod2["LIST_MCP_REGISTRY"] = "droid.list_mcp_registry";
301
357
  DroidServerMethod2["LIST_MCP_TOOLS"] = "droid.list_mcp_tools";
358
+ DroidServerMethod2["LIST_TOOLS"] = "droid.list_tools";
302
359
  DroidServerMethod2["LIST_MCP_SERVERS"] = "droid.list_mcp_servers";
303
360
  DroidServerMethod2["TOGGLE_MCP_TOOL"] = "droid.toggle_mcp_tool";
304
361
  DroidServerMethod2["SUBMIT_MCP_AUTH_CODE"] = "droid.submit_mcp_auth_code";
305
362
  DroidServerMethod2["LIST_SKILLS"] = "droid.list_skills";
306
363
  DroidServerMethod2["SUBMIT_BUG_REPORT"] = "droid.submit_bug_report";
364
+ DroidServerMethod2["GET_REWIND_INFO"] = "droid.get_rewind_info";
365
+ DroidServerMethod2["EXECUTE_REWIND"] = "droid.execute_rewind";
366
+ DroidServerMethod2["COMPACT_SESSION"] = "droid.compact_session";
367
+ DroidServerMethod2["FORK_SESSION"] = "droid.fork_session";
368
+ DroidServerMethod2["RENAME_SESSION"] = "droid.rename_session";
369
+ DroidServerMethod2["GET_CONTEXT_STATS"] = "droid.get_context_stats";
307
370
  return DroidServerMethod2;
308
371
  })(DroidServerMethod || {});
309
372
  var DroidClientMethod = /* @__PURE__ */ ((DroidClientMethod2) => {
@@ -342,6 +405,10 @@ var ToolConfirmationOutcome = /* @__PURE__ */ ((ToolConfirmationOutcome3) => {
342
405
  ToolConfirmationOutcome3["ProceedAutoRunLow"] = "proceed_auto_run_low";
343
406
  ToolConfirmationOutcome3["ProceedAutoRunMedium"] = "proceed_auto_run_medium";
344
407
  ToolConfirmationOutcome3["ProceedAutoRunHigh"] = "proceed_auto_run_high";
408
+ ToolConfirmationOutcome3["ProceedNewSession"] = "proceed_new_session";
409
+ ToolConfirmationOutcome3["ProceedNewSessionLow"] = "proceed_new_session_low";
410
+ ToolConfirmationOutcome3["ProceedNewSessionMedium"] = "proceed_new_session_medium";
411
+ ToolConfirmationOutcome3["ProceedNewSessionHigh"] = "proceed_new_session_high";
345
412
  ToolConfirmationOutcome3["ProceedEdit"] = "proceed_edit";
346
413
  ToolConfirmationOutcome3["Cancel"] = "cancel";
347
414
  return ToolConfirmationOutcome3;
@@ -366,6 +433,11 @@ var DroidWorkingState = /* @__PURE__ */ ((DroidWorkingState2) => {
366
433
  DroidWorkingState2["CompactingConversation"] = "compacting_conversation";
367
434
  return DroidWorkingState2;
368
435
  })(DroidWorkingState || {});
436
+ var ContextStatsAccuracy = /* @__PURE__ */ ((ContextStatsAccuracy2) => {
437
+ ContextStatsAccuracy2["Exact"] = "exact";
438
+ ContextStatsAccuracy2["Estimated"] = "estimated";
439
+ return ContextStatsAccuracy2;
440
+ })(ContextStatsAccuracy || {});
369
441
  var DroidErrorType = /* @__PURE__ */ ((DroidErrorType2) => {
370
442
  DroidErrorType2["CONNECTION_ERROR"] = "ConnectionError";
371
443
  DroidErrorType2["PROTOCOL_ERROR"] = "ProtocolError";
@@ -537,19 +609,39 @@ var SkillLocation = /* @__PURE__ */ ((SkillLocation2) => {
537
609
  // src/schemas/constants.ts
538
610
  var JSONRPC_VERSION = "2.0";
539
611
  var LEGACY_FACTORY_API_VERSION = "1.0.0";
540
- var FACTORY_PROTOCOL_VERSION = "1.2.0";
612
+ var FACTORY_PROTOCOL_VERSION = "1.3.0";
541
613
  var FACTORY_CLIENT_HEADER = "X-Factory-Client";
542
614
  var FACTORY_CLIENT_VERSION = "X-Client-Version";
543
615
  var DEFAULT_REQUEST_TIMEOUT = 3e4;
544
616
  var SESSION_INIT_TIMEOUT = 6e4;
545
617
  var MCP_AUTH_TIMEOUT = 3e5;
618
+ var COMPACTION_TIMEOUT = 24e4;
619
+ var REWIND_TIMEOUT = 6e4;
546
620
 
547
621
  // src/schemas/shared.ts
548
622
  var import_zod = require("zod");
623
+ var JsonValueSchema = import_zod.z.lazy(
624
+ () => import_zod.z.union([
625
+ import_zod.z.string(),
626
+ import_zod.z.number(),
627
+ import_zod.z.boolean(),
628
+ import_zod.z.null(),
629
+ import_zod.z.array(JsonValueSchema),
630
+ import_zod.z.record(JsonValueSchema)
631
+ ])
632
+ );
633
+ var JsonObjectSchema = import_zod.z.record(JsonValueSchema);
634
+ var JsonArraySchema = import_zod.z.array(JsonValueSchema);
549
635
  var TraceContextMetaSchema = import_zod.z.object({
550
636
  traceparent: import_zod.z.string().optional(),
551
637
  tracestate: import_zod.z.string().optional()
552
638
  });
639
+ var ToolSelectionOverridesSchema = import_zod.z.object({
640
+ enabledToolIds: import_zod.z.array(import_zod.z.string()).optional(),
641
+ disabledToolIds: import_zod.z.array(import_zod.z.string()).optional()
642
+ });
643
+ var EmptyResultSchema = import_zod.z.object({}).passthrough();
644
+ var SuccessResultSchema = import_zod.z.object({ success: import_zod.z.boolean() }).passthrough();
553
645
  var JsonRpcEnvelopeSchema = import_zod.z.object({
554
646
  jsonrpc: import_zod.z.literal(JSONRPC_VERSION),
555
647
  factoryApiVersion: import_zod.z.literal(LEGACY_FACTORY_API_VERSION),
@@ -559,18 +651,18 @@ var JsonRpcEnvelopeSchema = import_zod.z.object({
559
651
  var JsonRpcErrorSchema = import_zod.z.object({
560
652
  code: import_zod.z.nativeEnum(JsonRpcErrorCode),
561
653
  message: import_zod.z.string(),
562
- data: import_zod.z.unknown().optional()
654
+ data: JsonValueSchema.optional()
563
655
  });
564
656
  var BaseRequestSchema = import_zod.z.object({
565
657
  type: import_zod.z.literal("request"),
566
658
  id: import_zod.z.string(),
567
659
  method: import_zod.z.string(),
568
- params: import_zod.z.unknown().optional()
660
+ params: JsonValueSchema.optional()
569
661
  });
570
662
  var BaseResponseSuccessSchema = import_zod.z.object({
571
663
  type: import_zod.z.literal("response"),
572
664
  id: import_zod.z.string(),
573
- result: import_zod.z.unknown()
665
+ result: JsonValueSchema
574
666
  });
575
667
  var BaseResponseFailureSchema = import_zod.z.object({
576
668
  type: import_zod.z.literal("response"),
@@ -580,7 +672,7 @@ var BaseResponseFailureSchema = import_zod.z.object({
580
672
  var BaseNotificationSchema = import_zod.z.object({
581
673
  type: import_zod.z.literal("notification"),
582
674
  method: import_zod.z.string(),
583
- params: import_zod.z.unknown().optional()
675
+ params: JsonValueSchema.optional()
584
676
  });
585
677
  var JsonRpcRequestSchema = JsonRpcEnvelopeSchema.extend(
586
678
  BaseRequestSchema.shape
@@ -603,61 +695,128 @@ var JsonRpcMessageSchema = import_zod.z.discriminatedUnion("type", [
603
695
  JsonRpcEnvelopeSchema.extend({
604
696
  type: import_zod.z.literal("response"),
605
697
  id: import_zod.z.string().nullable(),
606
- result: import_zod.z.unknown().optional(),
698
+ result: JsonValueSchema.optional(),
607
699
  error: JsonRpcErrorSchema.optional()
608
700
  }),
609
701
  JsonRpcNotificationSchema
610
702
  ]);
611
703
 
612
- // src/schemas/messages.ts
704
+ // src/schemas/session-metadata.ts
705
+ var import_zod6 = require("zod");
706
+
707
+ // src/schemas/client.ts
708
+ var import_zod5 = require("zod");
709
+
710
+ // src/schemas/mcp.ts
613
711
  var import_zod2 = require("zod");
614
- var TextBlockSchema = import_zod2.z.object({
615
- type: import_zod2.z.literal("text"),
616
- text: import_zod2.z.string(),
617
- id: import_zod2.z.string().optional()
618
- }).passthrough();
619
- var Base64ImageSourceSchema = import_zod2.z.object({
620
- type: import_zod2.z.literal("base64"),
621
- data: import_zod2.z.string(),
622
- mediaType: import_zod2.z.enum(["image/jpeg", "image/png", "image/gif", "image/webp"])
623
- }).passthrough();
624
- var ImageBlockSchema = import_zod2.z.object({
625
- type: import_zod2.z.literal("image"),
626
- source: Base64ImageSourceSchema,
627
- id: import_zod2.z.string().optional()
628
- }).passthrough();
629
- var ThinkingBlockSchema = import_zod2.z.object({
630
- type: import_zod2.z.literal("thinking"),
631
- signature: import_zod2.z.string(),
632
- thinking: import_zod2.z.string(),
633
- id: import_zod2.z.string().optional(),
634
- signatureProvider: import_zod2.z.string().optional()
635
- }).passthrough();
636
- var RedactedThinkingBlockSchema = import_zod2.z.object({
637
- type: import_zod2.z.literal("redacted_thinking"),
638
- data: import_zod2.z.string(),
639
- id: import_zod2.z.string().optional()
640
- }).passthrough();
641
- var ToolUseBlockSchema = import_zod2.z.object({
642
- type: import_zod2.z.literal("tool_use"),
643
- id: import_zod2.z.string(),
644
- input: import_zod2.z.record(import_zod2.z.unknown()),
712
+ var McpStdioServerConfigFieldsSchema = import_zod2.z.object({
713
+ command: import_zod2.z.string().optional(),
714
+ args: import_zod2.z.array(import_zod2.z.string()).optional()
715
+ });
716
+ var McpHttpServerConfigFieldsSchema = import_zod2.z.object({
717
+ url: import_zod2.z.string().optional()
718
+ });
719
+ var McpSseServerConfigFieldsSchema = import_zod2.z.object({
720
+ url: import_zod2.z.string(),
721
+ headers: import_zod2.z.record(import_zod2.z.string()).optional()
722
+ });
723
+ var McpServerStatusInfoSchema = import_zod2.z.object({
724
+ name: import_zod2.z.string(),
725
+ status: import_zod2.z.nativeEnum(McpServerStatus),
726
+ source: import_zod2.z.nativeEnum(SettingsLevel),
727
+ isManaged: import_zod2.z.boolean(),
728
+ error: import_zod2.z.string().optional(),
729
+ toolCount: import_zod2.z.number().optional(),
730
+ serverType: import_zod2.z.nativeEnum(McpServerType).optional(),
731
+ hasAuthTokens: import_zod2.z.boolean().optional()
732
+ }).passthrough();
733
+ var McpStatusSummarySchema = import_zod2.z.object({
734
+ total: import_zod2.z.number(),
735
+ connected: import_zod2.z.number(),
736
+ connecting: import_zod2.z.number(),
737
+ failed: import_zod2.z.number(),
738
+ disabled: import_zod2.z.number().optional()
739
+ }).passthrough();
740
+ var McpRegistryServerSchema = import_zod2.z.object({
645
741
  name: import_zod2.z.string(),
646
- thoughtSignature: import_zod2.z.string().optional()
742
+ description: import_zod2.z.string(),
743
+ type: import_zod2.z.nativeEnum(McpServerType),
744
+ // Stdio config fields
745
+ command: import_zod2.z.string().optional(),
746
+ args: import_zod2.z.array(import_zod2.z.string()).optional(),
747
+ // HTTP config fields
748
+ url: import_zod2.z.string().optional(),
749
+ // Additional metadata
750
+ note: import_zod2.z.string().optional(),
751
+ logoUrl: import_zod2.z.string().optional()
752
+ }).passthrough();
753
+ var McpToolInputSchemaSchema = import_zod2.z.object({
754
+ type: import_zod2.z.string().optional(),
755
+ properties: JsonObjectSchema.optional(),
756
+ required: import_zod2.z.array(import_zod2.z.string()).optional()
757
+ }).passthrough();
758
+ var McpToolInfoSchema = import_zod2.z.object({
759
+ serverName: import_zod2.z.string(),
760
+ name: import_zod2.z.string(),
761
+ description: import_zod2.z.string().optional(),
762
+ isEnabled: import_zod2.z.boolean(),
763
+ isReadOnly: import_zod2.z.boolean().optional(),
764
+ inputSchema: McpToolInputSchemaSchema.optional()
765
+ }).passthrough();
766
+ var ToolConfirmationListItemSchema = import_zod2.z.object({
767
+ label: import_zod2.z.string(),
768
+ value: import_zod2.z.nativeEnum(ToolConfirmationOutcome)
769
+ }).passthrough();
770
+
771
+ // src/schemas/messages.ts
772
+ var import_zod3 = require("zod");
773
+ var TextBlockSchema = import_zod3.z.object({
774
+ type: import_zod3.z.literal("text"),
775
+ text: import_zod3.z.string(),
776
+ id: import_zod3.z.string().optional()
777
+ }).passthrough();
778
+ var Base64ImageSourceSchema = import_zod3.z.object({
779
+ type: import_zod3.z.literal("base64"),
780
+ data: import_zod3.z.string(),
781
+ mediaType: import_zod3.z.enum(["image/jpeg", "image/png", "image/gif", "image/webp"])
782
+ }).passthrough();
783
+ var ImageBlockSchema = import_zod3.z.object({
784
+ type: import_zod3.z.literal("image"),
785
+ source: Base64ImageSourceSchema,
786
+ id: import_zod3.z.string().optional()
787
+ }).passthrough();
788
+ var ThinkingBlockSchema = import_zod3.z.object({
789
+ type: import_zod3.z.literal("thinking"),
790
+ signature: import_zod3.z.string(),
791
+ thinking: import_zod3.z.string(),
792
+ id: import_zod3.z.string().optional(),
793
+ signatureProvider: import_zod3.z.string().optional()
647
794
  }).passthrough();
648
- var ToolResultBlockSchema = import_zod2.z.object({
649
- type: import_zod2.z.literal("tool_result"),
650
- toolUseId: import_zod2.z.string(),
651
- content: import_zod2.z.union([import_zod2.z.string(), import_zod2.z.array(import_zod2.z.unknown())]).optional(),
652
- isError: import_zod2.z.boolean().optional(),
653
- id: import_zod2.z.string().optional()
795
+ var RedactedThinkingBlockSchema = import_zod3.z.object({
796
+ type: import_zod3.z.literal("redacted_thinking"),
797
+ data: import_zod3.z.string(),
798
+ id: import_zod3.z.string().optional()
654
799
  }).passthrough();
655
- var DocumentBlockSchema = import_zod2.z.object({
656
- type: import_zod2.z.literal("document"),
657
- source: import_zod2.z.record(import_zod2.z.unknown()),
658
- id: import_zod2.z.string().optional()
800
+ var ToolUseBlockSchema = import_zod3.z.object({
801
+ type: import_zod3.z.literal("tool_use"),
802
+ id: import_zod3.z.string(),
803
+ input: JsonObjectSchema,
804
+ name: import_zod3.z.string(),
805
+ thoughtSignature: import_zod3.z.string().optional()
806
+ }).passthrough();
807
+ var ToolResultBlockSchema = import_zod3.z.object({
808
+ type: import_zod3.z.literal("tool_result"),
809
+ toolUseId: import_zod3.z.string(),
810
+ content: import_zod3.z.union([import_zod3.z.string(), import_zod3.z.array(JsonValueSchema)]).optional(),
811
+ isError: import_zod3.z.boolean().optional(),
812
+ id: import_zod3.z.string().optional()
659
813
  }).passthrough();
660
- var ContentBlockSchema = import_zod2.z.discriminatedUnion("type", [
814
+ var DocumentBlockSchema = import_zod3.z.object({
815
+ type: import_zod3.z.literal("document"),
816
+ source: JsonObjectSchema,
817
+ id: import_zod3.z.string().optional()
818
+ }).passthrough();
819
+ var ContentBlockSchema = import_zod3.z.discriminatedUnion("type", [
661
820
  TextBlockSchema,
662
821
  ImageBlockSchema,
663
822
  ThinkingBlockSchema,
@@ -666,83 +825,33 @@ var ContentBlockSchema = import_zod2.z.discriminatedUnion("type", [
666
825
  ToolResultBlockSchema,
667
826
  DocumentBlockSchema
668
827
  ]);
669
- var FactoryDroidMessageSchema = import_zod2.z.object({
670
- id: import_zod2.z.string(),
671
- role: import_zod2.z.enum(["user", "assistant", "tool", "system"]),
672
- content: import_zod2.z.array(ContentBlockSchema),
673
- createdAt: import_zod2.z.number(),
674
- updatedAt: import_zod2.z.number(),
675
- parentId: import_zod2.z.string().optional(),
676
- visibility: import_zod2.z.enum(["both", "llm_only", "user_only"]).optional(),
677
- isError: import_zod2.z.boolean().optional()
678
- }).passthrough();
679
- var DocumentSourceSchema = import_zod2.z.object({
680
- type: import_zod2.z.string(),
681
- mediaType: import_zod2.z.string(),
682
- data: import_zod2.z.string(),
683
- name: import_zod2.z.string().optional(),
684
- mime: import_zod2.z.string().optional()
685
- }).strict();
686
-
687
- // src/schemas/mcp.ts
688
- var import_zod3 = require("zod");
689
- var McpStdioServerConfigFieldsSchema = import_zod3.z.object({
690
- command: import_zod3.z.string().optional(),
691
- args: import_zod3.z.array(import_zod3.z.string()).optional()
692
- });
693
- var McpHttpServerConfigFieldsSchema = import_zod3.z.object({
694
- url: import_zod3.z.string().optional()
695
- });
696
- var McpSseServerConfigFieldsSchema = import_zod3.z.object({
697
- url: import_zod3.z.string(),
698
- headers: import_zod3.z.record(import_zod3.z.string()).optional()
699
- });
700
- var McpServerStatusInfoSchema = import_zod3.z.object({
701
- name: import_zod3.z.string(),
702
- status: import_zod3.z.nativeEnum(McpServerStatus),
703
- source: import_zod3.z.nativeEnum(SettingsLevel),
704
- isManaged: import_zod3.z.boolean(),
705
- error: import_zod3.z.string().optional(),
706
- toolCount: import_zod3.z.number().optional(),
707
- serverType: import_zod3.z.nativeEnum(McpServerType).optional(),
708
- hasAuthTokens: import_zod3.z.boolean().optional()
709
- }).passthrough();
710
- var McpStatusSummarySchema = import_zod3.z.object({
711
- total: import_zod3.z.number(),
712
- connected: import_zod3.z.number(),
713
- connecting: import_zod3.z.number(),
714
- failed: import_zod3.z.number(),
715
- disabled: import_zod3.z.number().optional()
716
- }).passthrough();
717
- var McpRegistryServerSchema = import_zod3.z.object({
718
- name: import_zod3.z.string(),
719
- description: import_zod3.z.string(),
720
- type: import_zod3.z.nativeEnum(McpServerType),
721
- // Stdio config fields
722
- command: import_zod3.z.string().optional(),
723
- args: import_zod3.z.array(import_zod3.z.string()).optional(),
724
- // HTTP config fields
725
- url: import_zod3.z.string().optional(),
726
- // Additional metadata
727
- note: import_zod3.z.string().optional(),
728
- logoUrl: import_zod3.z.string().optional()
729
- }).passthrough();
730
- var McpToolInputSchemaSchema = import_zod3.z.object({
731
- type: import_zod3.z.string().optional(),
732
- properties: import_zod3.z.record(import_zod3.z.unknown()).optional(),
733
- required: import_zod3.z.array(import_zod3.z.string()).optional()
734
- }).passthrough();
735
- var McpToolInfoSchema = import_zod3.z.object({
736
- serverName: import_zod3.z.string(),
737
- name: import_zod3.z.string(),
738
- description: import_zod3.z.string().optional(),
739
- isEnabled: import_zod3.z.boolean(),
740
- isReadOnly: import_zod3.z.boolean().optional(),
741
- inputSchema: McpToolInputSchemaSchema.optional()
828
+ var FactoryDroidMessageRole = {
829
+ User: "user",
830
+ Assistant: "assistant",
831
+ Tool: "tool",
832
+ System: "system"
833
+ };
834
+ var FactoryDroidMessageSchema = import_zod3.z.object({
835
+ id: import_zod3.z.string(),
836
+ role: import_zod3.z.enum([
837
+ FactoryDroidMessageRole.User,
838
+ FactoryDroidMessageRole.Assistant,
839
+ FactoryDroidMessageRole.Tool,
840
+ FactoryDroidMessageRole.System
841
+ ]),
842
+ content: import_zod3.z.array(ContentBlockSchema),
843
+ createdAt: import_zod3.z.number(),
844
+ updatedAt: import_zod3.z.number(),
845
+ parentId: import_zod3.z.string().optional(),
846
+ visibility: import_zod3.z.enum(["both", "llm_only", "user_only"]).optional(),
847
+ isError: import_zod3.z.boolean().optional()
742
848
  }).passthrough();
743
- var ToolConfirmationListItemSchema = import_zod3.z.object({
744
- label: import_zod3.z.string(),
745
- value: import_zod3.z.nativeEnum(ToolConfirmationOutcome)
849
+ var DocumentSourceSchema = import_zod3.z.object({
850
+ type: import_zod3.z.string(),
851
+ mediaType: import_zod3.z.string(),
852
+ data: import_zod3.z.string(),
853
+ name: import_zod3.z.string().optional(),
854
+ mime: import_zod3.z.string().optional()
746
855
  }).passthrough();
747
856
 
748
857
  // src/schemas/mission.ts
@@ -893,7 +1002,12 @@ var ProgressLogEntrySchema = import_zod4.z.discriminatedUnion("type", [
893
1002
  ]);
894
1003
 
895
1004
  // src/schemas/client.ts
896
- var import_zod5 = require("zod");
1005
+ var SessionModeRequestFieldsShape = {
1006
+ modelId: import_zod5.z.string().optional(),
1007
+ autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
1008
+ interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional(),
1009
+ autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional()
1010
+ };
897
1011
  var SessionTagSchema = import_zod5.z.object({
898
1012
  name: import_zod5.z.string(),
899
1013
  metadata: import_zod5.z.record(import_zod5.z.string()).optional()
@@ -935,7 +1049,8 @@ var SessionSettingsSchema = import_zod5.z.object({
935
1049
  interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
936
1050
  autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
937
1051
  specModeModelId: import_zod5.z.string().optional(),
938
- specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional()
1052
+ specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1053
+ ...ToolSelectionOverridesSchema.shape
939
1054
  }).passthrough();
940
1055
  var GitRepoInfoSchema = import_zod5.z.object({
941
1056
  owner: import_zod5.z.string().optional(),
@@ -955,7 +1070,7 @@ var AvailableModelConfigSchema = import_zod5.z.object({
955
1070
  tier: import_zod5.z.string().optional(),
956
1071
  tokenMultiplier: import_zod5.z.number().optional(),
957
1072
  promoLabel: import_zod5.z.string().optional(),
958
- featureFlag: import_zod5.z.record(import_zod5.z.unknown()).optional(),
1073
+ featureFlag: JsonObjectSchema.optional(),
959
1074
  usesUSBasedInference: import_zod5.z.boolean().optional()
960
1075
  }).passthrough();
961
1076
  var TokenUsageSchema = import_zod5.z.object({
@@ -965,6 +1080,13 @@ var TokenUsageSchema = import_zod5.z.object({
965
1080
  cacheReadTokens: import_zod5.z.number(),
966
1081
  thinkingTokens: import_zod5.z.number()
967
1082
  }).passthrough();
1083
+ var ContextStatsSchema = import_zod5.z.object({
1084
+ used: import_zod5.z.number(),
1085
+ remaining: import_zod5.z.number(),
1086
+ limit: import_zod5.z.number(),
1087
+ accuracy: import_zod5.z.nativeEnum(ContextStatsAccuracy),
1088
+ updatedAt: import_zod5.z.string()
1089
+ }).passthrough();
968
1090
  var WorkerStateInfoSchema = import_zod5.z.object({
969
1091
  startedAt: import_zod5.z.string(),
970
1092
  completedAt: import_zod5.z.string().optional(),
@@ -992,17 +1114,14 @@ var InitializeSessionRequestParamsSchema = import_zod5.z.object({
992
1114
  workspaceId: import_zod5.z.string().optional(),
993
1115
  sessionId: import_zod5.z.string().optional(),
994
1116
  mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
995
- autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
996
- interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
997
- autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
998
- modelId: import_zod5.z.string().optional(),
1117
+ ...SessionModeRequestFieldsShape,
999
1118
  reasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1000
1119
  specModeModelId: import_zod5.z.string().optional(),
1001
1120
  specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1002
1121
  decompSessionType: import_zod5.z.nativeEnum(DecompSessionType).optional(),
1003
1122
  decompMissionId: import_zod5.z.string().optional(),
1004
1123
  skipPermissionsUnsafe: import_zod5.z.boolean().optional(),
1005
- enabledToolIds: import_zod5.z.array(import_zod5.z.string()).optional(),
1124
+ ...ToolSelectionOverridesSchema.shape,
1006
1125
  sessionLocation: import_zod5.z.string().optional(),
1007
1126
  sessionSource: SessionSourceSchema.optional(),
1008
1127
  tags: import_zod5.z.array(SessionTagSchema).optional(),
@@ -1013,24 +1132,30 @@ var LoadSessionRequestParamsSchema = import_zod5.z.object({
1013
1132
  mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1014
1133
  mcpOAuthCallbackUri: import_zod5.z.string().optional()
1015
1134
  }).strict();
1135
+ var OutputFormatType = {
1136
+ JsonSchema: "json_schema"
1137
+ };
1138
+ var OutputFormatSchema = import_zod5.z.object({
1139
+ type: import_zod5.z.literal(OutputFormatType.JsonSchema),
1140
+ schema: JsonObjectSchema
1141
+ }).strict();
1016
1142
  var AddUserMessageRequestParamsSchema = import_zod5.z.object({
1017
1143
  messageId: import_zod5.z.string().optional(),
1018
1144
  text: import_zod5.z.string(),
1019
1145
  images: import_zod5.z.array(Base64ImageSourceSchema).optional(),
1020
- files: import_zod5.z.array(DocumentSourceSchema).optional()
1146
+ files: import_zod5.z.array(DocumentSourceSchema).optional(),
1147
+ outputFormat: OutputFormatSchema.optional()
1021
1148
  }).strict();
1022
1149
  var InterruptSessionRequestParamsSchema = import_zod5.z.object({}).strict();
1023
1150
  var KillWorkerSessionRequestParamsSchema = import_zod5.z.object({
1024
1151
  workerSessionId: import_zod5.z.string()
1025
1152
  }).strict();
1026
1153
  var UpdateSessionSettingsRequestParamsSchema = import_zod5.z.object({
1027
- modelId: import_zod5.z.string().optional(),
1154
+ ...SessionModeRequestFieldsShape,
1028
1155
  reasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).optional(),
1029
- autonomyMode: import_zod5.z.nativeEnum(AutonomyMode).optional(),
1030
- interactionMode: import_zod5.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1031
- autonomyLevel: import_zod5.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1032
1156
  specModeModelId: import_zod5.z.string().nullable().optional(),
1033
- specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).nullable().optional()
1157
+ specModeReasoningEffort: import_zod5.z.nativeEnum(ReasoningEffort).nullable().optional(),
1158
+ ...ToolSelectionOverridesSchema.shape
1034
1159
  }).strict();
1035
1160
  var ToggleMcpServerRequestParamsSchema = import_zod5.z.object({
1036
1161
  serverName: import_zod5.z.string(),
@@ -1066,6 +1191,22 @@ var RemoveMcpServerRequestParamsSchema = import_zod5.z.object({
1066
1191
  }).strict();
1067
1192
  var ListMcpRegistryRequestParamsSchema = import_zod5.z.object({}).strict();
1068
1193
  var ListMcpToolsRequestParamsSchema = import_zod5.z.object({}).strict();
1194
+ var ExecToolInfoSchema = import_zod5.z.object({
1195
+ id: import_zod5.z.string(),
1196
+ llmId: import_zod5.z.string(),
1197
+ displayName: import_zod5.z.string(),
1198
+ description: import_zod5.z.string(),
1199
+ category: import_zod5.z.enum(["read", "edit", "execute", "other"]),
1200
+ defaultAllowed: import_zod5.z.boolean(),
1201
+ currentlyAllowed: import_zod5.z.boolean()
1202
+ }).passthrough();
1203
+ var ListToolsRequestParamsSchema = import_zod5.z.object({
1204
+ ...SessionModeRequestFieldsShape,
1205
+ specModeModelId: import_zod5.z.string().nullable().optional(),
1206
+ skipPermissionsUnsafe: import_zod5.z.boolean().optional(),
1207
+ ...ToolSelectionOverridesSchema.shape,
1208
+ depth: import_zod5.z.number().int().min(0).optional()
1209
+ }).strict();
1069
1210
  var ListMcpServersRequestParamsSchema = import_zod5.z.object({}).strict();
1070
1211
  var ToggleMcpToolRequestParamsSchema = import_zod5.z.object({
1071
1212
  serverName: import_zod5.z.string(),
@@ -1077,6 +1218,35 @@ var SubmitBugReportRequestParamsSchema = import_zod5.z.object({
1077
1218
  userComment: import_zod5.z.string(),
1078
1219
  clientLogs: import_zod5.z.string().optional()
1079
1220
  }).strict();
1221
+ var RewindFileSnapshotSchema = import_zod5.z.object({
1222
+ filePath: import_zod5.z.string(),
1223
+ contentHash: import_zod5.z.string(),
1224
+ size: import_zod5.z.number()
1225
+ }).passthrough();
1226
+ var RewindFileCreationSchema = import_zod5.z.object({
1227
+ filePath: import_zod5.z.string()
1228
+ }).passthrough();
1229
+ var RewindEvictedFileSchema = import_zod5.z.object({
1230
+ filePath: import_zod5.z.string(),
1231
+ reason: import_zod5.z.string()
1232
+ }).passthrough();
1233
+ var GetRewindInfoRequestParamsSchema = import_zod5.z.object({
1234
+ messageId: import_zod5.z.string()
1235
+ }).passthrough();
1236
+ var ExecuteRewindRequestParamsSchema = import_zod5.z.object({
1237
+ messageId: import_zod5.z.string(),
1238
+ filesToRestore: import_zod5.z.array(RewindFileSnapshotSchema),
1239
+ filesToDelete: import_zod5.z.array(RewindFileCreationSchema),
1240
+ forkTitle: import_zod5.z.string()
1241
+ }).passthrough();
1242
+ var CompactSessionRequestParamsSchema = import_zod5.z.object({
1243
+ customInstructions: import_zod5.z.string().optional()
1244
+ }).passthrough();
1245
+ var RenameSessionRequestParamsSchema = import_zod5.z.object({
1246
+ title: import_zod5.z.string()
1247
+ }).passthrough();
1248
+ var ForkSessionRequestParamsSchema = import_zod5.z.object({}).passthrough();
1249
+ var GetContextStatsRequestParamsSchema = import_zod5.z.object({}).passthrough();
1080
1250
  var InitializeSessionRequestSchema = JsonRpcRequestSchema.extend({
1081
1251
  method: import_zod5.z.literal("droid.initialize_session" /* INITIALIZE_SESSION */),
1082
1252
  params: InitializeSessionRequestParamsSchema
@@ -1137,6 +1307,10 @@ var ListMcpToolsRequestSchema = JsonRpcRequestSchema.extend({
1137
1307
  method: import_zod5.z.literal("droid.list_mcp_tools" /* LIST_MCP_TOOLS */),
1138
1308
  params: ListMcpToolsRequestParamsSchema
1139
1309
  });
1310
+ var ListToolsRequestSchema = JsonRpcRequestSchema.extend({
1311
+ method: import_zod5.z.literal("droid.list_tools" /* LIST_TOOLS */),
1312
+ params: ListToolsRequestParamsSchema
1313
+ });
1140
1314
  var ListMcpServersRequestSchema = JsonRpcRequestSchema.extend({
1141
1315
  method: import_zod5.z.literal("droid.list_mcp_servers" /* LIST_MCP_SERVERS */),
1142
1316
  params: ListMcpServersRequestParamsSchema
@@ -1153,6 +1327,30 @@ var SubmitBugReportRequestSchema = JsonRpcRequestSchema.extend({
1153
1327
  method: import_zod5.z.literal("droid.submit_bug_report" /* SUBMIT_BUG_REPORT */),
1154
1328
  params: SubmitBugReportRequestParamsSchema
1155
1329
  });
1330
+ var GetRewindInfoRequestSchema = JsonRpcRequestSchema.extend({
1331
+ method: import_zod5.z.literal("droid.get_rewind_info" /* GET_REWIND_INFO */),
1332
+ params: GetRewindInfoRequestParamsSchema
1333
+ });
1334
+ var ExecuteRewindRequestSchema = JsonRpcRequestSchema.extend({
1335
+ method: import_zod5.z.literal("droid.execute_rewind" /* EXECUTE_REWIND */),
1336
+ params: ExecuteRewindRequestParamsSchema
1337
+ });
1338
+ var CompactSessionRequestSchema = JsonRpcRequestSchema.extend({
1339
+ method: import_zod5.z.literal("droid.compact_session" /* COMPACT_SESSION */),
1340
+ params: CompactSessionRequestParamsSchema
1341
+ });
1342
+ var ForkSessionRequestSchema = JsonRpcRequestSchema.extend({
1343
+ method: import_zod5.z.literal("droid.fork_session" /* FORK_SESSION */),
1344
+ params: ForkSessionRequestParamsSchema
1345
+ });
1346
+ var GetContextStatsRequestSchema = JsonRpcRequestSchema.extend({
1347
+ method: import_zod5.z.literal("droid.get_context_stats" /* GET_CONTEXT_STATS */),
1348
+ params: GetContextStatsRequestParamsSchema
1349
+ });
1350
+ var RenameSessionRequestSchema = JsonRpcRequestSchema.extend({
1351
+ method: import_zod5.z.literal("droid.rename_session" /* RENAME_SESSION */),
1352
+ params: RenameSessionRequestParamsSchema
1353
+ });
1156
1354
  var ClientRequestSchema = import_zod5.z.discriminatedUnion("method", [
1157
1355
  InitializeSessionRequestSchema,
1158
1356
  LoadSessionRequestSchema,
@@ -1169,10 +1367,17 @@ var ClientRequestSchema = import_zod5.z.discriminatedUnion("method", [
1169
1367
  RemoveMcpServerRequestSchema,
1170
1368
  ListMcpRegistryRequestSchema,
1171
1369
  ListMcpToolsRequestSchema,
1370
+ ListToolsRequestSchema,
1172
1371
  ListMcpServersRequestSchema,
1173
1372
  ToggleMcpToolRequestSchema,
1174
1373
  ListSkillsRequestSchema,
1175
- SubmitBugReportRequestSchema
1374
+ SubmitBugReportRequestSchema,
1375
+ GetRewindInfoRequestSchema,
1376
+ ExecuteRewindRequestSchema,
1377
+ CompactSessionRequestSchema,
1378
+ ForkSessionRequestSchema,
1379
+ GetContextStatsRequestSchema,
1380
+ RenameSessionRequestSchema
1176
1381
  ]);
1177
1382
  var MissionSnapshotSchema = import_zod5.z.object({
1178
1383
  state: import_zod5.z.nativeEnum(MissionState),
@@ -1185,20 +1390,20 @@ var MissionSnapshotSchema = import_zod5.z.object({
1185
1390
  }).passthrough();
1186
1391
  var InitializeSessionResultSchema = import_zod5.z.object({
1187
1392
  sessionId: import_zod5.z.string(),
1188
- session: import_zod5.z.record(import_zod5.z.unknown()),
1393
+ session: JsonObjectSchema,
1189
1394
  mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1190
1395
  settings: SessionSettingsSchema,
1191
1396
  gitRepo: GitRepoInfoSchema.optional(),
1192
1397
  availableModels: import_zod5.z.array(AvailableModelConfigSchema).optional()
1193
1398
  }).passthrough();
1194
1399
  var LoadSessionResultSchema = import_zod5.z.object({
1195
- session: import_zod5.z.record(import_zod5.z.unknown()),
1400
+ session: JsonObjectSchema,
1196
1401
  mcpServers: import_zod5.z.array(McpServerConfigSchema).optional(),
1197
- pendingPermissions: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1198
- pendingAskUserRequests: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1402
+ pendingPermissions: import_zod5.z.array(JsonObjectSchema).optional(),
1403
+ pendingAskUserRequests: import_zod5.z.array(JsonObjectSchema).optional(),
1199
1404
  settings: SessionSettingsSchema,
1200
1405
  isAgentLoopInProgress: import_zod5.z.boolean().optional(),
1201
- queuedMessages: import_zod5.z.array(import_zod5.z.record(import_zod5.z.unknown())).optional(),
1406
+ queuedMessages: import_zod5.z.array(JsonObjectSchema).optional(),
1202
1407
  gitRepo: GitRepoInfoSchema.optional(),
1203
1408
  cwd: import_zod5.z.string().optional(),
1204
1409
  callingSessionId: import_zod5.z.string().optional(),
@@ -1208,26 +1413,48 @@ var LoadSessionResultSchema = import_zod5.z.object({
1208
1413
  mission: MissionSnapshotSchema.optional(),
1209
1414
  decompSessionType: import_zod5.z.nativeEnum(DecompSessionType).optional()
1210
1415
  }).passthrough();
1211
- var AddUserMessageResultSchema = import_zod5.z.object({}).passthrough();
1212
- var InterruptSessionResultSchema = import_zod5.z.object({}).passthrough();
1213
- var KillWorkerSessionResultSchema = import_zod5.z.object({}).passthrough();
1214
- var UpdateSessionSettingsResultSchema = import_zod5.z.object({}).passthrough();
1215
- var ToggleMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1216
- var AuthenticateMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1217
- var CancelMcpAuthResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1218
- var ClearMcpAuthResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1219
- var SubmitMcpAuthCodeResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1220
- var AddMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1221
- var RemoveMcpServerResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1416
+ var AddUserMessageResultSchema = EmptyResultSchema;
1417
+ var InterruptSessionResultSchema = EmptyResultSchema;
1418
+ var KillWorkerSessionResultSchema = EmptyResultSchema;
1419
+ var UpdateSessionSettingsResultSchema = EmptyResultSchema;
1420
+ var ToggleMcpServerResultSchema = SuccessResultSchema;
1421
+ var AuthenticateMcpServerResultSchema = SuccessResultSchema;
1422
+ var CancelMcpAuthResultSchema = SuccessResultSchema;
1423
+ var ClearMcpAuthResultSchema = SuccessResultSchema;
1424
+ var SubmitMcpAuthCodeResultSchema = SuccessResultSchema;
1425
+ var AddMcpServerResultSchema = SuccessResultSchema;
1426
+ var RemoveMcpServerResultSchema = SuccessResultSchema;
1222
1427
  var ListMcpRegistryResultSchema = import_zod5.z.object({ servers: import_zod5.z.array(McpRegistryServerSchema) }).passthrough();
1223
1428
  var ListMcpToolsResultSchema = import_zod5.z.object({ tools: import_zod5.z.array(McpToolInfoSchema) }).passthrough();
1429
+ var ListToolsResultSchema = import_zod5.z.object({ tools: import_zod5.z.array(ExecToolInfoSchema) }).passthrough();
1224
1430
  var ListMcpServersResultSchema = import_zod5.z.object({
1225
1431
  servers: import_zod5.z.array(McpServerStatusInfoSchema),
1226
1432
  summary: McpStatusSummarySchema
1227
1433
  }).passthrough();
1228
- var ToggleMcpToolResultSchema = import_zod5.z.object({ success: import_zod5.z.boolean() }).passthrough();
1434
+ var ToggleMcpToolResultSchema = SuccessResultSchema;
1229
1435
  var ListSkillsResultSchema = import_zod5.z.object({ skills: import_zod5.z.array(SkillInfoSchema) }).passthrough();
1230
1436
  var SubmitBugReportResultSchema = import_zod5.z.object({ bugReportId: import_zod5.z.string() }).passthrough();
1437
+ var GetRewindInfoResultSchema = import_zod5.z.object({
1438
+ availableFiles: import_zod5.z.array(RewindFileSnapshotSchema),
1439
+ createdFiles: import_zod5.z.array(RewindFileCreationSchema),
1440
+ evictedFiles: import_zod5.z.array(RewindEvictedFileSchema)
1441
+ }).passthrough();
1442
+ var ExecuteRewindResultSchema = import_zod5.z.object({
1443
+ newSessionId: import_zod5.z.string(),
1444
+ restoredCount: import_zod5.z.number(),
1445
+ deletedCount: import_zod5.z.number(),
1446
+ failedRestoreCount: import_zod5.z.number(),
1447
+ failedDeleteCount: import_zod5.z.number()
1448
+ }).passthrough();
1449
+ var CompactSessionResultSchema = import_zod5.z.object({
1450
+ newSessionId: import_zod5.z.string(),
1451
+ removedCount: import_zod5.z.number()
1452
+ }).passthrough();
1453
+ var ForkSessionResultSchema = import_zod5.z.object({
1454
+ newSessionId: import_zod5.z.string()
1455
+ }).passthrough();
1456
+ var GetContextStatsResultSchema = ContextStatsSchema;
1457
+ var RenameSessionResultSchema = SuccessResultSchema;
1231
1458
  var InitializeSessionResponseSchema = import_zod5.z.union([
1232
1459
  JsonRpcResponseSuccessSchema.extend({
1233
1460
  result: InitializeSessionResultSchema
@@ -1305,6 +1532,10 @@ var ListMcpToolsResponseSchema = import_zod5.z.union([
1305
1532
  JsonRpcResponseSuccessSchema.extend({ result: ListMcpToolsResultSchema }),
1306
1533
  JsonRpcResponseFailureSchema
1307
1534
  ]);
1535
+ var ListToolsResponseSchema = import_zod5.z.union([
1536
+ JsonRpcResponseSuccessSchema.extend({ result: ListToolsResultSchema }),
1537
+ JsonRpcResponseFailureSchema
1538
+ ]);
1308
1539
  var ListMcpServersResponseSchema = import_zod5.z.union([
1309
1540
  JsonRpcResponseSuccessSchema.extend({ result: ListMcpServersResultSchema }),
1310
1541
  JsonRpcResponseFailureSchema
@@ -1321,145 +1552,194 @@ var SubmitBugReportResponseSchema = import_zod5.z.union([
1321
1552
  JsonRpcResponseSuccessSchema.extend({ result: SubmitBugReportResultSchema }),
1322
1553
  JsonRpcResponseFailureSchema
1323
1554
  ]);
1555
+ var GetRewindInfoResponseSchema = import_zod5.z.union([
1556
+ JsonRpcResponseSuccessSchema.extend({ result: GetRewindInfoResultSchema }),
1557
+ JsonRpcResponseFailureSchema
1558
+ ]);
1559
+ var ExecuteRewindResponseSchema = import_zod5.z.union([
1560
+ JsonRpcResponseSuccessSchema.extend({ result: ExecuteRewindResultSchema }),
1561
+ JsonRpcResponseFailureSchema
1562
+ ]);
1563
+ var CompactSessionResponseSchema = import_zod5.z.union([
1564
+ JsonRpcResponseSuccessSchema.extend({ result: CompactSessionResultSchema }),
1565
+ JsonRpcResponseFailureSchema
1566
+ ]);
1567
+ var ForkSessionResponseSchema = import_zod5.z.union([
1568
+ JsonRpcResponseSuccessSchema.extend({ result: ForkSessionResultSchema }),
1569
+ JsonRpcResponseFailureSchema
1570
+ ]);
1571
+ var GetContextStatsResponseSchema = import_zod5.z.union([
1572
+ JsonRpcResponseSuccessSchema.extend({ result: GetContextStatsResultSchema }),
1573
+ JsonRpcResponseFailureSchema
1574
+ ]);
1575
+ var RenameSessionResponseSchema = import_zod5.z.union([
1576
+ JsonRpcResponseSuccessSchema.extend({ result: RenameSessionResultSchema }),
1577
+ JsonRpcResponseFailureSchema
1578
+ ]);
1324
1579
 
1325
- // src/schemas/server.ts
1326
- var import_zod6 = require("zod");
1327
- var ToolUseSchema = import_zod6.z.object({
1328
- type: import_zod6.z.literal("tool_use"),
1580
+ // src/schemas/session-metadata.ts
1581
+ var SessionMetadataSchema = import_zod6.z.object({
1329
1582
  id: import_zod6.z.string(),
1330
- input: import_zod6.z.record(import_zod6.z.unknown()),
1331
- name: import_zod6.z.string(),
1332
- thoughtSignature: import_zod6.z.string().optional()
1333
- }).passthrough();
1334
- var ErrorDetailSchema = import_zod6.z.object({
1335
- name: import_zod6.z.string(),
1336
- message: import_zod6.z.string()
1337
- }).passthrough();
1338
- var ToolProgressUpdateSchema = import_zod6.z.object({
1339
- type: import_zod6.z.enum(["tool_call", "tool_result", "error", "status", "message"]),
1340
- toolName: import_zod6.z.string().optional(),
1341
- status: import_zod6.z.string().optional(),
1342
- details: import_zod6.z.string().optional(),
1343
- text: import_zod6.z.string().optional(),
1344
- error: import_zod6.z.string().optional(),
1345
- timestamp: import_zod6.z.number().optional(),
1346
- parameters: import_zod6.z.record(import_zod6.z.unknown()).optional(),
1347
- valueSnippet: import_zod6.z.string().optional(),
1348
- subagentSessionId: import_zod6.z.string().optional()
1349
- }).passthrough();
1350
- var SettingsUpdatedPayloadSchema = import_zod6.z.object({
1351
- autonomyMode: import_zod6.z.nativeEnum(AutonomyMode).optional(),
1352
- interactionMode: import_zod6.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1353
- autonomyLevel: import_zod6.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1354
- modelId: import_zod6.z.string().optional(),
1355
- reasoningEffort: import_zod6.z.nativeEnum(ReasoningEffort).optional(),
1356
- specModeModelId: import_zod6.z.string().optional(),
1357
- specModeReasoningEffort: import_zod6.z.nativeEnum(ReasoningEffort).optional()
1358
- }).passthrough();
1359
- var ToolResultNotificationSchema = import_zod6.z.object({
1360
- type: import_zod6.z.literal("tool_result" /* TOOL_RESULT */),
1361
- messageId: import_zod6.z.string(),
1362
- toolUseId: import_zod6.z.string(),
1363
- content: import_zod6.z.unknown().optional(),
1364
- isError: import_zod6.z.boolean().optional(),
1365
- id: import_zod6.z.string().optional()
1366
- }).passthrough();
1367
- var ToolProgressUpdateNotificationSchema = import_zod6.z.object({
1368
- type: import_zod6.z.literal("tool_progress_update" /* TOOL_PROGRESS_UPDATE */),
1369
- toolUseId: import_zod6.z.string(),
1370
- toolName: import_zod6.z.string(),
1583
+ title: import_zod6.z.string(),
1584
+ sessionTitle: import_zod6.z.string().optional(),
1585
+ owner: import_zod6.z.string(),
1586
+ messageCount: import_zod6.z.number(),
1587
+ modifiedTime: import_zod6.z.date(),
1588
+ createdTime: import_zod6.z.date(),
1589
+ isFavorite: import_zod6.z.boolean().optional(),
1590
+ cwd: import_zod6.z.string().optional(),
1591
+ decompSessionType: import_zod6.z.nativeEnum(DecompSessionType).optional(),
1592
+ decompMissionId: import_zod6.z.string().optional()
1593
+ }).passthrough();
1594
+ var SessionStartEventSchema = import_zod6.z.object({
1595
+ type: import_zod6.z.literal("session_start"),
1596
+ sessionId: import_zod6.z.string().optional(),
1597
+ title: import_zod6.z.string().optional(),
1598
+ sessionTitle: import_zod6.z.string().optional(),
1599
+ owner: import_zod6.z.string().optional(),
1600
+ cwd: import_zod6.z.string().optional(),
1601
+ decompSessionType: import_zod6.z.nativeEnum(DecompSessionType).optional().catch(void 0),
1602
+ decompMissionId: import_zod6.z.string().optional()
1603
+ }).passthrough();
1604
+ var SessionSettingsFileSchema = import_zod6.z.object({
1605
+ archivedAt: import_zod6.z.string().optional(),
1606
+ tags: import_zod6.z.array(SessionTagSchema).optional()
1607
+ }).passthrough();
1608
+
1609
+ // src/schemas/server.ts
1610
+ var import_zod7 = require("zod");
1611
+ var ToolUseBlockSchema2 = ToolUseBlockSchema;
1612
+ var ToolUseSchema = ToolUseBlockSchema2;
1613
+ var ErrorDetailSchema = import_zod7.z.object({
1614
+ name: import_zod7.z.string(),
1615
+ message: import_zod7.z.string()
1616
+ }).passthrough();
1617
+ var ToolProgressUpdateSchema = import_zod7.z.object({
1618
+ type: import_zod7.z.enum(["tool_call", "tool_result", "error", "status", "message"]),
1619
+ toolName: import_zod7.z.string().optional(),
1620
+ status: import_zod7.z.string().optional(),
1621
+ details: import_zod7.z.string().optional(),
1622
+ text: import_zod7.z.string().optional(),
1623
+ error: import_zod7.z.string().optional(),
1624
+ timestamp: import_zod7.z.number().optional(),
1625
+ parameters: JsonObjectSchema.optional(),
1626
+ valueSnippet: import_zod7.z.string().optional(),
1627
+ subagentSessionId: import_zod7.z.string().optional()
1628
+ }).passthrough();
1629
+ var SettingsUpdatedPayloadSchema = import_zod7.z.object({
1630
+ autonomyMode: import_zod7.z.nativeEnum(AutonomyMode).optional(),
1631
+ interactionMode: import_zod7.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1632
+ autonomyLevel: import_zod7.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1633
+ modelId: import_zod7.z.string().optional(),
1634
+ reasoningEffort: import_zod7.z.nativeEnum(ReasoningEffort).optional(),
1635
+ specModeModelId: import_zod7.z.string().optional(),
1636
+ specModeReasoningEffort: import_zod7.z.nativeEnum(ReasoningEffort).optional(),
1637
+ ...ToolSelectionOverridesSchema.shape
1638
+ }).passthrough();
1639
+ var ToolResultNotificationSchema = import_zod7.z.object({
1640
+ type: import_zod7.z.literal("tool_result" /* TOOL_RESULT */),
1641
+ messageId: import_zod7.z.string(),
1642
+ toolUseId: import_zod7.z.string(),
1643
+ content: JsonValueSchema.optional(),
1644
+ isError: import_zod7.z.boolean().optional(),
1645
+ id: import_zod7.z.string().optional()
1646
+ }).passthrough();
1647
+ var ToolProgressUpdateNotificationSchema = import_zod7.z.object({
1648
+ type: import_zod7.z.literal("tool_progress_update" /* TOOL_PROGRESS_UPDATE */),
1649
+ toolUseId: import_zod7.z.string(),
1650
+ toolName: import_zod7.z.string(),
1371
1651
  update: ToolProgressUpdateSchema
1372
1652
  }).passthrough();
1373
- var CreateMessageNotificationSchema = import_zod6.z.object({
1374
- type: import_zod6.z.literal("create_message" /* CREATE_MESSAGE */),
1653
+ var CreateMessageNotificationSchema = import_zod7.z.object({
1654
+ type: import_zod7.z.literal("create_message" /* CREATE_MESSAGE */),
1375
1655
  message: FactoryDroidMessageSchema,
1376
- parentId: import_zod6.z.string().optional(),
1377
- requestId: import_zod6.z.string().optional()
1378
- }).passthrough();
1379
- var ErrorNotificationSchema = import_zod6.z.object({
1380
- type: import_zod6.z.literal("error" /* ERROR */),
1381
- message: import_zod6.z.string(),
1382
- errorType: import_zod6.z.nativeEnum(DroidErrorType),
1383
- timestamp: import_zod6.z.string(),
1656
+ parentId: import_zod7.z.string().optional(),
1657
+ requestId: import_zod7.z.string().optional()
1658
+ }).passthrough();
1659
+ var ErrorNotificationSchema = import_zod7.z.object({
1660
+ type: import_zod7.z.literal("error" /* ERROR */),
1661
+ message: import_zod7.z.string(),
1662
+ errorType: import_zod7.z.nativeEnum(DroidErrorType),
1663
+ timestamp: import_zod7.z.string(),
1384
1664
  error: ErrorDetailSchema.optional()
1385
1665
  }).passthrough();
1386
- var DroidWorkingStateChangedNotificationSchema = import_zod6.z.object({
1387
- type: import_zod6.z.literal("droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */),
1388
- newState: import_zod6.z.nativeEnum(DroidWorkingState)
1666
+ var DroidWorkingStateChangedNotificationSchema = import_zod7.z.object({
1667
+ type: import_zod7.z.literal("droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */),
1668
+ newState: import_zod7.z.nativeEnum(DroidWorkingState)
1389
1669
  }).passthrough();
1390
- var PermissionResolvedNotificationSchema = import_zod6.z.object({
1391
- type: import_zod6.z.literal("permission_resolved" /* PERMISSION_RESOLVED */),
1392
- requestId: import_zod6.z.string(),
1393
- toolUseIds: import_zod6.z.array(import_zod6.z.string()),
1394
- selectedOption: import_zod6.z.nativeEnum(ToolConfirmationOutcome)
1670
+ var PermissionResolvedNotificationSchema = import_zod7.z.object({
1671
+ type: import_zod7.z.literal("permission_resolved" /* PERMISSION_RESOLVED */),
1672
+ requestId: import_zod7.z.string(),
1673
+ toolUseIds: import_zod7.z.array(import_zod7.z.string()),
1674
+ selectedOption: import_zod7.z.nativeEnum(ToolConfirmationOutcome)
1395
1675
  }).passthrough();
1396
- var SettingsUpdatedNotificationSchema = import_zod6.z.object({
1397
- type: import_zod6.z.literal("settings_updated" /* SETTINGS_UPDATED */),
1676
+ var SettingsUpdatedNotificationSchema = import_zod7.z.object({
1677
+ type: import_zod7.z.literal("settings_updated" /* SETTINGS_UPDATED */),
1398
1678
  settings: SettingsUpdatedPayloadSchema
1399
1679
  }).passthrough();
1400
- var SessionTitleUpdatedNotificationSchema = import_zod6.z.object({
1401
- type: import_zod6.z.literal("session_title_updated" /* SESSION_TITLE_UPDATED */),
1402
- title: import_zod6.z.string()
1680
+ var SessionTitleUpdatedNotificationSchema = import_zod7.z.object({
1681
+ type: import_zod7.z.literal("session_title_updated" /* SESSION_TITLE_UPDATED */),
1682
+ title: import_zod7.z.string()
1403
1683
  }).passthrough();
1404
- var McpStatusChangedNotificationSchema = import_zod6.z.object({
1405
- type: import_zod6.z.literal("mcp_status_changed" /* MCP_STATUS_CHANGED */),
1406
- servers: import_zod6.z.array(McpServerStatusInfoSchema),
1684
+ var McpStatusChangedNotificationSchema = import_zod7.z.object({
1685
+ type: import_zod7.z.literal("mcp_status_changed" /* MCP_STATUS_CHANGED */),
1686
+ servers: import_zod7.z.array(McpServerStatusInfoSchema),
1407
1687
  summary: McpStatusSummarySchema
1408
1688
  }).passthrough();
1409
- var AssistantTextDeltaNotificationSchema = import_zod6.z.object({
1410
- type: import_zod6.z.literal("assistant_text_delta" /* ASSISTANT_TEXT_DELTA */),
1411
- messageId: import_zod6.z.string(),
1412
- blockIndex: import_zod6.z.number(),
1413
- textDelta: import_zod6.z.string()
1414
- }).passthrough();
1415
- var ThinkingTextDeltaNotificationSchema = import_zod6.z.object({
1416
- type: import_zod6.z.literal("thinking_text_delta" /* THINKING_TEXT_DELTA */),
1417
- messageId: import_zod6.z.string(),
1418
- blockIndex: import_zod6.z.number(),
1419
- textDelta: import_zod6.z.string()
1420
- }).passthrough();
1421
- var SessionTokenUsageChangedNotificationSchema = import_zod6.z.object({
1422
- type: import_zod6.z.literal("session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */),
1423
- sessionId: import_zod6.z.string(),
1689
+ var AssistantTextDeltaNotificationSchema = import_zod7.z.object({
1690
+ type: import_zod7.z.literal("assistant_text_delta" /* ASSISTANT_TEXT_DELTA */),
1691
+ messageId: import_zod7.z.string(),
1692
+ blockIndex: import_zod7.z.number(),
1693
+ textDelta: import_zod7.z.string()
1694
+ }).passthrough();
1695
+ var ThinkingTextDeltaNotificationSchema = import_zod7.z.object({
1696
+ type: import_zod7.z.literal("thinking_text_delta" /* THINKING_TEXT_DELTA */),
1697
+ messageId: import_zod7.z.string(),
1698
+ blockIndex: import_zod7.z.number(),
1699
+ textDelta: import_zod7.z.string()
1700
+ }).passthrough();
1701
+ var SessionTokenUsageChangedNotificationSchema = import_zod7.z.object({
1702
+ type: import_zod7.z.literal("session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */),
1703
+ sessionId: import_zod7.z.string(),
1424
1704
  tokenUsage: TokenUsageSchema
1425
1705
  }).passthrough();
1426
- var MissionStateChangedNotificationSchema = import_zod6.z.object({
1427
- type: import_zod6.z.literal("mission_state_changed" /* MISSION_STATE_CHANGED */),
1428
- state: import_zod6.z.nativeEnum(MissionState)
1706
+ var MissionStateChangedNotificationSchema = import_zod7.z.object({
1707
+ type: import_zod7.z.literal("mission_state_changed" /* MISSION_STATE_CHANGED */),
1708
+ state: import_zod7.z.nativeEnum(MissionState)
1429
1709
  }).passthrough();
1430
- var MissionFeaturesChangedNotificationSchema = import_zod6.z.object({
1431
- type: import_zod6.z.literal("mission_features_changed" /* MISSION_FEATURES_CHANGED */),
1432
- features: import_zod6.z.array(MissionFeatureSchema)
1710
+ var MissionFeaturesChangedNotificationSchema = import_zod7.z.object({
1711
+ type: import_zod7.z.literal("mission_features_changed" /* MISSION_FEATURES_CHANGED */),
1712
+ features: import_zod7.z.array(MissionFeatureSchema)
1433
1713
  }).passthrough();
1434
- var MissionProgressEntryNotificationSchema = import_zod6.z.object({
1435
- type: import_zod6.z.literal("mission_progress_entry" /* MISSION_PROGRESS_ENTRY */),
1436
- progressLog: import_zod6.z.array(ProgressLogEntrySchema)
1714
+ var MissionProgressEntryNotificationSchema = import_zod7.z.object({
1715
+ type: import_zod7.z.literal("mission_progress_entry" /* MISSION_PROGRESS_ENTRY */),
1716
+ progressLog: import_zod7.z.array(ProgressLogEntrySchema)
1437
1717
  }).passthrough();
1438
- var MissionHeartbeatNotificationSchema = import_zod6.z.object({
1439
- type: import_zod6.z.literal("mission_heartbeat" /* MISSION_HEARTBEAT */),
1440
- timestamp: import_zod6.z.string()
1718
+ var MissionHeartbeatNotificationSchema = import_zod7.z.object({
1719
+ type: import_zod7.z.literal("mission_heartbeat" /* MISSION_HEARTBEAT */),
1720
+ timestamp: import_zod7.z.string()
1441
1721
  }).passthrough();
1442
- var MissionWorkerStartedNotificationSchema = import_zod6.z.object({
1443
- type: import_zod6.z.literal("mission_worker_started" /* MISSION_WORKER_STARTED */),
1444
- workerSessionId: import_zod6.z.string()
1722
+ var MissionWorkerStartedNotificationSchema = import_zod7.z.object({
1723
+ type: import_zod7.z.literal("mission_worker_started" /* MISSION_WORKER_STARTED */),
1724
+ workerSessionId: import_zod7.z.string()
1445
1725
  }).passthrough();
1446
- var MissionWorkerCompletedNotificationSchema = import_zod6.z.object({
1447
- type: import_zod6.z.literal("mission_worker_completed" /* MISSION_WORKER_COMPLETED */),
1448
- workerSessionId: import_zod6.z.string(),
1449
- exitCode: import_zod6.z.number()
1726
+ var MissionWorkerCompletedNotificationSchema = import_zod7.z.object({
1727
+ type: import_zod7.z.literal("mission_worker_completed" /* MISSION_WORKER_COMPLETED */),
1728
+ workerSessionId: import_zod7.z.string(),
1729
+ exitCode: import_zod7.z.number()
1450
1730
  }).passthrough();
1451
- var McpAuthRequiredNotificationSchema = import_zod6.z.object({
1452
- type: import_zod6.z.literal("mcp_auth_required" /* MCP_AUTH_REQUIRED */),
1453
- serverName: import_zod6.z.string(),
1454
- authUrl: import_zod6.z.string(),
1455
- message: import_zod6.z.string(),
1456
- state: import_zod6.z.string()
1731
+ var McpAuthRequiredNotificationSchema = import_zod7.z.object({
1732
+ type: import_zod7.z.literal("mcp_auth_required" /* MCP_AUTH_REQUIRED */),
1733
+ serverName: import_zod7.z.string(),
1734
+ authUrl: import_zod7.z.string(),
1735
+ message: import_zod7.z.string(),
1736
+ state: import_zod7.z.string()
1457
1737
  }).passthrough();
1458
- var McpAuthCompletedNotificationSchema = import_zod6.z.object({
1459
- type: import_zod6.z.literal("mcp_auth_completed" /* MCP_AUTH_COMPLETED */),
1460
- serverName: import_zod6.z.string(),
1461
- outcome: import_zod6.z.nativeEnum(McpAuthOutcome),
1462
- message: import_zod6.z.string()
1738
+ var McpAuthCompletedNotificationSchema = import_zod7.z.object({
1739
+ type: import_zod7.z.literal("mcp_auth_completed" /* MCP_AUTH_COMPLETED */),
1740
+ serverName: import_zod7.z.string(),
1741
+ outcome: import_zod7.z.nativeEnum(McpAuthOutcome),
1742
+ message: import_zod7.z.string()
1463
1743
  }).passthrough();
1464
1744
  var SessionNotificationSchemaList = [
1465
1745
  ToolResultNotificationSchema,
@@ -1483,84 +1763,86 @@ var SessionNotificationSchemaList = [
1483
1763
  McpAuthRequiredNotificationSchema,
1484
1764
  McpAuthCompletedNotificationSchema
1485
1765
  ];
1486
- var SessionNotificationPayloadSchema = import_zod6.z.discriminatedUnion(
1766
+ var SessionNotificationPayloadSchema = import_zod7.z.discriminatedUnion(
1487
1767
  "type",
1488
1768
  SessionNotificationSchemaList
1489
1769
  );
1490
- var SessionNotificationParamsSchema = import_zod6.z.object({
1770
+ var _SessionNotificationParamsSchema = import_zod7.z.object({
1491
1771
  notification: SessionNotificationPayloadSchema
1492
1772
  }).passthrough();
1493
- var SessionNotificationSchema = JsonRpcNotificationSchema.extend({
1494
- method: import_zod6.z.literal("droid.session_notification" /* SESSION_NOTIFICATION */),
1773
+ var SessionNotificationParamsSchema = _SessionNotificationParamsSchema;
1774
+ var _SessionNotificationSchema = JsonRpcNotificationSchema.extend({
1775
+ method: import_zod7.z.literal("droid.session_notification" /* SESSION_NOTIFICATION */),
1495
1776
  params: SessionNotificationParamsSchema
1496
1777
  });
1497
- var EditToolConfirmationDetailsSchema = import_zod6.z.object({
1498
- type: import_zod6.z.literal("edit" /* Edit */),
1499
- filePath: import_zod6.z.string(),
1500
- fileName: import_zod6.z.string(),
1501
- oldContent: import_zod6.z.string().optional(),
1502
- newContent: import_zod6.z.string().optional()
1503
- }).passthrough();
1504
- var ExecuteToolConfirmationDetailsSchema = import_zod6.z.object({
1505
- type: import_zod6.z.literal("exec" /* Execute */),
1506
- fullCommand: import_zod6.z.string(),
1507
- command: import_zod6.z.string(),
1508
- extractedCommands: import_zod6.z.array(import_zod6.z.string()).optional(),
1509
- impactLevel: import_zod6.z.string().optional()
1510
- }).passthrough();
1511
- var CreateToolConfirmationDetailsSchema = import_zod6.z.object({
1512
- type: import_zod6.z.literal("create" /* Create */),
1513
- filePath: import_zod6.z.string(),
1514
- fileName: import_zod6.z.string(),
1515
- content: import_zod6.z.string()
1516
- }).passthrough();
1517
- var AskUserQuestionSchema = import_zod6.z.object({
1518
- index: import_zod6.z.number(),
1519
- topic: import_zod6.z.string(),
1520
- question: import_zod6.z.string(),
1521
- options: import_zod6.z.array(import_zod6.z.string())
1522
- }).passthrough();
1523
- var AskUserConfirmationDetailsSchema = import_zod6.z.object({
1524
- type: import_zod6.z.literal("ask_user" /* AskUser */),
1525
- questionnaire: import_zod6.z.string(),
1526
- parsed: import_zod6.z.object({
1527
- questions: import_zod6.z.array(AskUserQuestionSchema)
1778
+ var SessionNotificationSchema = _SessionNotificationSchema;
1779
+ var EditToolConfirmationDetailsSchema = import_zod7.z.object({
1780
+ type: import_zod7.z.literal("edit" /* Edit */),
1781
+ filePath: import_zod7.z.string(),
1782
+ fileName: import_zod7.z.string(),
1783
+ oldContent: import_zod7.z.string().optional(),
1784
+ newContent: import_zod7.z.string().optional()
1785
+ }).passthrough();
1786
+ var ExecuteToolConfirmationDetailsSchema = import_zod7.z.object({
1787
+ type: import_zod7.z.literal("exec" /* Execute */),
1788
+ fullCommand: import_zod7.z.string(),
1789
+ command: import_zod7.z.string(),
1790
+ extractedCommands: import_zod7.z.array(import_zod7.z.string()).optional(),
1791
+ impactLevel: import_zod7.z.string().optional()
1792
+ }).passthrough();
1793
+ var CreateToolConfirmationDetailsSchema = import_zod7.z.object({
1794
+ type: import_zod7.z.literal("create" /* Create */),
1795
+ filePath: import_zod7.z.string(),
1796
+ fileName: import_zod7.z.string(),
1797
+ content: import_zod7.z.string()
1798
+ }).passthrough();
1799
+ var AskUserQuestionSchema = import_zod7.z.object({
1800
+ index: import_zod7.z.number(),
1801
+ topic: import_zod7.z.string(),
1802
+ question: import_zod7.z.string(),
1803
+ options: import_zod7.z.array(import_zod7.z.string())
1804
+ }).passthrough();
1805
+ var AskUserConfirmationDetailsSchema = import_zod7.z.object({
1806
+ type: import_zod7.z.literal("ask_user" /* AskUser */),
1807
+ questionnaire: import_zod7.z.string(),
1808
+ parsed: import_zod7.z.object({
1809
+ questions: import_zod7.z.array(AskUserQuestionSchema)
1528
1810
  }).optional(),
1529
- parseError: import_zod6.z.object({
1530
- message: import_zod6.z.string(),
1531
- line: import_zod6.z.number().optional()
1811
+ parseError: import_zod7.z.object({
1812
+ message: import_zod7.z.string(),
1813
+ line: import_zod7.z.number().optional()
1532
1814
  }).optional()
1533
1815
  }).passthrough();
1534
- var ExitSpecModeConfirmationDetailsSchema = import_zod6.z.object({
1535
- type: import_zod6.z.literal("exit_spec_mode" /* ExitSpecMode */),
1536
- plan: import_zod6.z.string(),
1537
- title: import_zod6.z.string().optional(),
1538
- optionNames: import_zod6.z.array(import_zod6.z.string()).optional()
1539
- }).passthrough();
1540
- var ProposeMissionConfirmationDetailsSchema = import_zod6.z.object({
1541
- type: import_zod6.z.literal("propose_mission" /* ProposeMission */),
1542
- proposal: import_zod6.z.string(),
1543
- title: import_zod6.z.string().optional()
1544
- }).passthrough();
1545
- var StartMissionRunConfirmationDetailsSchema = import_zod6.z.object({
1546
- type: import_zod6.z.literal("start_mission_run" /* StartMissionRun */),
1547
- runningMissionCount: import_zod6.z.number(),
1548
- runningMissionSessionIds: import_zod6.z.array(import_zod6.z.string())
1549
- }).passthrough();
1550
- var ApplyPatchToolConfirmationDetailsSchema = import_zod6.z.object({
1551
- type: import_zod6.z.literal("apply_patch" /* ApplyPatch */),
1552
- filePath: import_zod6.z.string(),
1553
- fileName: import_zod6.z.string(),
1554
- patchContent: import_zod6.z.string(),
1555
- oldContent: import_zod6.z.string().optional(),
1556
- newContent: import_zod6.z.string().optional()
1557
- }).passthrough();
1558
- var McpToolConfirmationDetailsSchema = import_zod6.z.object({
1559
- type: import_zod6.z.literal("mcp_tool" /* McpTool */),
1560
- toolName: import_zod6.z.string(),
1561
- impactLevel: import_zod6.z.string()
1562
- }).passthrough();
1563
- var ToolConfirmationDetailsSchema = import_zod6.z.discriminatedUnion("type", [
1816
+ var ExitSpecModeConfirmationDetailsSchema = import_zod7.z.object({
1817
+ type: import_zod7.z.literal("exit_spec_mode" /* ExitSpecMode */),
1818
+ plan: import_zod7.z.string(),
1819
+ title: import_zod7.z.string().optional(),
1820
+ optionNames: import_zod7.z.array(import_zod7.z.string()).optional()
1821
+ }).passthrough();
1822
+ var ProposeMissionConfirmationDetailsSchema = import_zod7.z.object({
1823
+ type: import_zod7.z.literal("propose_mission" /* ProposeMission */),
1824
+ proposal: import_zod7.z.string(),
1825
+ title: import_zod7.z.string().optional()
1826
+ }).passthrough();
1827
+ var StartMissionRunConfirmationDetailsSchema = import_zod7.z.object({
1828
+ type: import_zod7.z.literal("start_mission_run" /* StartMissionRun */),
1829
+ runningMissionCount: import_zod7.z.number(),
1830
+ runningMissionSessionIds: import_zod7.z.array(import_zod7.z.string())
1831
+ }).passthrough();
1832
+ var ApplyPatchToolConfirmationDetailsSchema = import_zod7.z.object({
1833
+ type: import_zod7.z.literal("apply_patch" /* ApplyPatch */),
1834
+ filePath: import_zod7.z.string(),
1835
+ fileName: import_zod7.z.string(),
1836
+ patchContent: import_zod7.z.string(),
1837
+ oldContent: import_zod7.z.string().optional(),
1838
+ newContent: import_zod7.z.string().optional()
1839
+ }).passthrough();
1840
+ var McpToolConfirmationDetailsSchema = import_zod7.z.object({
1841
+ type: import_zod7.z.literal("mcp_tool" /* McpTool */),
1842
+ toolName: import_zod7.z.string(),
1843
+ impactLevel: import_zod7.z.string()
1844
+ }).passthrough();
1845
+ var ToolConfirmationDetailsSchema = import_zod7.z.discriminatedUnion("type", [
1564
1846
  EditToolConfirmationDetailsSchema,
1565
1847
  ExecuteToolConfirmationDetailsSchema,
1566
1848
  CreateToolConfirmationDetailsSchema,
@@ -1571,60 +1853,67 @@ var ToolConfirmationDetailsSchema = import_zod6.z.discriminatedUnion("type", [
1571
1853
  ApplyPatchToolConfirmationDetailsSchema,
1572
1854
  McpToolConfirmationDetailsSchema
1573
1855
  ]);
1574
- var ToolConfirmationInfoSchema = import_zod6.z.object({
1856
+ var ToolConfirmationInfoSchema = import_zod7.z.object({
1575
1857
  toolUse: ToolUseSchema,
1576
- confirmationType: import_zod6.z.nativeEnum(ToolConfirmationType),
1858
+ confirmationType: import_zod7.z.nativeEnum(ToolConfirmationType),
1577
1859
  details: ToolConfirmationDetailsSchema
1578
1860
  }).passthrough();
1579
- var RequestPermissionRequestParamsSchema = import_zod6.z.object({
1580
- toolUses: import_zod6.z.array(ToolConfirmationInfoSchema),
1581
- options: import_zod6.z.array(ToolConfirmationListItemSchema)
1861
+ var RequestPermissionRequestParamsSchema = import_zod7.z.object({
1862
+ toolUses: import_zod7.z.array(ToolConfirmationInfoSchema),
1863
+ options: import_zod7.z.array(ToolConfirmationListItemSchema)
1582
1864
  }).passthrough();
1583
1865
  var RequestPermissionRequestSchema = JsonRpcRequestSchema.extend({
1584
- method: import_zod6.z.literal("droid.request_permission" /* REQUEST_PERMISSION */),
1866
+ method: import_zod7.z.literal("droid.request_permission" /* REQUEST_PERMISSION */),
1585
1867
  params: RequestPermissionRequestParamsSchema
1586
1868
  });
1587
- var RequestPermissionResultSchema = import_zod6.z.object({
1588
- selectedOption: import_zod6.z.nativeEnum(ToolConfirmationOutcome)
1869
+ var RequestPermissionResultSchema = import_zod7.z.object({
1870
+ selectedOption: import_zod7.z.nativeEnum(ToolConfirmationOutcome),
1871
+ comment: import_zod7.z.string().optional()
1589
1872
  }).strict();
1590
- var RequestPermissionResponseSchema = import_zod6.z.union([
1873
+ var RequestPermissionResponseSchema = import_zod7.z.union([
1591
1874
  JsonRpcResponseSuccessSchema.extend({
1592
1875
  result: RequestPermissionResultSchema
1593
1876
  }),
1594
1877
  JsonRpcResponseFailureSchema
1595
1878
  ]);
1596
- var AskUserRequestParamsSchema = import_zod6.z.object({
1597
- toolCallId: import_zod6.z.string(),
1598
- questions: import_zod6.z.array(AskUserQuestionSchema)
1879
+ var AskUserRequestParamsSchema = import_zod7.z.object({
1880
+ toolCallId: import_zod7.z.string(),
1881
+ questions: import_zod7.z.array(AskUserQuestionSchema)
1599
1882
  }).passthrough();
1600
1883
  var AskUserRequestSchema = JsonRpcRequestSchema.extend({
1601
- method: import_zod6.z.literal("droid.ask_user" /* ASK_USER */),
1884
+ method: import_zod7.z.literal("droid.ask_user" /* ASK_USER */),
1602
1885
  params: AskUserRequestParamsSchema
1603
1886
  });
1604
- var AskUserCollectedAnswerSchema = import_zod6.z.object({
1605
- index: import_zod6.z.number(),
1606
- question: import_zod6.z.string(),
1607
- answer: import_zod6.z.string()
1887
+ var AskUserCollectedAnswerSchema = import_zod7.z.object({
1888
+ index: import_zod7.z.number(),
1889
+ question: import_zod7.z.string(),
1890
+ answer: import_zod7.z.string()
1608
1891
  }).strict();
1609
- var AskUserResultSchema = import_zod6.z.object({
1610
- cancelled: import_zod6.z.boolean().optional(),
1611
- answers: import_zod6.z.array(AskUserCollectedAnswerSchema)
1892
+ var AskUserResultSchema = import_zod7.z.object({
1893
+ cancelled: import_zod7.z.boolean().optional(),
1894
+ answers: import_zod7.z.array(AskUserCollectedAnswerSchema)
1612
1895
  }).strict();
1613
- var AskUserResponseSchema = import_zod6.z.union([
1896
+ var AskUserResponseSchema = import_zod7.z.union([
1614
1897
  JsonRpcResponseSuccessSchema.extend({ result: AskUserResultSchema }),
1615
1898
  JsonRpcResponseFailureSchema
1616
1899
  ]);
1617
- var CliRequestOrNotificationSchema = import_zod6.z.union([
1900
+ var _CliRequestOrNotificationSchema = import_zod7.z.union([
1618
1901
  SessionNotificationSchema,
1619
1902
  RequestPermissionRequestSchema,
1620
1903
  AskUserRequestSchema
1621
1904
  ]);
1905
+ var CliRequestOrNotificationSchema = _CliRequestOrNotificationSchema;
1906
+
1907
+ // src/constants.ts
1908
+ var SDK_VERSION = "0.2.0";
1909
+ var SDK_TAG = {
1910
+ name: "sdk",
1911
+ metadata: { language: "typescript", version: SDK_VERSION }
1912
+ };
1622
1913
 
1623
1914
  // src/errors.ts
1624
1915
  var ConnectionError = class _ConnectionError extends Error {
1625
- /** The working directory used when spawning the process. */
1626
1916
  cwd;
1627
- /** The executable path used when spawning the process. */
1628
1917
  execPath;
1629
1918
  constructor(message, options) {
1630
1919
  super(message);
@@ -1635,9 +1924,7 @@ var ConnectionError = class _ConnectionError extends Error {
1635
1924
  }
1636
1925
  };
1637
1926
  var ProtocolError = class _ProtocolError extends Error {
1638
- /** The JSON-RPC error code, if available. */
1639
1927
  code;
1640
- /** Additional error data from the JSON-RPC response. */
1641
1928
  data;
1642
1929
  constructor(message, options) {
1643
1930
  super(message);
@@ -1655,7 +1942,6 @@ var SessionError = class _SessionError extends Error {
1655
1942
  }
1656
1943
  };
1657
1944
  var SessionNotFoundError = class _SessionNotFoundError extends SessionError {
1658
- /** The ID of the session that was not found. */
1659
1945
  sessionId;
1660
1946
  constructor(sessionId) {
1661
1947
  super(`Session not found: ${sessionId}`);
@@ -1672,9 +1958,7 @@ var TimeoutError = class _TimeoutError extends Error {
1672
1958
  }
1673
1959
  };
1674
1960
  var ProcessExitError = class _ProcessExitError extends Error {
1675
- /** The exit code of the process, or null if terminated by signal. */
1676
1961
  exitCode;
1677
- /** The signal that terminated the process, or null if exited normally. */
1678
1962
  signal;
1679
1963
  constructor(message, options) {
1680
1964
  super(message);
@@ -1688,6 +1972,13 @@ var ProcessExitError = class _ProcessExitError extends Error {
1688
1972
  // src/transport.ts
1689
1973
  var import_node_child_process = require("child_process");
1690
1974
  var readline = __toESM(require("readline"), 1);
1975
+
1976
+ // src/utils.ts
1977
+ function isRecord(value) {
1978
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1979
+ }
1980
+
1981
+ // src/transport.ts
1691
1982
  var DEFAULT_EXEC_ARGS = [
1692
1983
  "exec",
1693
1984
  "--input-format",
@@ -1706,12 +1997,9 @@ var ProcessTransport = class {
1706
1997
  readlineInterface = null;
1707
1998
  messageHandler = null;
1708
1999
  errorHandler = null;
1709
- /**
1710
- * Sticky error from a process error or unexpected exit. Once set,
1711
- * all subsequent `send()` calls throw immediately.
1712
- */
2000
+ /** Once set, all subsequent `send()` calls throw immediately. */
1713
2001
  processError = null;
1714
- /** Promise-chain serializer for stdin writes. */
2002
+ /** Serializes stdin writes to prevent interleaving. */
1715
2003
  writeChain = Promise.resolve();
1716
2004
  _isConnected = false;
1717
2005
  isClosing = false;
@@ -1722,9 +2010,6 @@ var ProcessTransport = class {
1722
2010
  this.env = options.env;
1723
2011
  this.gracePeriodMs = (options.gracePeriod ?? DEFAULT_GRACE_PERIOD_MS / 1e3) * 1e3;
1724
2012
  }
1725
- // -----------------------------------------------------------------------
1726
- // DroidClientTransport interface
1727
- // -----------------------------------------------------------------------
1728
2013
  get isConnected() {
1729
2014
  return this._isConnected;
1730
2015
  }
@@ -1776,7 +2061,7 @@ var ProcessTransport = class {
1776
2061
  if (this.processError) {
1777
2062
  throw this.processError;
1778
2063
  }
1779
- await new Promise((resolve, reject) => {
2064
+ await new Promise((resolve2, reject) => {
1780
2065
  if (!this.childProcess || !this.childProcess.stdin) {
1781
2066
  reject(
1782
2067
  new ConnectionError("Process stdin unavailable", {
@@ -1812,7 +2097,7 @@ var ProcessTransport = class {
1812
2097
  );
1813
2098
  }
1814
2099
  } else {
1815
- resolve();
2100
+ resolve2();
1816
2101
  }
1817
2102
  });
1818
2103
  });
@@ -1837,7 +2122,7 @@ var ProcessTransport = class {
1837
2122
  this.readlineInterface = null;
1838
2123
  }
1839
2124
  if (proc && proc.exitCode === null && !proc.killed) {
1840
- await new Promise((resolve) => {
2125
+ await new Promise((resolve2) => {
1841
2126
  const timeout = setTimeout(() => {
1842
2127
  if (proc.exitCode === null && !proc.killed) {
1843
2128
  try {
@@ -1848,7 +2133,7 @@ var ProcessTransport = class {
1848
2133
  }, this.gracePeriodMs);
1849
2134
  proc.once("exit", () => {
1850
2135
  clearTimeout(timeout);
1851
- resolve();
2136
+ resolve2();
1852
2137
  });
1853
2138
  if (proc.stdin) {
1854
2139
  try {
@@ -1860,15 +2145,12 @@ var ProcessTransport = class {
1860
2145
  proc.kill("SIGTERM");
1861
2146
  } catch {
1862
2147
  clearTimeout(timeout);
1863
- resolve();
2148
+ resolve2();
1864
2149
  }
1865
2150
  });
1866
2151
  }
1867
2152
  this.isClosing = false;
1868
2153
  }
1869
- // -----------------------------------------------------------------------
1870
- // Private helpers
1871
- // -----------------------------------------------------------------------
1872
2154
  setupHandlers() {
1873
2155
  const proc = this.childProcess;
1874
2156
  if (!proc || !proc.stdout) {
@@ -1883,10 +2165,10 @@ var ProcessTransport = class {
1883
2165
  if (!trimmed) {
1884
2166
  return;
1885
2167
  }
1886
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2168
+ if (trimmed.startsWith("{")) {
1887
2169
  try {
1888
2170
  const parsed = JSON.parse(trimmed);
1889
- if (this.messageHandler && typeof parsed === "object" && parsed !== null) {
2171
+ if (this.messageHandler && isRecord(parsed)) {
1890
2172
  this.messageHandler(parsed);
1891
2173
  }
1892
2174
  } catch {
@@ -1942,23 +2224,12 @@ var import_uuid = require("uuid");
1942
2224
  var ProtocolEngine = class {
1943
2225
  _transport;
1944
2226
  _defaultTimeout;
1945
- /** Pending requests keyed by UUID string. */
1946
2227
  _pendingRequests = /* @__PURE__ */ new Map();
1947
- /** Notification listener registry. */
1948
2228
  _notificationListeners = /* @__PURE__ */ new Set();
1949
- /** Server→client request handlers. */
1950
2229
  _permissionHandler = null;
1951
2230
  _askUserHandler = null;
1952
- /** Sticky transport error — once set, all requests fail immediately. */
1953
2231
  _transportError = null;
1954
- /** Closed flag — once true, new requests are rejected. */
1955
2232
  _closed = false;
1956
- /**
1957
- * Create a new ProtocolEngine.
1958
- *
1959
- * @param options.transport - A connected DroidClientTransport implementation.
1960
- * @param options.defaultTimeout - Default timeout in ms for sendRequest (default 30 000).
1961
- */
1962
2233
  constructor(options) {
1963
2234
  this._transport = options.transport;
1964
2235
  this._defaultTimeout = options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT;
@@ -1969,25 +2240,6 @@ var ProtocolEngine = class {
1969
2240
  this._handleTransportError(error);
1970
2241
  });
1971
2242
  }
1972
- // ------------------------------------------------------------------
1973
- // Public API: Sending requests
1974
- // ------------------------------------------------------------------
1975
- /**
1976
- * Send a JSON-RPC request and wait for the response.
1977
- *
1978
- * Constructs the full envelope, registers a pending promise, sends
1979
- * via transport, and returns the parsed response `result` field.
1980
- *
1981
- * @param method - The RPC method name (e.g. `"droid.list_skills"`).
1982
- * @param params - Method parameters object.
1983
- * @param timeout - Timeout in ms. Defaults to `defaultTimeout`.
1984
- * @returns The `result` field from the JSON-RPC success response.
1985
- * @throws {ConnectionError} If the engine is closed.
1986
- * @throws {ConnectionError} If the transport has a sticky error.
1987
- * @throws {TimeoutError} If no response arrives within the timeout.
1988
- * @throws {ProtocolError} If the response contains a protocol error.
1989
- * @throws {SessionNotFoundError} If error code is ENTITY_NOT_FOUND.
1990
- */
1991
2243
  async sendRequest(method, params, timeout) {
1992
2244
  if (this._closed) {
1993
2245
  throw new ConnectionError("Protocol engine is closed");
@@ -2003,12 +2255,12 @@ var ProtocolEngine = class {
2003
2255
  jsonrpc: JSONRPC_VERSION,
2004
2256
  factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2005
2257
  factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2006
- type: "request",
2258
+ type: "request" /* Request */,
2007
2259
  id: requestId,
2008
2260
  method,
2009
2261
  params
2010
2262
  };
2011
- return new Promise((resolve, reject) => {
2263
+ return new Promise((resolve2, reject) => {
2012
2264
  const timer = setTimeout(() => {
2013
2265
  this._pendingRequests.delete(requestId);
2014
2266
  reject(
@@ -2021,7 +2273,7 @@ var ProtocolEngine = class {
2021
2273
  method,
2022
2274
  requestId,
2023
2275
  params,
2024
- resolve,
2276
+ resolve: resolve2,
2025
2277
  reject,
2026
2278
  timer
2027
2279
  };
@@ -2041,19 +2293,6 @@ var ProtocolEngine = class {
2041
2293
  }
2042
2294
  });
2043
2295
  }
2044
- // ------------------------------------------------------------------
2045
- // Public API: Notification listeners
2046
- // ------------------------------------------------------------------
2047
- /**
2048
- * Register a callback for incoming notification messages.
2049
- *
2050
- * Multiple listeners can be registered. Each receives the full
2051
- * parsed notification object.
2052
- *
2053
- * @param callback - Invoked with the notification object.
2054
- * @param filter - Optional filter to only receive specific notification types.
2055
- * @returns An unsubscribe function. Calling it again is safe (no-op).
2056
- */
2057
2296
  onNotification(callback, filter) {
2058
2297
  const listener = { callback, filter };
2059
2298
  this._notificationListeners.add(listener);
@@ -2065,23 +2304,9 @@ var ProtocolEngine = class {
2065
2304
  }
2066
2305
  };
2067
2306
  }
2068
- // ------------------------------------------------------------------
2069
- // Public API: Server→client request handlers
2070
- // ------------------------------------------------------------------
2071
- /**
2072
- * Register a handler for server→client permission requests.
2073
- *
2074
- * The handler receives the request params and should return a
2075
- * ToolConfirmationOutcome string value.
2076
- *
2077
- * Replaces any previously registered handler.
2078
- */
2079
2307
  setPermissionHandler(handler) {
2080
2308
  this._permissionHandler = handler;
2081
2309
  }
2082
- /**
2083
- * Remove the permission request handler (restores default Cancel).
2084
- */
2085
2310
  clearPermissionHandler() {
2086
2311
  this._permissionHandler = null;
2087
2312
  }
@@ -2096,31 +2321,12 @@ var ProtocolEngine = class {
2096
2321
  setAskUserHandler(handler) {
2097
2322
  this._askUserHandler = handler;
2098
2323
  }
2099
- /**
2100
- * Remove the ask-user request handler (restores default cancelled=true).
2101
- */
2102
2324
  clearAskUserHandler() {
2103
2325
  this._askUserHandler = null;
2104
2326
  }
2105
- // ------------------------------------------------------------------
2106
- // Public API: Health check
2107
- // ------------------------------------------------------------------
2108
- /**
2109
- * Whether the engine is in a healthy state — not closed and no
2110
- * sticky transport error.
2111
- */
2112
2327
  get isHealthy() {
2113
2328
  return !this._closed && this._transportError === null;
2114
2329
  }
2115
- // ------------------------------------------------------------------
2116
- // Public API: Close
2117
- // ------------------------------------------------------------------
2118
- /**
2119
- * Close the protocol engine.
2120
- *
2121
- * Rejects all pending requests, closes the transport, and prevents
2122
- * new requests. Idempotent — safe to call multiple times.
2123
- */
2124
2330
  async close() {
2125
2331
  if (this._closed) {
2126
2332
  return;
@@ -2135,38 +2341,25 @@ var ProtocolEngine = class {
2135
2341
  this._notificationListeners.clear();
2136
2342
  await this._transport.close();
2137
2343
  }
2138
- // ------------------------------------------------------------------
2139
- // Internal: Message handling
2140
- // ------------------------------------------------------------------
2141
- /**
2142
- * Handle an incoming parsed message from the transport.
2143
- * Dispatches to response handler, notification handler, or
2144
- * server→client request handler based on message type.
2145
- */
2146
- _handleMessage(parsed) {
2147
- const msgType = parsed["type"];
2148
- if (msgType === "response") {
2149
- this._handleResponse(parsed);
2150
- } else if (msgType === "notification") {
2151
- this._handleNotification(parsed);
2152
- } else if (msgType === "request") {
2153
- void this._handleServerRequest(parsed);
2154
- } else {
2155
- if ("result" in parsed || "error" in parsed) {
2156
- this._handleResponse(parsed);
2157
- } else if ("method" in parsed && !("id" in parsed)) {
2158
- this._handleNotification(parsed);
2159
- } else if ("method" in parsed && "id" in parsed) {
2160
- void this._handleServerRequest(parsed);
2161
- }
2344
+ _handleMessage(raw) {
2345
+ const parsed = JsonRpcMessageSchema.safeParse(raw);
2346
+ if (!parsed.success) {
2347
+ return;
2348
+ }
2349
+ const msg = parsed.data;
2350
+ switch (msg.type) {
2351
+ case "response" /* Response */:
2352
+ this._handleResponse(msg.id, msg.result, msg.error);
2353
+ break;
2354
+ case "notification" /* Notification */:
2355
+ this._handleNotification(msg);
2356
+ break;
2357
+ case "request" /* Request */:
2358
+ void this._handleServerRequest(msg.method, msg.id, msg.params);
2359
+ break;
2162
2360
  }
2163
2361
  }
2164
- /**
2165
- * Handle an incoming response message.
2166
- * Matches by ID to resolve the correct pending Promise.
2167
- */
2168
- _handleResponse(response) {
2169
- const responseId = response["id"];
2362
+ _handleResponse(responseId, result, error) {
2170
2363
  if (responseId == null) {
2171
2364
  return;
2172
2365
  }
@@ -2176,32 +2369,29 @@ var ProtocolEngine = class {
2176
2369
  }
2177
2370
  this._pendingRequests.delete(responseId);
2178
2371
  clearTimeout(pending.timer);
2179
- const errorObj = response["error"];
2180
- if (errorObj != null && typeof errorObj === "object") {
2181
- const error = errorObj;
2182
- const code = error["code"];
2183
- const message = error["message"] ?? "Unknown error";
2184
- const data = error["data"];
2185
- if (code === -32004 /* ENTITY_NOT_FOUND */) {
2372
+ if (error != null) {
2373
+ if (error.code === -32004 /* ENTITY_NOT_FOUND */) {
2186
2374
  const sessionId = String(
2187
2375
  pending.params["sessionId"] ?? pending.requestId
2188
2376
  );
2189
2377
  pending.reject(new SessionNotFoundError(sessionId));
2190
2378
  return;
2191
2379
  }
2192
- pending.reject(new ProtocolError(message, { code, data }));
2380
+ pending.reject(
2381
+ new ProtocolError(error.message, { code: error.code, data: error.data })
2382
+ );
2193
2383
  return;
2194
2384
  }
2195
- pending.resolve(response);
2385
+ pending.resolve(result);
2196
2386
  }
2197
- /**
2198
- * Handle an incoming notification message.
2199
- * Dispatches to all registered notification listeners that match.
2200
- */
2201
2387
  _handleNotification(notification) {
2202
- const params = notification["params"];
2203
- const innerNotification = params?.["notification"];
2204
- const notificationType = innerNotification?.["type"];
2388
+ let notificationType;
2389
+ const parsed = SessionNotificationParamsSchema.safeParse(
2390
+ notification["params"]
2391
+ );
2392
+ if (parsed.success) {
2393
+ notificationType = parsed.data.notification.type;
2394
+ }
2205
2395
  for (const listener of this._notificationListeners) {
2206
2396
  if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2207
2397
  continue;
@@ -2212,32 +2402,32 @@ var ProtocolEngine = class {
2212
2402
  }
2213
2403
  }
2214
2404
  }
2215
- /**
2216
- * Handle an incoming server→client request.
2217
- * Dispatches to the appropriate handler based on the method field.
2218
- */
2219
- async _handleServerRequest(request) {
2220
- const method = request["method"];
2221
- const requestId = request["id"];
2222
- const params = request["params"] ?? {};
2405
+ async _handleServerRequest(method, requestId, params) {
2223
2406
  if (method === "droid.request_permission" /* REQUEST_PERMISSION */) {
2224
2407
  await this._handlePermissionRequest(requestId, params);
2225
2408
  } else if (method === "droid.ask_user" /* ASK_USER */) {
2226
2409
  await this._handleAskUserRequest(requestId, params);
2227
2410
  }
2228
2411
  }
2229
- /**
2230
- * Handle droid.request_permission server→client request.
2231
- */
2232
2412
  async _handlePermissionRequest(requestId, params) {
2233
2413
  const handler = this._permissionHandler;
2234
2414
  if (handler == null) {
2235
- this._sendResponse(requestId, { selectedOption: "cancel" });
2415
+ this._sendResponse(
2416
+ requestId,
2417
+ RequestPermissionResultSchema.parse({
2418
+ selectedOption: "cancel" /* Cancel */
2419
+ })
2420
+ );
2236
2421
  return;
2237
2422
  }
2238
2423
  try {
2239
- const selectedOption = await Promise.resolve(handler(params));
2240
- this._sendResponse(requestId, { selectedOption });
2424
+ const parsedParams = RequestPermissionRequestParamsSchema.parse(params);
2425
+ const selection = await Promise.resolve(handler(parsedParams));
2426
+ const result = typeof selection === "string" ? { selectedOption: selection } : selection;
2427
+ this._sendResponse(
2428
+ requestId,
2429
+ RequestPermissionResultSchema.parse(result)
2430
+ );
2241
2431
  } catch (exc) {
2242
2432
  const errorMessage = exc instanceof Error ? exc.message : String(exc);
2243
2433
  this._sendErrorResponse(
@@ -2248,18 +2438,19 @@ var ProtocolEngine = class {
2248
2438
  );
2249
2439
  }
2250
2440
  }
2251
- /**
2252
- * Handle droid.ask_user server→client request.
2253
- */
2254
2441
  async _handleAskUserRequest(requestId, params) {
2255
2442
  const handler = this._askUserHandler;
2256
2443
  if (handler == null) {
2257
- this._sendResponse(requestId, { cancelled: true, answers: [] });
2444
+ this._sendResponse(
2445
+ requestId,
2446
+ AskUserResultSchema.parse({ cancelled: true, answers: [] })
2447
+ );
2258
2448
  return;
2259
2449
  }
2260
2450
  try {
2261
- const result = await Promise.resolve(handler(params));
2262
- this._sendResponse(requestId, result);
2451
+ const parsedParams = AskUserRequestParamsSchema.parse(params);
2452
+ const result = await Promise.resolve(handler(parsedParams));
2453
+ this._sendResponse(requestId, AskUserResultSchema.parse(result));
2263
2454
  } catch (exc) {
2264
2455
  const errorMessage = exc instanceof Error ? exc.message : String(exc);
2265
2456
  this._sendErrorResponse(
@@ -2270,9 +2461,6 @@ var ProtocolEngine = class {
2270
2461
  );
2271
2462
  }
2272
2463
  }
2273
- // ------------------------------------------------------------------
2274
- // Internal: Transport error handling
2275
- // ------------------------------------------------------------------
2276
2464
  /**
2277
2465
  * Handle a transport error.
2278
2466
  * Sets the sticky transport error and rejects all pending requests.
@@ -2286,29 +2474,17 @@ var ProtocolEngine = class {
2286
2474
  connectionError.cause = error;
2287
2475
  this._rejectAllPending(connectionError);
2288
2476
  }
2289
- // ------------------------------------------------------------------
2290
- // Internal: Response helpers
2291
- // ------------------------------------------------------------------
2292
- /**
2293
- * Send a JSON-RPC success response back to the server.
2294
- */
2295
2477
  _sendResponse(requestId, result) {
2296
2478
  const response = {
2297
2479
  jsonrpc: JSONRPC_VERSION,
2298
2480
  factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2299
2481
  factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2300
- type: "response",
2482
+ type: "response" /* Response */,
2301
2483
  id: requestId,
2302
2484
  result
2303
2485
  };
2304
- try {
2305
- this._transport.send(response);
2306
- } catch {
2307
- }
2486
+ this._sendBestEffort(response);
2308
2487
  }
2309
- /**
2310
- * Send a JSON-RPC error response back to the server.
2311
- */
2312
2488
  _sendErrorResponse(requestId, code, message, data) {
2313
2489
  const errorObj = { code, message };
2314
2490
  if (data !== void 0) {
@@ -2318,18 +2494,18 @@ var ProtocolEngine = class {
2318
2494
  jsonrpc: JSONRPC_VERSION,
2319
2495
  factoryApiVersion: LEGACY_FACTORY_API_VERSION,
2320
2496
  factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
2321
- type: "response",
2497
+ type: "response" /* Response */,
2322
2498
  id: requestId,
2323
2499
  error: errorObj
2324
2500
  };
2501
+ this._sendBestEffort(response);
2502
+ }
2503
+ _sendBestEffort(message) {
2325
2504
  try {
2326
- this._transport.send(response);
2505
+ this._transport.send(message);
2327
2506
  } catch {
2328
2507
  }
2329
2508
  }
2330
- /**
2331
- * Reject all pending requests with the given error.
2332
- */
2333
2509
  _rejectAllPending(error) {
2334
2510
  const pending = new Map(this._pendingRequests);
2335
2511
  this._pendingRequests.clear();
@@ -2347,7 +2523,7 @@ var DroidClient = class {
2347
2523
  _closed = false;
2348
2524
  /**
2349
2525
  * Client-level notification listeners.
2350
- * Each entry is [callback, optional type filter string].
2526
+ * Each entry is [callback, optional notification filter].
2351
2527
  */
2352
2528
  _notificationListeners = [];
2353
2529
  /** Client-level permission handler. */
@@ -2369,329 +2545,212 @@ var DroidClient = class {
2369
2545
  (params) => this._dispatchAskUserRequest(params)
2370
2546
  );
2371
2547
  }
2372
- // ------------------------------------------------------------------
2373
- // Properties
2374
- // ------------------------------------------------------------------
2375
- /**
2376
- * Current session ID, or `null` if no session is active.
2377
- */
2548
+ async _rpc(method, params, schema, timeout) {
2549
+ const raw = await this._engine.sendRequest(method, params, timeout);
2550
+ return schema.parse(raw);
2551
+ }
2552
+ async _sessionRpc(method, params, schema, timeout) {
2553
+ this._ensureNotClosed();
2554
+ this._ensureSession();
2555
+ return this._rpc(method, params, schema, timeout);
2556
+ }
2557
+ async _sessionRpcWithoutParams(method, schema, timeout) {
2558
+ return this._sessionRpc(method, {}, schema, timeout);
2559
+ }
2378
2560
  get sessionId() {
2379
2561
  return this._sessionId;
2380
2562
  }
2381
- /**
2382
- * Whether the client is in a healthy state — not closed and no
2383
- * transport errors have occurred. Returns false after transport
2384
- * disconnect/error.
2385
- */
2386
2563
  get isConnected() {
2387
2564
  return !this._closed && this._engine.isHealthy;
2388
2565
  }
2389
- // ------------------------------------------------------------------
2390
- // Session lifecycle methods
2391
- // ------------------------------------------------------------------
2392
- /**
2393
- * Initialize a new session.
2394
- *
2395
- * Sends `droid.initialize_session` with extended timeout. On success,
2396
- * stores the session ID internally and returns the typed result.
2397
- */
2398
2566
  async initializeSession(params) {
2399
2567
  this._ensureNotClosed();
2400
- const response = await this._engine.sendRequest(
2568
+ const result = await this._rpc(
2401
2569
  "droid.initialize_session" /* INITIALIZE_SESSION */,
2402
2570
  params,
2571
+ InitializeSessionResultSchema,
2403
2572
  SESSION_INIT_TIMEOUT
2404
2573
  );
2405
- const result = response["result"];
2406
- if (result) {
2407
- this._sessionId = result.sessionId;
2408
- return result;
2409
- }
2410
- if ("sessionId" in response) {
2411
- this._sessionId = response["sessionId"];
2412
- return response;
2413
- }
2414
- return response;
2574
+ this._sessionId = result.sessionId;
2575
+ return result;
2415
2576
  }
2416
- /**
2417
- * Load an existing session.
2418
- *
2419
- * Sends `droid.load_session`. SessionNotFoundError is thrown for
2420
- * non-existent sessions (mapped from ENTITY_NOT_FOUND by the protocol engine).
2421
- */
2422
2577
  async loadSession(params) {
2423
2578
  this._ensureNotClosed();
2424
- const response = await this._engine.sendRequest(
2579
+ const result = await this._rpc(
2425
2580
  "droid.load_session" /* LOAD_SESSION */,
2426
2581
  params,
2582
+ LoadSessionResultSchema,
2427
2583
  SESSION_INIT_TIMEOUT
2428
2584
  );
2429
- const result = response["result"];
2430
- if (result) {
2431
- this._sessionId = params.sessionId;
2432
- return result;
2433
- }
2434
2585
  this._sessionId = params.sessionId;
2435
- return response;
2586
+ return result;
2436
2587
  }
2437
- /**
2438
- * Add a user message to the active session.
2439
- *
2440
- * Sends `droid.add_user_message` with text and optional images/files.
2441
- */
2442
2588
  async addUserMessage(params) {
2443
- this._ensureNotClosed();
2444
- this._ensureSession();
2445
- const response = await this._engine.sendRequest(
2589
+ return this._sessionRpc(
2446
2590
  "droid.add_user_message" /* ADD_USER_MESSAGE */,
2447
- params
2591
+ params,
2592
+ AddUserMessageResultSchema
2448
2593
  );
2449
- const result = response["result"];
2450
- return result ?? response;
2451
2594
  }
2452
- /**
2453
- * Interrupt the current session.
2454
- *
2455
- * Sends `droid.interrupt_session` with empty params.
2456
- */
2457
2595
  async interruptSession() {
2458
- this._ensureNotClosed();
2459
- this._ensureSession();
2460
- const response = await this._engine.sendRequest(
2596
+ return this._sessionRpcWithoutParams(
2461
2597
  "droid.interrupt_session" /* INTERRUPT_SESSION */,
2462
- {}
2598
+ InterruptSessionResultSchema
2463
2599
  );
2464
- const result = response["result"];
2465
- return result ?? response;
2466
2600
  }
2467
- /**
2468
- * Kill a worker session.
2469
- *
2470
- * Sends `droid.kill_worker_session`.
2471
- */
2472
2601
  async killWorkerSession(params) {
2473
- this._ensureNotClosed();
2474
- this._ensureSession();
2475
- const response = await this._engine.sendRequest(
2602
+ return this._sessionRpc(
2476
2603
  "droid.kill_worker_session" /* KILL_WORKER_SESSION */,
2477
- params
2604
+ params,
2605
+ KillWorkerSessionResultSchema
2478
2606
  );
2479
- const result = response["result"];
2480
- return result ?? response;
2481
2607
  }
2482
- /**
2483
- * Update session settings.
2484
- *
2485
- * Sends `droid.update_session_settings` with the provided partial settings.
2486
- */
2487
2608
  async updateSessionSettings(params) {
2488
- this._ensureNotClosed();
2489
- this._ensureSession();
2490
- const response = await this._engine.sendRequest(
2609
+ return this._sessionRpc(
2491
2610
  "droid.update_session_settings" /* UPDATE_SESSION_SETTINGS */,
2492
- params
2611
+ params,
2612
+ UpdateSessionSettingsResultSchema
2493
2613
  );
2494
- const result = response["result"];
2495
- return result ?? response;
2496
2614
  }
2497
- // ------------------------------------------------------------------
2498
- // MCP methods
2499
- // ------------------------------------------------------------------
2500
- /**
2501
- * Toggle an MCP server on or off.
2502
- */
2503
2615
  async toggleMcpServer(params) {
2504
- this._ensureNotClosed();
2505
- this._ensureSession();
2506
- const response = await this._engine.sendRequest(
2616
+ return this._sessionRpc(
2507
2617
  "droid.toggle_mcp_server" /* TOGGLE_MCP_SERVER */,
2508
- params
2618
+ params,
2619
+ ToggleMcpServerResultSchema
2509
2620
  );
2510
- const result = response["result"];
2511
- return result ?? response;
2512
2621
  }
2513
- /**
2514
- * Authenticate an MCP server (OAuth flow).
2515
- * Uses extended timeout (300s) since OAuth requires user interaction.
2516
- */
2517
2622
  async authenticateMcpServer(params) {
2518
- this._ensureNotClosed();
2519
- this._ensureSession();
2520
- const response = await this._engine.sendRequest(
2623
+ return this._sessionRpc(
2521
2624
  "droid.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */,
2522
2625
  params,
2626
+ AuthenticateMcpServerResultSchema,
2523
2627
  MCP_AUTH_TIMEOUT
2524
2628
  );
2525
- const result = response["result"];
2526
- return result ?? response;
2527
2629
  }
2528
- /**
2529
- * Cancel an in-progress MCP authentication.
2530
- */
2531
2630
  async cancelMcpAuth(params) {
2532
- this._ensureNotClosed();
2533
- this._ensureSession();
2534
- const response = await this._engine.sendRequest(
2631
+ return this._sessionRpc(
2535
2632
  "droid.cancel_mcp_auth" /* CANCEL_MCP_AUTH */,
2536
- params
2633
+ params,
2634
+ CancelMcpAuthResultSchema
2537
2635
  );
2538
- const result = response["result"];
2539
- return result ?? response;
2540
2636
  }
2541
- /**
2542
- * Clear stored MCP authentication tokens.
2543
- */
2544
2637
  async clearMcpAuth(params) {
2545
- this._ensureNotClosed();
2546
- this._ensureSession();
2547
- const response = await this._engine.sendRequest(
2638
+ return this._sessionRpc(
2548
2639
  "droid.clear_mcp_auth" /* CLEAR_MCP_AUTH */,
2549
- params
2640
+ params,
2641
+ ClearMcpAuthResultSchema
2550
2642
  );
2551
- const result = response["result"];
2552
- return result ?? response;
2553
2643
  }
2554
- /**
2555
- * Submit an MCP authentication code (OAuth callback).
2556
- */
2557
2644
  async submitMcpAuthCode(params) {
2558
- this._ensureNotClosed();
2559
- this._ensureSession();
2560
- const response = await this._engine.sendRequest(
2645
+ return this._sessionRpc(
2561
2646
  "droid.submit_mcp_auth_code" /* SUBMIT_MCP_AUTH_CODE */,
2562
- params
2647
+ params,
2648
+ SubmitMcpAuthCodeResultSchema
2563
2649
  );
2564
- const result = response["result"];
2565
- return result ?? response;
2566
2650
  }
2567
- /**
2568
- * Add an MCP server.
2569
- */
2570
2651
  async addMcpServer(params) {
2571
- this._ensureNotClosed();
2572
- this._ensureSession();
2573
- const response = await this._engine.sendRequest(
2652
+ return this._sessionRpc(
2574
2653
  "droid.add_mcp_server" /* ADD_MCP_SERVER */,
2575
- params
2654
+ params,
2655
+ AddMcpServerResultSchema
2576
2656
  );
2577
- const result = response["result"];
2578
- return result ?? response;
2579
2657
  }
2580
- /**
2581
- * Remove an MCP server.
2582
- */
2583
2658
  async removeMcpServer(params) {
2584
- this._ensureNotClosed();
2585
- this._ensureSession();
2586
- const response = await this._engine.sendRequest(
2659
+ return this._sessionRpc(
2587
2660
  "droid.remove_mcp_server" /* REMOVE_MCP_SERVER */,
2588
- params
2661
+ params,
2662
+ RemoveMcpServerResultSchema
2589
2663
  );
2590
- const result = response["result"];
2591
- return result ?? response;
2592
2664
  }
2593
- /**
2594
- * List available MCP registry servers.
2595
- */
2596
2665
  async listMcpRegistry() {
2597
- this._ensureNotClosed();
2598
- this._ensureSession();
2599
- const response = await this._engine.sendRequest(
2666
+ return this._sessionRpcWithoutParams(
2600
2667
  "droid.list_mcp_registry" /* LIST_MCP_REGISTRY */,
2601
- {}
2668
+ ListMcpRegistryResultSchema
2602
2669
  );
2603
- const result = response["result"];
2604
- return result ?? response;
2605
2670
  }
2606
- /**
2607
- * List available MCP tools.
2608
- */
2609
2671
  async listMcpTools() {
2610
- this._ensureNotClosed();
2611
- this._ensureSession();
2612
- const response = await this._engine.sendRequest(
2672
+ return this._sessionRpcWithoutParams(
2613
2673
  "droid.list_mcp_tools" /* LIST_MCP_TOOLS */,
2614
- {}
2674
+ ListMcpToolsResultSchema
2675
+ );
2676
+ }
2677
+ async listTools(params = {}) {
2678
+ return this._sessionRpc(
2679
+ "droid.list_tools" /* LIST_TOOLS */,
2680
+ params,
2681
+ ListToolsResultSchema
2615
2682
  );
2616
- const result = response["result"];
2617
- return result ?? response;
2618
2683
  }
2619
- /**
2620
- * List MCP servers with status and summary.
2621
- */
2622
2684
  async listMcpServers() {
2623
- this._ensureNotClosed();
2624
- this._ensureSession();
2625
- const response = await this._engine.sendRequest(
2685
+ return this._sessionRpcWithoutParams(
2626
2686
  "droid.list_mcp_servers" /* LIST_MCP_SERVERS */,
2627
- {}
2687
+ ListMcpServersResultSchema
2628
2688
  );
2629
- const result = response["result"];
2630
- return result ?? response;
2631
2689
  }
2632
- /**
2633
- * Toggle an MCP tool on or off.
2634
- */
2635
2690
  async toggleMcpTool(params) {
2636
- this._ensureNotClosed();
2637
- this._ensureSession();
2638
- const response = await this._engine.sendRequest(
2691
+ return this._sessionRpc(
2639
2692
  "droid.toggle_mcp_tool" /* TOGGLE_MCP_TOOL */,
2640
- params
2693
+ params,
2694
+ ToggleMcpToolResultSchema
2641
2695
  );
2642
- const result = response["result"];
2643
- return result ?? response;
2644
2696
  }
2645
- // ------------------------------------------------------------------
2646
- // Skills and bug report methods
2647
- // ------------------------------------------------------------------
2648
- /**
2649
- * List available skills.
2650
- */
2651
2697
  async listSkills() {
2652
- this._ensureNotClosed();
2653
- this._ensureSession();
2654
- const response = await this._engine.sendRequest(
2698
+ return this._sessionRpcWithoutParams(
2655
2699
  "droid.list_skills" /* LIST_SKILLS */,
2656
- {}
2700
+ ListSkillsResultSchema
2657
2701
  );
2658
- const result = response["result"];
2659
- return result ?? response;
2660
2702
  }
2661
- /**
2662
- * Submit a bug report.
2663
- */
2664
2703
  async submitBugReport(params) {
2665
- this._ensureNotClosed();
2666
- this._ensureSession();
2667
- const response = await this._engine.sendRequest(
2704
+ return this._sessionRpc(
2668
2705
  "droid.submit_bug_report" /* SUBMIT_BUG_REPORT */,
2669
- params
2706
+ params,
2707
+ SubmitBugReportResultSchema
2708
+ );
2709
+ }
2710
+ async getRewindInfo(params) {
2711
+ return this._sessionRpc(
2712
+ "droid.get_rewind_info" /* GET_REWIND_INFO */,
2713
+ params,
2714
+ GetRewindInfoResultSchema
2715
+ );
2716
+ }
2717
+ async executeRewind(params) {
2718
+ return this._sessionRpc(
2719
+ "droid.execute_rewind" /* EXECUTE_REWIND */,
2720
+ params,
2721
+ ExecuteRewindResultSchema,
2722
+ REWIND_TIMEOUT
2723
+ );
2724
+ }
2725
+ async compactSession(params) {
2726
+ return this._sessionRpc(
2727
+ "droid.compact_session" /* COMPACT_SESSION */,
2728
+ params,
2729
+ CompactSessionResultSchema,
2730
+ COMPACTION_TIMEOUT
2731
+ );
2732
+ }
2733
+ async forkSession() {
2734
+ return this._sessionRpcWithoutParams(
2735
+ "droid.fork_session" /* FORK_SESSION */,
2736
+ ForkSessionResultSchema
2737
+ );
2738
+ }
2739
+ async getContextStats() {
2740
+ return this._sessionRpcWithoutParams(
2741
+ "droid.get_context_stats" /* GET_CONTEXT_STATS */,
2742
+ GetContextStatsResultSchema
2743
+ );
2744
+ }
2745
+ async renameSession(params) {
2746
+ return this._sessionRpc(
2747
+ "droid.rename_session" /* RENAME_SESSION */,
2748
+ params,
2749
+ RenameSessionResultSchema
2670
2750
  );
2671
- const result = response["result"];
2672
- return result ?? response;
2673
2751
  }
2674
- // ------------------------------------------------------------------
2675
- // Notification subscription
2676
- // ------------------------------------------------------------------
2677
- /**
2678
- * Register a callback for incoming notification messages.
2679
- *
2680
- * Multiple listeners can be registered. Each receives the full parsed
2681
- * notification object. Optionally filter by notification type.
2682
- *
2683
- * Listener exceptions are isolated — if one raises, others still receive
2684
- * the event and the engine continues.
2685
- *
2686
- * @param callback - Invoked with the notification object.
2687
- * @param filter - Optional filter to only receive specific notification types.
2688
- * @returns An unsubscribe function. Calling it again is safe (no-op).
2689
- */
2690
2752
  onNotification(callback, filter) {
2691
- const entry = {
2692
- callback,
2693
- typeFilter: filter?.type
2694
- };
2753
+ const entry = { callback, filter };
2695
2754
  this._notificationListeners.push(entry);
2696
2755
  let unsubscribed = false;
2697
2756
  return () => {
@@ -2704,54 +2763,18 @@ var DroidClient = class {
2704
2763
  }
2705
2764
  };
2706
2765
  }
2707
- // ------------------------------------------------------------------
2708
- // Permission/ask-user handler registration
2709
- // ------------------------------------------------------------------
2710
- /**
2711
- * Register a handler for server→client permission requests.
2712
- *
2713
- * The handler receives the request params and should return a
2714
- * ToolConfirmationOutcome string value. Async handlers are awaited.
2715
- * Replaces any previously registered handler.
2716
- */
2717
2766
  setPermissionHandler(handler) {
2718
2767
  this._permissionHandler = handler;
2719
2768
  }
2720
- /**
2721
- * Remove the permission request handler.
2722
- * Restores default behavior: return "cancel".
2723
- */
2724
2769
  clearPermissionHandler() {
2725
2770
  this._permissionHandler = null;
2726
2771
  }
2727
- /**
2728
- * Register a handler for server→client ask-user requests.
2729
- *
2730
- * The handler receives the request params and should return a result
2731
- * object with `cancelled` and `answers` keys. Async handlers are awaited.
2732
- * Replaces any previously registered handler.
2733
- */
2734
2772
  setAskUserHandler(handler) {
2735
2773
  this._askUserHandler = handler;
2736
2774
  }
2737
- /**
2738
- * Remove the ask-user request handler.
2739
- * Restores default behavior: return `{ cancelled: true, answers: [] }`.
2740
- */
2741
2775
  clearAskUserHandler() {
2742
2776
  this._askUserHandler = null;
2743
2777
  }
2744
- // ------------------------------------------------------------------
2745
- // Lifecycle
2746
- // ------------------------------------------------------------------
2747
- /**
2748
- * Close the client and release all resources.
2749
- *
2750
- * Rejects pending requests, clears handlers and listeners, and closes
2751
- * the protocol engine. Idempotent — safe to call multiple times.
2752
- *
2753
- * After close, all method calls throw ConnectionError immediately.
2754
- */
2755
2778
  async close() {
2756
2779
  if (this._closed) {
2757
2780
  return;
@@ -2762,21 +2785,17 @@ var DroidClient = class {
2762
2785
  this._askUserHandler = null;
2763
2786
  await this._engine.close();
2764
2787
  }
2765
- // ------------------------------------------------------------------
2766
- // Internal: dispatch methods
2767
- // ------------------------------------------------------------------
2768
- /**
2769
- * Dispatch a notification to all registered client-level listeners.
2770
- * Filters by notification type if a type filter is set.
2771
- * Exception in one listener does not affect others.
2772
- */
2773
2788
  _dispatchNotification(notification) {
2774
- const params = notification["params"];
2775
- const innerNotification = params?.["notification"];
2776
- const notificationType = innerNotification?.["type"];
2789
+ let notificationType;
2790
+ const parsed = SessionNotificationParamsSchema.safeParse(
2791
+ notification["params"]
2792
+ );
2793
+ if (parsed.success) {
2794
+ notificationType = parsed.data.notification.type;
2795
+ }
2777
2796
  const listeners = [...this._notificationListeners];
2778
2797
  for (const listener of listeners) {
2779
- if (listener.typeFilter != null && listener.typeFilter !== notificationType) {
2798
+ if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2780
2799
  continue;
2781
2800
  }
2782
2801
  try {
@@ -2785,25 +2804,13 @@ var DroidClient = class {
2785
2804
  }
2786
2805
  }
2787
2806
  }
2788
- /**
2789
- * Dispatch to the client-level permission handler.
2790
- * If no handler is set, returns the default "cancel" outcome.
2791
- * If handler throws, the error propagates to the protocol engine
2792
- * which sends an error response.
2793
- */
2794
2807
  _dispatchPermissionRequest(params) {
2795
2808
  const handler = this._permissionHandler;
2796
2809
  if (handler == null) {
2797
- return "cancel";
2810
+ return "cancel" /* Cancel */;
2798
2811
  }
2799
2812
  return handler(params);
2800
2813
  }
2801
- /**
2802
- * Dispatch to the client-level ask-user handler.
2803
- * If no handler is set, returns the default cancelled response.
2804
- * If handler throws, the error propagates to the protocol engine
2805
- * which sends an error response.
2806
- */
2807
2814
  _dispatchAskUserRequest(params) {
2808
2815
  const handler = this._askUserHandler;
2809
2816
  if (handler == null) {
@@ -2811,12 +2818,6 @@ var DroidClient = class {
2811
2818
  }
2812
2819
  return handler(params);
2813
2820
  }
2814
- // ------------------------------------------------------------------
2815
- // Internal: guards
2816
- // ------------------------------------------------------------------
2817
- /**
2818
- * Throw ConnectionError if the client has been closed.
2819
- */
2820
2821
  _ensureNotClosed() {
2821
2822
  if (this._closed) {
2822
2823
  throw new ConnectionError(
@@ -2824,9 +2825,6 @@ var DroidClient = class {
2824
2825
  );
2825
2826
  }
2826
2827
  }
2827
- /**
2828
- * Throw SessionError if no active session.
2829
- */
2830
2828
  _ensureSession() {
2831
2829
  if (this._sessionId == null) {
2832
2830
  throw new SessionError(
@@ -2837,26 +2835,56 @@ var DroidClient = class {
2837
2835
  };
2838
2836
 
2839
2837
  // src/stream.ts
2840
- function convertNotificationToStreamMessage(notification) {
2838
+ var DroidMessageType = {
2839
+ AssistantTextDelta: "assistant_text_delta",
2840
+ ThinkingTextDelta: "thinking_text_delta",
2841
+ ToolUse: "tool_use",
2842
+ ToolResult: "tool_result",
2843
+ ToolProgress: "tool_progress",
2844
+ WorkingStateChanged: "working_state_changed",
2845
+ TokenUsageUpdate: "token_usage_update",
2846
+ CreateMessage: "create_message",
2847
+ PermissionResolved: "permission_resolved",
2848
+ SettingsUpdated: "settings_updated",
2849
+ SessionTitleUpdated: "session_title_updated",
2850
+ McpStatusChanged: "mcp_status_changed",
2851
+ MissionStateChanged: "mission_state_changed",
2852
+ MissionFeaturesChanged: "mission_features_changed",
2853
+ MissionProgressEntry: "mission_progress_entry",
2854
+ MissionHeartbeat: "mission_heartbeat",
2855
+ MissionWorkerStarted: "mission_worker_started",
2856
+ MissionWorkerCompleted: "mission_worker_completed",
2857
+ McpAuthRequired: "mcp_auth_required",
2858
+ McpAuthCompleted: "mcp_auth_completed",
2859
+ Error: "error",
2860
+ TurnComplete: "turn_complete"
2861
+ };
2862
+ function convertNotificationToStreamMessage(raw) {
2863
+ const parsed = SessionNotificationPayloadSchema.safeParse(raw);
2864
+ if (!parsed.success) {
2865
+ return null;
2866
+ }
2867
+ const notification = parsed.data;
2841
2868
  switch (notification.type) {
2842
2869
  case "assistant_text_delta" /* ASSISTANT_TEXT_DELTA */:
2843
2870
  return {
2844
- type: "assistant_text_delta",
2871
+ type: DroidMessageType.AssistantTextDelta,
2845
2872
  messageId: notification.messageId,
2846
2873
  blockIndex: notification.blockIndex,
2847
2874
  text: notification.textDelta
2848
2875
  };
2849
2876
  case "thinking_text_delta" /* THINKING_TEXT_DELTA */:
2850
2877
  return {
2851
- type: "thinking_text_delta",
2878
+ type: DroidMessageType.ThinkingTextDelta,
2852
2879
  messageId: notification.messageId,
2853
2880
  blockIndex: notification.blockIndex,
2854
2881
  text: notification.textDelta
2855
2882
  };
2856
2883
  case "tool_result" /* TOOL_RESULT */:
2857
2884
  return {
2858
- type: "tool_result",
2885
+ type: DroidMessageType.ToolResult,
2859
2886
  toolUseId: notification.toolUseId,
2887
+ toolName: "",
2860
2888
  content: normalizeToolResultContent(notification.content),
2861
2889
  isError: Boolean(notification.isError)
2862
2890
  };
@@ -2864,7 +2892,7 @@ function convertNotificationToStreamMessage(notification) {
2864
2892
  const update = notification.update;
2865
2893
  const text = update?.text ?? update?.status ?? update?.details ?? "";
2866
2894
  return {
2867
- type: "tool_progress",
2895
+ type: DroidMessageType.ToolProgress,
2868
2896
  toolUseId: notification.toolUseId,
2869
2897
  toolName: notification.toolName,
2870
2898
  content: text,
@@ -2873,108 +2901,106 @@ function convertNotificationToStreamMessage(notification) {
2873
2901
  }
2874
2902
  case "droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */:
2875
2903
  return {
2876
- type: "working_state_changed",
2904
+ type: DroidMessageType.WorkingStateChanged,
2877
2905
  state: notification.newState
2878
2906
  };
2879
2907
  case "session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */: {
2880
2908
  const tu = notification.tokenUsage;
2881
2909
  return {
2882
- type: "token_usage_update",
2910
+ type: DroidMessageType.TokenUsageUpdate,
2883
2911
  inputTokens: tu.inputTokens,
2884
2912
  outputTokens: tu.outputTokens,
2885
2913
  cacheReadTokens: tu.cacheReadTokens,
2886
- cacheWriteTokens: tu.cacheCreationTokens,
2914
+ cacheCreationTokens: tu.cacheCreationTokens,
2887
2915
  thinkingTokens: tu.thinkingTokens
2888
2916
  };
2889
2917
  }
2890
2918
  case "create_message" /* CREATE_MESSAGE */: {
2891
2919
  const msg = notification.message;
2892
2920
  const messages = [];
2893
- if (msg.content && Array.isArray(msg.content)) {
2894
- for (const block of msg.content) {
2895
- if (block.type === "tool_use") {
2896
- messages.push({
2897
- type: "tool_use",
2898
- toolName: block.name,
2899
- toolInput: block.input ?? {},
2900
- toolUseId: block.id
2901
- });
2902
- }
2921
+ for (const block of msg.content) {
2922
+ if (block.type === DroidMessageType.ToolUse) {
2923
+ messages.push({
2924
+ type: DroidMessageType.ToolUse,
2925
+ toolName: block.name,
2926
+ toolInput: block.input,
2927
+ toolUseId: block.id
2928
+ });
2903
2929
  }
2904
2930
  }
2905
2931
  messages.push({
2906
- type: "create_message",
2932
+ type: DroidMessageType.CreateMessage,
2907
2933
  messageId: msg.id,
2908
2934
  role: msg.role,
2909
- content: msg.content ?? [],
2935
+ content: msg.content,
2910
2936
  parentId: notification.parentId
2911
2937
  });
2912
2938
  return messages;
2913
2939
  }
2914
2940
  case "error" /* ERROR */:
2915
2941
  return {
2916
- type: "error",
2942
+ type: DroidMessageType.Error,
2917
2943
  message: notification.message,
2918
2944
  errorType: notification.errorType,
2919
2945
  timestamp: notification.timestamp
2920
2946
  };
2921
2947
  case "permission_resolved" /* PERMISSION_RESOLVED */:
2922
2948
  return {
2923
- type: "permission_resolved",
2949
+ type: DroidMessageType.PermissionResolved,
2924
2950
  requestId: notification.requestId,
2925
2951
  toolUseIds: notification.toolUseIds,
2926
2952
  selectedOption: notification.selectedOption
2927
2953
  };
2928
2954
  case "settings_updated" /* SETTINGS_UPDATED */:
2929
2955
  return {
2930
- type: "settings_updated",
2956
+ type: DroidMessageType.SettingsUpdated,
2931
2957
  settings: notification.settings
2932
2958
  };
2933
2959
  case "session_title_updated" /* SESSION_TITLE_UPDATED */:
2934
2960
  return {
2935
- type: "session_title_updated",
2961
+ type: DroidMessageType.SessionTitleUpdated,
2936
2962
  title: notification.title
2937
2963
  };
2938
2964
  case "mcp_status_changed" /* MCP_STATUS_CHANGED */:
2939
2965
  return {
2940
- type: "mcp_status_changed",
2966
+ type: DroidMessageType.McpStatusChanged,
2941
2967
  servers: notification.servers,
2942
2968
  summary: notification.summary
2943
2969
  };
2944
2970
  case "mission_state_changed" /* MISSION_STATE_CHANGED */:
2945
2971
  return {
2946
- type: "mission_state_changed",
2972
+ type: DroidMessageType.MissionStateChanged,
2947
2973
  state: notification.state
2948
2974
  };
2949
2975
  case "mission_features_changed" /* MISSION_FEATURES_CHANGED */:
2950
2976
  return {
2951
- type: "mission_features_changed",
2977
+ type: DroidMessageType.MissionFeaturesChanged,
2952
2978
  features: notification.features
2953
2979
  };
2954
2980
  case "mission_progress_entry" /* MISSION_PROGRESS_ENTRY */:
2955
2981
  return {
2956
- type: "mission_progress_entry",
2982
+ type: DroidMessageType.MissionProgressEntry,
2957
2983
  progressLog: notification.progressLog
2958
2984
  };
2959
2985
  case "mission_heartbeat" /* MISSION_HEARTBEAT */:
2960
2986
  return {
2961
- type: "mission_heartbeat",
2987
+ type: DroidMessageType.MissionHeartbeat,
2962
2988
  timestamp: notification.timestamp
2963
2989
  };
2964
2990
  case "mission_worker_started" /* MISSION_WORKER_STARTED */:
2965
2991
  return {
2966
- type: "mission_worker_started",
2992
+ type: DroidMessageType.MissionWorkerStarted,
2967
2993
  workerSessionId: notification.workerSessionId
2968
2994
  };
2969
2995
  case "mission_worker_completed" /* MISSION_WORKER_COMPLETED */:
2970
2996
  return {
2971
- type: "mission_worker_completed",
2997
+ type: DroidMessageType.MissionWorkerCompleted,
2972
2998
  workerSessionId: notification.workerSessionId,
2973
2999
  exitCode: notification.exitCode
2974
3000
  };
2975
3001
  case "mcp_auth_required" /* MCP_AUTH_REQUIRED */:
2976
3002
  return {
2977
- type: "mcp_auth_required",
3003
+ type: DroidMessageType.McpAuthRequired,
2978
3004
  serverName: notification.serverName,
2979
3005
  authUrl: notification.authUrl,
2980
3006
  message: notification.message,
@@ -2982,54 +3008,45 @@ function convertNotificationToStreamMessage(notification) {
2982
3008
  };
2983
3009
  case "mcp_auth_completed" /* MCP_AUTH_COMPLETED */:
2984
3010
  return {
2985
- type: "mcp_auth_completed",
3011
+ type: DroidMessageType.McpAuthCompleted,
2986
3012
  serverName: notification.serverName,
2987
3013
  outcome: notification.outcome,
2988
3014
  message: notification.message
2989
3015
  };
2990
3016
  default:
2991
- console.warn(
2992
- `[droid-sdk] Unknown notification type: ${String(notification.type)}`
2993
- );
2994
3017
  return null;
2995
3018
  }
2996
3019
  }
2997
3020
  var StreamStateTracker = class {
2998
- /** Whether we have ever seen a non-idle state. */
2999
3021
  hasBeenNonIdle = false;
3000
- /** Last-seen token usage update (to attach to TurnComplete). */
3001
3022
  lastTokenUsage = null;
3002
- /**
3003
- * Process a DroidMessage and return any additional messages that should be
3004
- * emitted (e.g. TurnComplete sentinel).
3005
- *
3006
- * @param message - The DroidMessage to process.
3007
- * @returns An array of additional messages to emit (may be empty).
3008
- */
3023
+ toolNameMap = /* @__PURE__ */ new Map();
3024
+ getToolName(toolUseId) {
3025
+ return this.toolNameMap.get(toolUseId) ?? "";
3026
+ }
3009
3027
  processMessage(message) {
3010
3028
  const additional = [];
3011
- if (message.type === "token_usage_update") {
3029
+ if (message.type === DroidMessageType.ToolUse) {
3030
+ this.toolNameMap.set(message.toolUseId, message.toolName);
3031
+ }
3032
+ if (message.type === DroidMessageType.ToolResult) {
3033
+ message = { ...message, toolName: this.getToolName(message.toolUseId) };
3034
+ }
3035
+ if (message.type === DroidMessageType.TokenUsageUpdate) {
3012
3036
  this.lastTokenUsage = message;
3013
3037
  }
3014
- if (message.type === "working_state_changed") {
3038
+ if (message.type === DroidMessageType.WorkingStateChanged) {
3015
3039
  if (message.state !== "idle" /* Idle */) {
3016
3040
  this.hasBeenNonIdle = true;
3017
3041
  } else if (this.hasBeenNonIdle) {
3018
3042
  additional.push({
3019
- type: "turn_complete",
3043
+ type: DroidMessageType.TurnComplete,
3020
3044
  tokenUsage: this.lastTokenUsage
3021
3045
  });
3022
3046
  this.hasBeenNonIdle = false;
3023
3047
  }
3024
3048
  }
3025
- return additional;
3026
- }
3027
- /**
3028
- * Reset the tracker for a new turn/stream call.
3029
- */
3030
- reset() {
3031
- this.hasBeenNonIdle = false;
3032
- this.lastTokenUsage = null;
3049
+ return { message, additional };
3033
3050
  }
3034
3051
  };
3035
3052
  function normalizeToolResultContent(content) {
@@ -3045,124 +3062,469 @@ function normalizeToolResultContent(content) {
3045
3062
  return String(content);
3046
3063
  }
3047
3064
 
3048
- // src/query.ts
3049
- function query(options) {
3050
- let transport = null;
3051
- let client = null;
3052
- let sessionId = null;
3053
- let aborted = false;
3054
- const messageQueue = [];
3055
- let resolveWaiting = null;
3056
- let streamDone = false;
3057
- function enqueueMessage(msg) {
3058
- messageQueue.push(msg);
3059
- if (resolveWaiting) {
3060
- const resolve = resolveWaiting;
3061
- resolveWaiting = null;
3062
- resolve();
3063
- }
3065
+ // src/helpers.ts
3066
+ function wireAbortSignal(signal, onAbort) {
3067
+ if (!signal) return () => {
3068
+ };
3069
+ if (signal.aborted) {
3070
+ onAbort();
3071
+ return () => {
3072
+ };
3073
+ } else {
3074
+ const listener = () => onAbort();
3075
+ signal.addEventListener("abort", listener, { once: true });
3076
+ return () => signal.removeEventListener("abort", listener);
3064
3077
  }
3065
- function signalDone() {
3066
- streamDone = true;
3067
- if (resolveWaiting) {
3068
- const resolve = resolveWaiting;
3069
- resolveWaiting = null;
3070
- resolve();
3078
+ }
3079
+ function extractInnerNotification(notification) {
3080
+ const parsed = SessionNotificationSchema.safeParse(notification);
3081
+ return parsed.success ? parsed.data.params.notification : null;
3082
+ }
3083
+ var MessageBridge = class {
3084
+ _queue = [];
3085
+ _resolveWaiting = null;
3086
+ _done = false;
3087
+ _stateTracker = new StreamStateTracker();
3088
+ notificationHandler = (notification) => {
3089
+ const inner = extractInnerNotification(notification);
3090
+ if (!inner) return;
3091
+ const converted = convertNotificationToStreamMessage(inner);
3092
+ if (converted === null) return;
3093
+ const messages = Array.isArray(converted) ? converted : [converted];
3094
+ for (const msg of messages) {
3095
+ const { message, additional } = this._stateTracker.processMessage(msg);
3096
+ this._enqueue(message);
3097
+ for (const extra of additional) {
3098
+ this._enqueue(extra);
3099
+ if (extra.type === DroidMessageType.TurnComplete) {
3100
+ this._signalDone();
3101
+ }
3102
+ }
3071
3103
  }
3104
+ };
3105
+ signalDone() {
3106
+ this._signalDone();
3072
3107
  }
3073
- async function* generateMessages() {
3074
- if (options.transport) {
3075
- transport = options.transport;
3076
- } else {
3077
- const transportOptions = {
3078
- execPath: options.execPath,
3079
- execArgs: options.execArgs,
3080
- cwd: options.cwd,
3081
- env: options.env
3082
- };
3083
- const processTransport = new ProcessTransport(transportOptions);
3084
- await processTransport.connect();
3085
- transport = processTransport;
3086
- }
3087
- client = new DroidClient({ transport });
3088
- if (options.permissionHandler) {
3089
- client.setPermissionHandler(options.permissionHandler);
3090
- }
3091
- if (options.askUserHandler) {
3092
- client.setAskUserHandler(options.askUserHandler);
3093
- }
3094
- const stateTracker = new StreamStateTracker();
3095
- client.onNotification((notification) => {
3096
- const params = notification["params"];
3097
- const innerNotification = params?.["notification"];
3098
- if (!innerNotification) {
3099
- return;
3108
+ async *messages() {
3109
+ while (true) {
3110
+ while (this._queue.length > 0) {
3111
+ const msg = this._queue.shift();
3112
+ yield msg;
3113
+ if (msg.type === DroidMessageType.TurnComplete) {
3114
+ return;
3115
+ }
3100
3116
  }
3101
- const converted = convertNotificationToStreamMessage(
3102
- innerNotification
3103
- );
3104
- if (converted === null) {
3117
+ if (this._done && this._queue.length === 0) {
3105
3118
  return;
3106
3119
  }
3107
- const messages = Array.isArray(converted) ? converted : [converted];
3108
- for (const msg of messages) {
3109
- enqueueMessage(msg);
3110
- const additional = stateTracker.processMessage(msg);
3111
- for (const extra of additional) {
3112
- enqueueMessage(extra);
3113
- if (extra.type === "turn_complete") {
3114
- signalDone();
3115
- }
3116
- }
3117
- }
3118
- });
3119
- const initParams = {
3120
- machineId: options.machineId ?? "default",
3121
- cwd: options.cwd ?? "."
3120
+ await new Promise((resolve2) => {
3121
+ this._resolveWaiting = resolve2;
3122
+ });
3123
+ }
3124
+ }
3125
+ _enqueue(msg) {
3126
+ this._queue.push(msg);
3127
+ if (this._resolveWaiting) {
3128
+ const resolve2 = this._resolveWaiting;
3129
+ this._resolveWaiting = null;
3130
+ resolve2();
3131
+ }
3132
+ }
3133
+ _signalDone() {
3134
+ this._done = true;
3135
+ if (this._resolveWaiting) {
3136
+ const resolve2 = this._resolveWaiting;
3137
+ this._resolveWaiting = null;
3138
+ resolve2();
3139
+ }
3140
+ }
3141
+ };
3142
+ async function createTransport(options) {
3143
+ if (options.transport) {
3144
+ return options.transport;
3145
+ }
3146
+ const transportOptions = {
3147
+ execPath: options.execPath,
3148
+ execArgs: options.execArgs,
3149
+ cwd: options.cwd,
3150
+ env: options.env
3151
+ };
3152
+ const processTransport = new ProcessTransport(transportOptions);
3153
+ await processTransport.connect();
3154
+ return processTransport;
3155
+ }
3156
+ function setupClientHandlers(client, options) {
3157
+ if (options.permissionHandler) {
3158
+ client.setPermissionHandler(options.permissionHandler);
3159
+ }
3160
+ if (options.askUserHandler) {
3161
+ client.setAskUserHandler(options.askUserHandler);
3162
+ }
3163
+ }
3164
+ async function createConfiguredClient(options) {
3165
+ const transport = await createTransport(options);
3166
+ const client = new DroidClient({ transport });
3167
+ setupClientHandlers(client, options);
3168
+ return { transport, client };
3169
+ }
3170
+ async function closeQuietly(resource) {
3171
+ if (!resource) {
3172
+ return;
3173
+ }
3174
+ try {
3175
+ await resource.close();
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ function buildInitParams(options) {
3180
+ return {
3181
+ machineId: options.machineId ?? "default",
3182
+ cwd: options.cwd ?? ".",
3183
+ ...options.modelId !== void 0 && { modelId: options.modelId },
3184
+ ...options.autonomyLevel !== void 0 && {
3185
+ autonomyLevel: options.autonomyLevel
3186
+ },
3187
+ ...options.interactionMode !== void 0 && {
3188
+ interactionMode: options.interactionMode
3189
+ },
3190
+ ...options.reasoningEffort !== void 0 && {
3191
+ reasoningEffort: options.reasoningEffort
3192
+ },
3193
+ ...options.specModeModelId !== void 0 && {
3194
+ specModeModelId: options.specModeModelId
3195
+ },
3196
+ ...options.specModeReasoningEffort !== void 0 && {
3197
+ specModeReasoningEffort: options.specModeReasoningEffort
3198
+ },
3199
+ ...options.mcpServers !== void 0 && {
3200
+ mcpServers: options.mcpServers
3201
+ },
3202
+ ...options.enabledToolIds !== void 0 && {
3203
+ enabledToolIds: options.enabledToolIds
3204
+ },
3205
+ ...options.disabledToolIds !== void 0 && {
3206
+ disabledToolIds: options.disabledToolIds
3207
+ },
3208
+ tags: [...options.tags ?? [], SDK_TAG]
3209
+ };
3210
+ }
3211
+
3212
+ // src/mcp.ts
3213
+ var import_node_events = require("events");
3214
+ var import_node_http = __toESM(require("http"), 1);
3215
+ var import_mcp4 = require("@modelcontextprotocol/sdk/server/mcp.js");
3216
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
3217
+ var import_zod8 = require("zod");
3218
+ function tool(name, description, inputSchemaOrHandler, handler) {
3219
+ if (typeof inputSchemaOrHandler === "function") {
3220
+ const actualHandler = inputSchemaOrHandler;
3221
+ return {
3222
+ name,
3223
+ description,
3224
+ handler: (input) => actualHandler(input)
3225
+ };
3226
+ }
3227
+ if (!handler) {
3228
+ throw new Error(`Missing handler for SDK MCP tool "${name}"`);
3229
+ }
3230
+ const inputObjectSchema = import_zod8.z.object(inputSchemaOrHandler);
3231
+ return {
3232
+ name,
3233
+ description,
3234
+ inputSchema: inputSchemaOrHandler,
3235
+ handler: (input) => handler(inputObjectSchema.parse(input))
3236
+ };
3237
+ }
3238
+ function isSdkMcpServer(server) {
3239
+ return server instanceof SdkMcpServer;
3240
+ }
3241
+ function toCallToolResult(result) {
3242
+ if (typeof result === "string") {
3243
+ return {
3244
+ content: [{ type: "text", text: result }]
3122
3245
  };
3123
- if (options.modelId !== void 0) {
3124
- initParams.modelId = options.modelId;
3246
+ }
3247
+ return result;
3248
+ }
3249
+ async function readJsonBody(req) {
3250
+ const chunks = [];
3251
+ for await (const chunk of req) {
3252
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
3253
+ }
3254
+ if (chunks.length === 0) {
3255
+ return void 0;
3256
+ }
3257
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
3258
+ }
3259
+ function writeJsonError(res, statusCode, message) {
3260
+ if (res.headersSent) {
3261
+ return;
3262
+ }
3263
+ res.writeHead(statusCode, { "content-type": "application/json" });
3264
+ res.end(
3265
+ JSON.stringify({
3266
+ jsonrpc: JSONRPC_VERSION,
3267
+ error: { code: -32603 /* INTERNAL_ERROR */, message },
3268
+ id: null
3269
+ })
3270
+ );
3271
+ }
3272
+ var SdkMcpServer = class {
3273
+ name;
3274
+ version;
3275
+ tools;
3276
+ _httpServer = null;
3277
+ _url = null;
3278
+ constructor(options) {
3279
+ this.name = options.name;
3280
+ this.version = options.version ?? "1.0.0";
3281
+ this.tools = options.tools;
3282
+ }
3283
+ get config() {
3284
+ if (!this._url) {
3285
+ return null;
3125
3286
  }
3126
- if (options.autonomyLevel !== void 0) {
3127
- initParams.autonomyLevel = options.autonomyLevel;
3287
+ return {
3288
+ type: "http" /* Http */,
3289
+ name: this.name,
3290
+ url: this._url,
3291
+ headers: []
3292
+ };
3293
+ }
3294
+ async start() {
3295
+ if (this.config) {
3296
+ return this.config;
3128
3297
  }
3129
- if (options.interactionMode !== void 0) {
3130
- initParams.interactionMode = options.interactionMode;
3298
+ this._httpServer = import_node_http.default.createServer((req, res) => {
3299
+ void this.handleRequest(req, res);
3300
+ });
3301
+ this._httpServer.listen(0, "127.0.0.1");
3302
+ await (0, import_node_events.once)(this._httpServer, "listening");
3303
+ const address = this._httpServer.address();
3304
+ if (!address || typeof address === "string") {
3305
+ throw new Error("Unable to determine SDK MCP server address");
3131
3306
  }
3132
- if (options.reasoningEffort !== void 0) {
3133
- initParams.reasoningEffort = options.reasoningEffort;
3307
+ this._url = `http://127.0.0.1:${address.port}/mcp`;
3308
+ const config = this.config;
3309
+ if (!config) {
3310
+ throw new Error("Unable to start SDK MCP server");
3134
3311
  }
3135
- if (options.mcpServers !== void 0) {
3136
- initParams.mcpServers = options.mcpServers;
3312
+ return config;
3313
+ }
3314
+ async close() {
3315
+ const server = this._httpServer;
3316
+ this._httpServer = null;
3317
+ this._url = null;
3318
+ if (!server) {
3319
+ return;
3137
3320
  }
3138
- if (options.enabledToolIds !== void 0) {
3139
- initParams.enabledToolIds = options.enabledToolIds;
3321
+ server.closeAllConnections?.();
3322
+ server.close();
3323
+ await (0, import_node_events.once)(server, "close");
3324
+ }
3325
+ createMcpServer() {
3326
+ const server = new import_mcp4.McpServer({
3327
+ name: this.name,
3328
+ version: this.version
3329
+ });
3330
+ for (const sdkTool of this.tools) {
3331
+ server.registerTool(
3332
+ sdkTool.name,
3333
+ {
3334
+ description: sdkTool.description,
3335
+ ...sdkTool.inputSchema && {
3336
+ inputSchema: sdkTool.inputSchema
3337
+ }
3338
+ },
3339
+ async (input) => toCallToolResult(await sdkTool.handler(input))
3340
+ );
3140
3341
  }
3141
- const initResult = await client.initializeSession(
3142
- initParams
3143
- );
3144
- sessionId = initResult.sessionId;
3145
- await client.addUserMessage({ text: options.prompt });
3342
+ return server;
3343
+ }
3344
+ async handleRequest(req, res) {
3345
+ if (req.url !== "/mcp") {
3346
+ res.writeHead(404).end();
3347
+ return;
3348
+ }
3349
+ if (req.method !== "POST") {
3350
+ res.writeHead(405).end();
3351
+ return;
3352
+ }
3353
+ const server = this.createMcpServer();
3354
+ const transport = new import_streamableHttp.StreamableHTTPServerTransport({
3355
+ sessionIdGenerator: void 0
3356
+ });
3357
+ res.on("close", () => {
3358
+ void transport.close();
3359
+ void server.close();
3360
+ });
3146
3361
  try {
3147
- while (true) {
3362
+ const body = await readJsonBody(req);
3363
+ await server.connect(transport);
3364
+ await transport.handleRequest(req, res, body);
3365
+ } catch (error) {
3366
+ writeJsonError(
3367
+ res,
3368
+ 500,
3369
+ error instanceof Error ? error.message : "Internal server error"
3370
+ );
3371
+ await transport.close();
3372
+ await server.close();
3373
+ }
3374
+ }
3375
+ };
3376
+ function createSdkMcpServer(options) {
3377
+ return new SdkMcpServer(options);
3378
+ }
3379
+ async function startSdkMcpServers(servers) {
3380
+ if (!servers) {
3381
+ return { cleanup: async () => {
3382
+ } };
3383
+ }
3384
+ const startedServers = [];
3385
+ const mcpServers = [];
3386
+ try {
3387
+ for (const server of servers) {
3388
+ if (isSdkMcpServer(server)) {
3389
+ mcpServers.push(await server.start());
3390
+ startedServers.push(server);
3391
+ } else {
3392
+ mcpServers.push(server);
3393
+ }
3394
+ }
3395
+ } catch (error) {
3396
+ await Promise.all(startedServers.map((server) => server.close()));
3397
+ throw error;
3398
+ }
3399
+ return {
3400
+ mcpServers,
3401
+ cleanup: async () => {
3402
+ await Promise.all(startedServers.map((server) => server.close()));
3403
+ }
3404
+ };
3405
+ }
3406
+
3407
+ // src/query.ts
3408
+ var DroidQueryImpl = class {
3409
+ _generator;
3410
+ _getSessionId;
3411
+ _getInitResult;
3412
+ _getInitialized;
3413
+ _interruptFn;
3414
+ _abortFn;
3415
+ constructor(generator, getSessionId, getInitResult, getInitialized, interruptFn, abortFn) {
3416
+ this._generator = generator;
3417
+ this._getSessionId = getSessionId;
3418
+ this._getInitResult = getInitResult;
3419
+ this._getInitialized = getInitialized;
3420
+ this._interruptFn = interruptFn;
3421
+ this._abortFn = abortFn;
3422
+ }
3423
+ get sessionId() {
3424
+ return this._getSessionId();
3425
+ }
3426
+ get initResult() {
3427
+ return this._getInitResult();
3428
+ }
3429
+ get initialized() {
3430
+ return this._getInitialized();
3431
+ }
3432
+ async interrupt() {
3433
+ return this._interruptFn();
3434
+ }
3435
+ abort() {
3436
+ this._abortFn();
3437
+ }
3438
+ next(...args) {
3439
+ return this._generator.next(...args);
3440
+ }
3441
+ return(value) {
3442
+ return this._generator.return(value);
3443
+ }
3444
+ throw(e) {
3445
+ return this._generator.throw(e);
3446
+ }
3447
+ [Symbol.asyncIterator]() {
3448
+ return this;
3449
+ }
3450
+ };
3451
+ function query(options) {
3452
+ let transport = null;
3453
+ let client = null;
3454
+ let sessionId = null;
3455
+ let initResult = null;
3456
+ let aborted = false;
3457
+ let initializationPromise = null;
3458
+ let promptPromise = null;
3459
+ let cleanupAbortSignal = () => {
3460
+ };
3461
+ let cleanupSdkMcpServers = null;
3462
+ const bridge = new MessageBridge();
3463
+ const closeActiveResources = async () => {
3464
+ const closer = client ?? transport;
3465
+ const cleanupMcp = cleanupSdkMcpServers;
3466
+ client = null;
3467
+ transport = null;
3468
+ cleanupSdkMcpServers = null;
3469
+ await Promise.all([closeQuietly(closer), cleanupMcp?.()]);
3470
+ };
3471
+ const ensureInitialized = () => {
3472
+ if (initResult) {
3473
+ return Promise.resolve(initResult);
3474
+ }
3475
+ if (initializationPromise) {
3476
+ return initializationPromise;
3477
+ }
3478
+ initializationPromise = (async () => {
3479
+ try {
3148
3480
  if (aborted) {
3149
- return;
3481
+ throw new Error("Query aborted before initialization");
3150
3482
  }
3151
- while (messageQueue.length > 0) {
3152
- const msg = messageQueue.shift();
3153
- yield msg;
3154
- if (msg.type === "turn_complete") {
3155
- return;
3156
- }
3157
- }
3158
- if (streamDone && messageQueue.length === 0) {
3159
- return;
3483
+ const configuredClient = await createConfiguredClient(options);
3484
+ transport = configuredClient.transport;
3485
+ client = configuredClient.client;
3486
+ client.onNotification(bridge.notificationHandler);
3487
+ if (aborted) {
3488
+ throw new Error("Query aborted before initialization");
3160
3489
  }
3161
- await new Promise((resolve) => {
3162
- resolveWaiting = resolve;
3163
- });
3490
+ const sdkMcpServers = await startSdkMcpServers(options.mcpServers);
3491
+ cleanupSdkMcpServers = sdkMcpServers.cleanup;
3492
+ const result = await client.initializeSession(
3493
+ buildInitParams({
3494
+ ...options,
3495
+ mcpServers: sdkMcpServers.mcpServers
3496
+ })
3497
+ );
3498
+ sessionId = result.sessionId;
3499
+ initResult = result;
3500
+ return result;
3501
+ } catch (error) {
3502
+ await closeActiveResources();
3503
+ throw error;
3164
3504
  }
3165
- } finally {
3505
+ })();
3506
+ return initializationPromise;
3507
+ };
3508
+ const ensurePromptSent = () => {
3509
+ if (promptPromise) {
3510
+ return promptPromise;
3511
+ }
3512
+ promptPromise = (async () => {
3513
+ await ensureInitialized();
3514
+ if (aborted || client === null) {
3515
+ return;
3516
+ }
3517
+ await client.addUserMessage({ text: options.prompt });
3518
+ })();
3519
+ return promptPromise;
3520
+ };
3521
+ async function* generateMessages() {
3522
+ if (aborted) return;
3523
+ await ensurePromptSent();
3524
+ if (aborted) return;
3525
+ for await (const msg of bridge.messages()) {
3526
+ if (aborted) return;
3527
+ yield msg;
3166
3528
  }
3167
3529
  }
3168
3530
  const generator = generateMessages();
@@ -3170,310 +3532,273 @@ function query(options) {
3170
3532
  try {
3171
3533
  yield* generator;
3172
3534
  } finally {
3173
- if (client) {
3174
- try {
3175
- await client.close();
3176
- } catch {
3177
- }
3178
- client = null;
3179
- } else if (transport) {
3180
- try {
3181
- await transport.close();
3182
- } catch {
3183
- }
3184
- }
3185
- transport = null;
3535
+ cleanupAbortSignal();
3536
+ await closeActiveResources();
3186
3537
  }
3187
3538
  }
3188
- const wrapped = wrappedGenerator();
3189
- const droidQuery = wrapped;
3190
- Object.defineProperties(droidQuery, {
3191
- interrupt: {
3192
- value: async function interrupt() {
3193
- if (client && !aborted) {
3194
- await client.interruptSession();
3195
- }
3196
- },
3197
- writable: false,
3198
- enumerable: true
3199
- },
3200
- abort: {
3201
- value: function abort() {
3202
- aborted = true;
3203
- signalDone();
3204
- if (client) {
3205
- void client.close().catch(() => {
3206
- });
3207
- client = null;
3208
- } else if (transport) {
3209
- void transport.close().catch(() => {
3210
- });
3211
- }
3212
- transport = null;
3213
- },
3214
- writable: false,
3215
- enumerable: true
3539
+ const droidQuery = new DroidQueryImpl(
3540
+ wrappedGenerator(),
3541
+ () => sessionId,
3542
+ () => initResult,
3543
+ () => ensureInitialized(),
3544
+ async () => {
3545
+ if (client && !aborted) {
3546
+ await client.interruptSession();
3547
+ }
3216
3548
  },
3217
- sessionId: {
3218
- get() {
3219
- return sessionId;
3220
- },
3221
- enumerable: true
3549
+ () => {
3550
+ aborted = true;
3551
+ bridge.signalDone();
3552
+ cleanupAbortSignal();
3553
+ void closeActiveResources();
3222
3554
  }
3223
- });
3555
+ );
3556
+ cleanupAbortSignal = wireAbortSignal(
3557
+ options.abortSignal,
3558
+ () => droidQuery.abort()
3559
+ );
3224
3560
  return droidQuery;
3225
3561
  }
3226
3562
 
3227
3563
  // src/session.ts
3564
+ function getAbortError(signal) {
3565
+ if (signal.reason instanceof Error) {
3566
+ return signal.reason;
3567
+ }
3568
+ return new Error(
3569
+ typeof signal.reason === "string" ? signal.reason : "Operation aborted"
3570
+ );
3571
+ }
3572
+ function throwIfAborted(signal) {
3573
+ if (signal?.aborted) {
3574
+ throw getAbortError(signal);
3575
+ }
3576
+ }
3577
+ function parseJsonObject(text) {
3578
+ try {
3579
+ const parsed = JSON.parse(text);
3580
+ const result = JsonObjectSchema.safeParse(parsed);
3581
+ return result.success ? result.data : null;
3582
+ } catch {
3583
+ return null;
3584
+ }
3585
+ }
3586
+ function extractAssistantText(message) {
3587
+ if (message.type !== DroidMessageType.CreateMessage) {
3588
+ return "";
3589
+ }
3590
+ if (message.role !== FactoryDroidMessageRole.Assistant) {
3591
+ return "";
3592
+ }
3593
+ return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
3594
+ }
3228
3595
  var DroidSession = class {
3229
3596
  _client;
3230
3597
  _sessionId;
3231
3598
  _initResult;
3232
3599
  _closed = false;
3600
+ _cleanupAbortSignal = null;
3601
+ _cleanupCallbacks = [];
3233
3602
  /** @internal */
3234
3603
  constructor(client, sessionId, initResult) {
3235
3604
  this._client = client;
3236
3605
  this._sessionId = sessionId;
3237
3606
  this._initResult = initResult;
3238
3607
  }
3239
- // ------------------------------------------------------------------
3240
- // Properties
3241
- // ------------------------------------------------------------------
3242
- /** The session ID. */
3243
3608
  get sessionId() {
3244
3609
  return this._sessionId;
3245
3610
  }
3246
- /** The result from session initialization or loading. */
3247
3611
  get initResult() {
3248
3612
  return this._initResult;
3249
3613
  }
3250
- // ------------------------------------------------------------------
3251
- // Messaging
3252
- // ------------------------------------------------------------------
3253
- /**
3254
- * Send a message and return a streaming async generator of DroidMessage events.
3255
- *
3256
- * The generator yields messages until a TurnComplete event is received,
3257
- * signaling the end of the agent's turn.
3258
- *
3259
- * @param text - The user message text.
3260
- * @param options - Optional images/files to include.
3261
- * @returns An async generator yielding DroidMessage events.
3262
- */
3614
+ /** @internal */
3615
+ setAbortSignalCleanup(cleanup) {
3616
+ this._cleanupAbortSignal = cleanup;
3617
+ }
3618
+ /** @internal */
3619
+ addCleanup(cleanup) {
3620
+ this._cleanupCallbacks.push(cleanup);
3621
+ }
3622
+ /** Yields {@link DroidMessage} events until `turn_complete`. */
3263
3623
  async *stream(text, options) {
3264
3624
  this._ensureNotClosed();
3265
- const messageQueue = [];
3266
- let resolveWaiting = null;
3267
- let streamDone = false;
3268
- function enqueueMessage(msg) {
3269
- messageQueue.push(msg);
3270
- if (resolveWaiting) {
3271
- const resolve = resolveWaiting;
3272
- resolveWaiting = null;
3273
- resolve();
3274
- }
3275
- }
3276
- function signalDone() {
3277
- streamDone = true;
3278
- if (resolveWaiting) {
3279
- const resolve = resolveWaiting;
3280
- resolveWaiting = null;
3281
- resolve();
3282
- }
3283
- }
3284
- const stateTracker = new StreamStateTracker();
3285
- const unsubscribe = this._client.onNotification((notification) => {
3286
- const params = notification["params"];
3287
- const innerNotification = params?.["notification"];
3288
- if (!innerNotification) {
3289
- return;
3290
- }
3291
- const converted = convertNotificationToStreamMessage(
3292
- innerNotification
3293
- );
3294
- if (converted === null) {
3295
- return;
3296
- }
3297
- const messages = Array.isArray(converted) ? converted : [converted];
3298
- for (const msg of messages) {
3299
- enqueueMessage(msg);
3300
- const additional = stateTracker.processMessage(msg);
3301
- for (const extra of additional) {
3302
- enqueueMessage(extra);
3303
- if (extra.type === "turn_complete") {
3304
- signalDone();
3305
- }
3306
- }
3307
- }
3625
+ throwIfAborted(options?.abortSignal);
3626
+ const bridge = new MessageBridge();
3627
+ const unsubscribe = this._client.onNotification(bridge.notificationHandler);
3628
+ let resolveAbort = () => {
3629
+ };
3630
+ const abortPromise = new Promise((resolve2) => {
3631
+ resolveAbort = resolve2;
3308
3632
  });
3309
- try {
3310
- await this._client.addUserMessage({
3311
- text,
3312
- images: options?.images,
3313
- files: options?.files
3633
+ const cleanupAbortSignal = wireAbortSignal(options?.abortSignal, () => {
3634
+ bridge.signalDone();
3635
+ resolveAbort();
3636
+ void this._client.interruptSession().catch(() => {
3314
3637
  });
3315
- while (true) {
3316
- while (messageQueue.length > 0) {
3317
- const msg = messageQueue.shift();
3318
- yield msg;
3319
- if (msg.type === "turn_complete") {
3320
- return;
3321
- }
3322
- }
3323
- if (streamDone && messageQueue.length === 0) {
3324
- return;
3325
- }
3326
- await new Promise((resolve) => {
3327
- resolveWaiting = resolve;
3328
- });
3638
+ });
3639
+ try {
3640
+ await Promise.race([
3641
+ this._client.addUserMessage({
3642
+ text,
3643
+ images: options?.images,
3644
+ files: options?.files,
3645
+ outputFormat: options?.outputFormat
3646
+ }),
3647
+ abortPromise
3648
+ ]);
3649
+ throwIfAborted(options?.abortSignal);
3650
+ for await (const msg of bridge.messages()) {
3651
+ throwIfAborted(options?.abortSignal);
3652
+ yield msg;
3329
3653
  }
3654
+ throwIfAborted(options?.abortSignal);
3330
3655
  } finally {
3656
+ cleanupAbortSignal();
3331
3657
  unsubscribe();
3332
3658
  }
3333
3659
  }
3334
- /**
3335
- * Send a message and collect the complete response (non-streaming).
3336
- *
3337
- * Internally consumes all stream messages and returns an aggregated
3338
- * {@link DroidResult} with the concatenated text, all messages, and
3339
- * final token usage.
3340
- *
3341
- * @param text - The user message text.
3342
- * @param options - Optional images/files to include.
3343
- * @returns Aggregated result with text, messages, and token usage.
3344
- */
3660
+ /** Consumes the stream and returns an aggregated {@link DroidResult}. */
3345
3661
  async send(text, options) {
3346
3662
  this._ensureNotClosed();
3347
3663
  const messages = [];
3348
3664
  let fullText = "";
3349
3665
  let lastTokenUsage = null;
3666
+ let firstError = null;
3667
+ let structuredOutput = null;
3668
+ let finalAssistantText = "";
3669
+ let turnCount = 0;
3670
+ const startedAt = Date.now();
3350
3671
  for await (const msg of this.stream(text, options)) {
3351
3672
  messages.push(msg);
3352
- if (msg.type === "assistant_text_delta") {
3673
+ if (msg.type === DroidMessageType.AssistantTextDelta) {
3353
3674
  fullText += msg.text;
3354
3675
  }
3355
- if (msg.type === "token_usage_update") {
3676
+ const assistantText = extractAssistantText(msg);
3677
+ if (assistantText) {
3678
+ finalAssistantText = assistantText;
3679
+ if (options?.outputFormat && fullText.length === 0) {
3680
+ fullText = assistantText;
3681
+ }
3682
+ }
3683
+ if (msg.type === DroidMessageType.TokenUsageUpdate) {
3356
3684
  lastTokenUsage = msg;
3357
3685
  }
3358
- if (msg.type === "turn_complete" && msg.tokenUsage) {
3359
- lastTokenUsage = msg.tokenUsage;
3686
+ if (msg.type === DroidMessageType.Error && firstError === null) {
3687
+ firstError = msg;
3688
+ }
3689
+ if (options?.outputFormat && structuredOutput === null) {
3690
+ const textToParse = finalAssistantText || fullText;
3691
+ if (textToParse) {
3692
+ structuredOutput = parseJsonObject(textToParse);
3693
+ }
3694
+ }
3695
+ if (msg.type === DroidMessageType.TurnComplete) {
3696
+ turnCount++;
3697
+ if (msg.tokenUsage) {
3698
+ lastTokenUsage = msg.tokenUsage;
3699
+ }
3360
3700
  }
3361
3701
  }
3362
3702
  return {
3703
+ sessionId: this._sessionId,
3363
3704
  text: fullText,
3364
3705
  messages,
3365
- tokenUsage: lastTokenUsage
3706
+ tokenUsage: lastTokenUsage,
3707
+ durationMs: Date.now() - startedAt,
3708
+ turnCount,
3709
+ error: firstError,
3710
+ structuredOutput,
3711
+ success: firstError === null
3366
3712
  };
3367
3713
  }
3368
- // ------------------------------------------------------------------
3369
- // Session control
3370
- // ------------------------------------------------------------------
3371
- /**
3372
- * Interrupt the current agent turn.
3373
- *
3374
- * Sends an interrupt request. The agent will stop after completing
3375
- * its current operation.
3376
- */
3377
3714
  async interrupt() {
3378
3715
  this._ensureNotClosed();
3379
3716
  await this._client.interruptSession();
3380
3717
  }
3381
- /**
3382
- * Close the session and release all resources.
3383
- *
3384
- * Closes the underlying transport and rejects any pending requests.
3385
- * After close, the session cannot be used.
3386
- */
3387
3718
  async close() {
3388
3719
  if (this._closed) {
3389
3720
  return;
3390
3721
  }
3391
3722
  this._closed = true;
3392
- await this._client.close();
3723
+ this._cleanupAbortSignal?.();
3724
+ this._cleanupAbortSignal = null;
3725
+ try {
3726
+ await this._client.close();
3727
+ } finally {
3728
+ const cleanups = this._cleanupCallbacks.splice(0);
3729
+ await Promise.all(cleanups.map((cleanup) => cleanup()));
3730
+ }
3393
3731
  }
3394
- // ------------------------------------------------------------------
3395
- // Settings
3396
- // ------------------------------------------------------------------
3397
- /**
3398
- * Update session settings (model, reasoning effort, autonomy, etc.).
3399
- *
3400
- * @param params - Partial settings to update.
3401
- */
3402
3732
  async updateSettings(params) {
3403
3733
  this._ensureNotClosed();
3404
3734
  return this._client.updateSessionSettings(params);
3405
3735
  }
3406
- // ------------------------------------------------------------------
3407
- // MCP methods
3408
- // ------------------------------------------------------------------
3409
- /**
3410
- * Add an MCP server to the session.
3411
- */
3736
+ async enterSpecMode(params = {}) {
3737
+ this._ensureNotClosed();
3738
+ return this._client.updateSessionSettings({
3739
+ interactionMode: "spec" /* Spec */,
3740
+ ...params
3741
+ });
3742
+ }
3412
3743
  async addMcpServer(params) {
3413
3744
  this._ensureNotClosed();
3414
3745
  return this._client.addMcpServer(params);
3415
3746
  }
3416
- /**
3417
- * Remove an MCP server from the session.
3418
- */
3419
3747
  async removeMcpServer(params) {
3420
3748
  this._ensureNotClosed();
3421
3749
  return this._client.removeMcpServer(params);
3422
3750
  }
3423
- /**
3424
- * Toggle an MCP server on or off.
3425
- */
3426
3751
  async toggleMcpServer(params) {
3427
3752
  this._ensureNotClosed();
3428
3753
  return this._client.toggleMcpServer(params);
3429
3754
  }
3430
- /**
3431
- * List MCP servers and their status.
3432
- */
3433
3755
  async listMcpServers() {
3434
3756
  this._ensureNotClosed();
3435
3757
  return this._client.listMcpServers();
3436
3758
  }
3437
- /**
3438
- * List available MCP tools.
3439
- */
3440
3759
  async listMcpTools() {
3441
3760
  this._ensureNotClosed();
3442
3761
  return this._client.listMcpTools();
3443
3762
  }
3444
- /**
3445
- * Authenticate an MCP server (OAuth flow).
3446
- */
3763
+ async listTools(params = {}) {
3764
+ this._ensureNotClosed();
3765
+ return this._client.listTools(params);
3766
+ }
3447
3767
  async authenticateMcpServer(params) {
3448
3768
  this._ensureNotClosed();
3449
3769
  return this._client.authenticateMcpServer(params);
3450
3770
  }
3451
- // ------------------------------------------------------------------
3452
- // Skills
3453
- // ------------------------------------------------------------------
3454
- /**
3455
- * List available skills.
3456
- */
3457
3771
  async listSkills() {
3458
3772
  this._ensureNotClosed();
3459
3773
  return this._client.listSkills();
3460
3774
  }
3461
- // ------------------------------------------------------------------
3462
- // Notification subscription
3463
- // ------------------------------------------------------------------
3464
- /**
3465
- * Register a callback for incoming notification messages.
3466
- *
3467
- * @param callback - Invoked with the notification object.
3468
- * @param filter - Optional filter to only receive specific notification types.
3469
- * @returns An unsubscribe function.
3470
- */
3775
+ async getRewindInfo(params) {
3776
+ this._ensureNotClosed();
3777
+ return this._client.getRewindInfo(params);
3778
+ }
3779
+ async executeRewind(params) {
3780
+ this._ensureNotClosed();
3781
+ return this._client.executeRewind(params);
3782
+ }
3783
+ async compactSession(params) {
3784
+ this._ensureNotClosed();
3785
+ return this._client.compactSession(params ?? {});
3786
+ }
3787
+ async forkSession() {
3788
+ this._ensureNotClosed();
3789
+ return this._client.forkSession();
3790
+ }
3791
+ async getContextStats() {
3792
+ this._ensureNotClosed();
3793
+ return this._client.getContextStats();
3794
+ }
3795
+ async renameSession(params) {
3796
+ this._ensureNotClosed();
3797
+ return this._client.renameSession(params);
3798
+ }
3471
3799
  onNotification(callback, filter) {
3472
3800
  return this._client.onNotification(callback, filter);
3473
3801
  }
3474
- // ------------------------------------------------------------------
3475
- // Internal
3476
- // ------------------------------------------------------------------
3477
3802
  _ensureNotClosed() {
3478
3803
  if (this._closed) {
3479
3804
  throw new ConnectionError(
@@ -3483,98 +3808,290 @@ var DroidSession = class {
3483
3808
  }
3484
3809
  };
3485
3810
  async function createSession(options = {}) {
3486
- let transport;
3487
- if (options.transport) {
3488
- transport = options.transport;
3489
- } else {
3490
- const transportOptions = {
3491
- execPath: options.execPath,
3492
- execArgs: options.execArgs,
3493
- cwd: options.cwd,
3494
- env: options.env
3811
+ const { client } = await createConfiguredClient(options);
3812
+ let cleanupInitAbortSignal = options.abortSignal?.aborted ? () => {
3813
+ } : wireAbortSignal(options.abortSignal, () => {
3814
+ void closeQuietly(client);
3815
+ });
3816
+ let sdkMcpServers;
3817
+ try {
3818
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
3819
+ const initParams = buildInitParams({
3820
+ ...options,
3821
+ mcpServers: sdkMcpServers.mcpServers
3822
+ });
3823
+ const initResult = await client.initializeSession(initParams);
3824
+ const session = new DroidSession(client, initResult.sessionId, initResult);
3825
+ session.addCleanup(sdkMcpServers.cleanup);
3826
+ cleanupInitAbortSignal();
3827
+ cleanupInitAbortSignal = () => {
3495
3828
  };
3496
- const processTransport = new ProcessTransport(transportOptions);
3497
- await processTransport.connect();
3498
- transport = processTransport;
3499
- }
3500
- const client = new DroidClient({ transport });
3501
- if (options.permissionHandler) {
3502
- client.setPermissionHandler(options.permissionHandler);
3503
- }
3504
- if (options.askUserHandler) {
3505
- client.setAskUserHandler(options.askUserHandler);
3829
+ session.setAbortSignalCleanup(
3830
+ wireAbortSignal(options.abortSignal, () => void session.close())
3831
+ );
3832
+ return session;
3833
+ } catch (error) {
3834
+ cleanupInitAbortSignal();
3835
+ await sdkMcpServers?.cleanup();
3836
+ await closeQuietly(client);
3837
+ throw error;
3506
3838
  }
3507
- const initParams = {
3508
- machineId: options.machineId ?? "default",
3509
- cwd: options.cwd ?? "."
3510
- };
3511
- if (options.modelId !== void 0) {
3512
- initParams.modelId = options.modelId;
3839
+ }
3840
+ async function resumeSession(sessionId, options = {}) {
3841
+ const { client } = await createConfiguredClient(options);
3842
+ let sdkMcpServers;
3843
+ try {
3844
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
3845
+ const loadParams = {
3846
+ sessionId,
3847
+ mcpServers: sdkMcpServers.mcpServers
3848
+ };
3849
+ const loadResult = await client.loadSession(loadParams);
3850
+ const session = new DroidSession(client, sessionId, loadResult);
3851
+ session.addCleanup(sdkMcpServers.cleanup);
3852
+ session.setAbortSignalCleanup(
3853
+ wireAbortSignal(options.abortSignal, () => void session.close())
3854
+ );
3855
+ return session;
3856
+ } catch (error) {
3857
+ await sdkMcpServers?.cleanup();
3858
+ await closeQuietly(client);
3859
+ throw error;
3513
3860
  }
3514
- if (options.autonomyLevel !== void 0) {
3515
- initParams.autonomyLevel = options.autonomyLevel;
3861
+ }
3862
+
3863
+ // src/run.ts
3864
+ async function run(text, options = {}) {
3865
+ const session = await createSession(options);
3866
+ try {
3867
+ return await session.send(text, options);
3868
+ } finally {
3869
+ await session.close();
3516
3870
  }
3517
- if (options.interactionMode !== void 0) {
3518
- initParams.interactionMode = options.interactionMode;
3871
+ }
3872
+
3873
+ // src/session-discovery.ts
3874
+ var fs = __toESM(require("fs"), 1);
3875
+ var os = __toESM(require("os"), 1);
3876
+ var path = __toESM(require("path"), 1);
3877
+ var FAVORITES_FILE = ".favorites";
3878
+ var SESSION_EXTENSION = ".jsonl";
3879
+ var SETTINGS_SUFFIX = ".settings.json";
3880
+ var MISSION_TAG_PREFIX = "mission:";
3881
+ var MISSION_ID_METADATA_KEY = "missionId";
3882
+ var DECOMP_SESSION_TYPE_TAG = "decompSessionType";
3883
+ var DECOMP_SESSION_TYPE_METADATA_KEY = "value";
3884
+ var LF = 10;
3885
+ var CR = 13;
3886
+ var SPACE = 32;
3887
+ var TAB = 9;
3888
+ var PARSE_OVERSAMPLE = 20;
3889
+ function readFileBuffer(filePath) {
3890
+ try {
3891
+ return fs.readFileSync(filePath);
3892
+ } catch {
3893
+ return null;
3519
3894
  }
3520
- if (options.reasoningEffort !== void 0) {
3521
- initParams.reasoningEffort = options.reasoningEffort;
3895
+ }
3896
+ function parseJsonBuffer(buf) {
3897
+ try {
3898
+ return JSON.parse(buf.toString("utf-8"));
3899
+ } catch {
3900
+ return null;
3522
3901
  }
3523
- if (options.mcpServers !== void 0) {
3524
- initParams.mcpServers = options.mcpServers;
3902
+ }
3903
+ function scanBufferForLines(buf) {
3904
+ let nonEmptyLineCount = 0;
3905
+ let firstLineEnd = -1;
3906
+ let currentLineHasContent = false;
3907
+ for (let i = 0; i < buf.length; i++) {
3908
+ const ch = buf[i];
3909
+ if (ch === LF) {
3910
+ if (currentLineHasContent) nonEmptyLineCount++;
3911
+ if (firstLineEnd === -1) firstLineEnd = i;
3912
+ currentLineHasContent = false;
3913
+ } else if (ch !== CR && ch !== SPACE && ch !== TAB) {
3914
+ currentLineHasContent = true;
3915
+ }
3525
3916
  }
3526
- if (options.enabledToolIds !== void 0) {
3527
- initParams.enabledToolIds = options.enabledToolIds;
3917
+ if (currentLineHasContent) nonEmptyLineCount++;
3918
+ const end = firstLineEnd === -1 ? buf.length : firstLineEnd > 0 && buf[firstLineEnd - 1] === CR ? firstLineEnd - 1 : firstLineEnd;
3919
+ return {
3920
+ firstLine: buf.subarray(0, end),
3921
+ nonEmptyLineCount
3922
+ };
3923
+ }
3924
+ function loadFavorites(sessionsDir) {
3925
+ const buf = readFileBuffer(path.join(sessionsDir, FAVORITES_FILE));
3926
+ if (!buf) return /* @__PURE__ */ new Set();
3927
+ const parsed = parseJsonBuffer(buf);
3928
+ if (!Array.isArray(parsed)) return /* @__PURE__ */ new Set();
3929
+ return new Set(parsed.filter((id) => typeof id === "string"));
3930
+ }
3931
+ function loadSettingsFile(directory, sessionId) {
3932
+ const buf = readFileBuffer(
3933
+ path.join(directory, `${sessionId}${SETTINGS_SUFFIX}`)
3934
+ );
3935
+ if (!buf) return null;
3936
+ const parsed = parseJsonBuffer(buf);
3937
+ if (parsed === null) return null;
3938
+ const result = SessionSettingsFileSchema.safeParse(parsed);
3939
+ return result.success ? result.data : null;
3940
+ }
3941
+ function getMissionMetadataFromTags(settings) {
3942
+ if (!settings?.tags) return {};
3943
+ const missionTag = settings.tags.find(
3944
+ (tag) => tag.name.startsWith(MISSION_TAG_PREFIX)
3945
+ );
3946
+ const roleTag = settings.tags.find(
3947
+ (tag) => tag.name === DECOMP_SESSION_TYPE_TAG
3948
+ );
3949
+ return {
3950
+ decompMissionId: missionTag?.metadata?.[MISSION_ID_METADATA_KEY],
3951
+ decompSessionType: roleTag?.metadata?.[DECOMP_SESSION_TYPE_METADATA_KEY]
3952
+ };
3953
+ }
3954
+ function parseSessionFile(candidate, ctx) {
3955
+ const buf = readFileBuffer(candidate.sessionPath);
3956
+ if (!buf) return null;
3957
+ const scanned = scanBufferForLines(buf);
3958
+ const firstParsed = parseJsonBuffer(scanned.firstLine);
3959
+ if (firstParsed === null) return null;
3960
+ const firstResult = SessionStartEventSchema.safeParse(firstParsed);
3961
+ if (!firstResult.success) return null;
3962
+ const summary = firstResult.data;
3963
+ if (ctx.requiredCwd !== void 0 && (summary.cwd === void 0 || path.resolve(summary.cwd) !== ctx.requiredCwd)) {
3964
+ return null;
3528
3965
  }
3966
+ const settingsName = `${candidate.sessionId}${SETTINGS_SUFFIX}`;
3967
+ const settings = candidate.siblingNames.has(settingsName) ? loadSettingsFile(candidate.directory, candidate.sessionId) : null;
3968
+ if (settings?.archivedAt) return null;
3969
+ const tagMeta = getMissionMetadataFromTags(settings);
3970
+ const decompSessionType = summary.decompSessionType ?? SessionStartEventSchema.shape.decompSessionType.safeParse(
3971
+ tagMeta.decompSessionType
3972
+ ).data;
3973
+ const messageCount = Math.max(0, scanned.nonEmptyLineCount - 1);
3974
+ return {
3975
+ id: candidate.sessionId,
3976
+ title: summary.title ?? "",
3977
+ sessionTitle: summary.sessionTitle,
3978
+ owner: summary.owner ?? "",
3979
+ messageCount,
3980
+ modifiedTime: candidate.stats.mtime,
3981
+ createdTime: candidate.stats.birthtime || candidate.stats.ctime,
3982
+ isFavorite: ctx.favorites.has(candidate.sessionId),
3983
+ cwd: summary.cwd,
3984
+ decompSessionType,
3985
+ decompMissionId: tagMeta.decompMissionId ?? summary.decompMissionId
3986
+ };
3987
+ }
3988
+ function readDirEntries(directory) {
3529
3989
  try {
3530
- const initResult = await client.initializeSession(
3531
- initParams
3532
- );
3533
- return new DroidSession(client, initResult.sessionId, initResult);
3534
- } catch (error) {
3990
+ return fs.readdirSync(directory, { withFileTypes: true });
3991
+ } catch {
3992
+ return [];
3993
+ }
3994
+ }
3995
+ function collectCandidates(directory, entries) {
3996
+ const siblingNames = new Set(entries.map((e) => e.name));
3997
+ const candidates = [];
3998
+ for (const entry of entries) {
3999
+ if (entry.isDirectory()) continue;
4000
+ if (!entry.name.endsWith(SESSION_EXTENSION)) continue;
4001
+ const sessionPath = path.join(directory, entry.name);
4002
+ let stats;
3535
4003
  try {
3536
- await client.close();
4004
+ stats = fs.statSync(sessionPath);
3537
4005
  } catch {
4006
+ continue;
3538
4007
  }
3539
- throw error;
4008
+ candidates.push({
4009
+ sessionId: entry.name.slice(0, -SESSION_EXTENSION.length),
4010
+ sessionPath,
4011
+ directory,
4012
+ siblingNames,
4013
+ stats
4014
+ });
3540
4015
  }
4016
+ return candidates;
3541
4017
  }
3542
- async function resumeSession(sessionId, options = {}) {
3543
- let transport;
3544
- if (options.transport) {
3545
- transport = options.transport;
3546
- } else {
3547
- const transportOptions = {
3548
- execPath: options.execPath,
3549
- execArgs: options.execArgs,
3550
- cwd: options.cwd,
3551
- env: options.env
3552
- };
3553
- const processTransport = new ProcessTransport(transportOptions);
3554
- await processTransport.connect();
3555
- transport = processTransport;
4018
+ function parseUpTo(candidates, ctx, limit) {
4019
+ const out = [];
4020
+ for (const candidate of candidates) {
4021
+ if (limit !== void 0 && out.length >= limit) break;
4022
+ const metadata = parseSessionFile(candidate, ctx);
4023
+ if (metadata) out.push(metadata);
3556
4024
  }
3557
- const client = new DroidClient({ transport });
3558
- if (options.permissionHandler) {
3559
- client.setPermissionHandler(options.permissionHandler);
3560
- }
3561
- if (options.askUserHandler) {
3562
- client.setAskUserHandler(options.askUserHandler);
4025
+ return out;
4026
+ }
4027
+ function sanitizePathToDirectoryName(cwd) {
4028
+ let expandedPath = cwd;
4029
+ if (cwd.startsWith("~/") || cwd === "~") {
4030
+ expandedPath = path.join(os.homedir(), cwd.slice(1));
3563
4031
  }
3564
- const loadParams = {
3565
- sessionId,
3566
- mcpServers: options.mcpServers
3567
- };
4032
+ const absolutePath = path.resolve(expandedPath);
4033
+ let canonicalPath = absolutePath;
3568
4034
  try {
3569
- const loadResult = await client.loadSession(loadParams);
3570
- return new DroidSession(client, sessionId, loadResult);
3571
- } catch (error) {
3572
- try {
3573
- await client.close();
3574
- } catch {
4035
+ canonicalPath = fs.realpathSync(absolutePath);
4036
+ } catch {
4037
+ canonicalPath = absolutePath;
4038
+ }
4039
+ const normalized = canonicalPath.replace(/[\\/]+$/, "");
4040
+ if (process.platform === "win32") {
4041
+ return `-${normalized.replace(/^([A-Z]):/i, "$1").replace(/[\\/]+/g, "-")}`;
4042
+ }
4043
+ return `-${normalized.replace(/^\/+/, "").replace(/\/+/g, "-")}`;
4044
+ }
4045
+ function getDefaultSessionsDir() {
4046
+ return path.join(os.homedir(), ".factory", "sessions");
4047
+ }
4048
+ async function listSessions(options = {}) {
4049
+ const sessionsDir = options.sessionsDir ?? getDefaultSessionsDir();
4050
+ const favorites = loadFavorites(sessionsDir);
4051
+ const rootEntries = readDirEntries(sessionsDir);
4052
+ const legacyCandidates = collectCandidates(sessionsDir, rootEntries);
4053
+ const projectCandidates = [];
4054
+ let requiredCwd;
4055
+ if (options.fetchOutsideCWD) {
4056
+ for (const entry of rootEntries) {
4057
+ if (!entry.isDirectory()) continue;
4058
+ if (!entry.name.startsWith("-")) continue;
4059
+ const dir = path.join(sessionsDir, entry.name);
4060
+ projectCandidates.push(...collectCandidates(dir, readDirEntries(dir)));
3575
4061
  }
3576
- throw error;
4062
+ } else {
4063
+ const normalizedCwd = path.resolve(options.cwd ?? process.cwd());
4064
+ requiredCwd = normalizedCwd;
4065
+ const projectDir = path.join(
4066
+ sessionsDir,
4067
+ sanitizePathToDirectoryName(normalizedCwd)
4068
+ );
4069
+ projectCandidates.push(
4070
+ ...collectCandidates(projectDir, readDirEntries(projectDir))
4071
+ );
4072
+ }
4073
+ const byMtimeDesc = (a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime();
4074
+ projectCandidates.sort(byMtimeDesc);
4075
+ legacyCandidates.sort(byMtimeDesc);
4076
+ const parseLimit = options.numSessions !== void 0 && options.numSessions >= 0 ? options.numSessions + PARSE_OVERSAMPLE : void 0;
4077
+ const ctx = { favorites };
4078
+ const legacyCtx = requiredCwd !== void 0 ? { favorites, requiredCwd } : ctx;
4079
+ const projectSessions = parseUpTo(projectCandidates, ctx, parseLimit);
4080
+ const legacySessions = parseUpTo(legacyCandidates, legacyCtx, parseLimit);
4081
+ const byId = /* @__PURE__ */ new Map();
4082
+ for (const session of [...projectSessions, ...legacySessions]) {
4083
+ const existing = byId.get(session.id);
4084
+ if (!existing || session.modifiedTime.getTime() > existing.modifiedTime.getTime()) {
4085
+ byId.set(session.id, session);
4086
+ }
4087
+ }
4088
+ const sorted = Array.from(byId.values()).sort(
4089
+ (a, b) => b.modifiedTime.getTime() - a.modifiedTime.getTime()
4090
+ );
4091
+ if (options.numSessions !== void 0 && options.numSessions >= 0) {
4092
+ return sorted.slice(0, options.numSessions);
3577
4093
  }
4094
+ return sorted;
3578
4095
  }
3579
4096
  // Annotate the CommonJS export names for ESM import in node:
3580
4097
  0 && (module.exports = {
@@ -3607,6 +4124,7 @@ async function resumeSession(sessionId, options = {}) {
3607
4124
  BaseRequestSchema,
3608
4125
  BaseResponseFailureSchema,
3609
4126
  BaseResponseSuccessSchema,
4127
+ COMPACTION_TIMEOUT,
3610
4128
  CancelMcpAuthRequestParamsSchema,
3611
4129
  CancelMcpAuthRequestSchema,
3612
4130
  CancelMcpAuthResponseSchema,
@@ -3617,8 +4135,14 @@ async function resumeSession(sessionId, options = {}) {
3617
4135
  ClearMcpAuthResultSchema,
3618
4136
  CliRequestOrNotificationSchema,
3619
4137
  ClientRequestSchema,
4138
+ CompactSessionRequestParamsSchema,
4139
+ CompactSessionRequestSchema,
4140
+ CompactSessionResponseSchema,
4141
+ CompactSessionResultSchema,
3620
4142
  ConnectionError,
3621
4143
  ContentBlockSchema,
4144
+ ContextStatsAccuracy,
4145
+ ContextStatsSchema,
3622
4146
  CreateMessageNotificationSchema,
3623
4147
  CreateToolConfirmationDetailsSchema,
3624
4148
  DEFAULT_REQUEST_TIMEOUT,
@@ -3632,22 +4156,42 @@ async function resumeSession(sessionId, options = {}) {
3632
4156
  DroidClientMethod,
3633
4157
  DroidErrorType,
3634
4158
  DroidInteractionMode,
4159
+ DroidMessageType,
3635
4160
  DroidServerMethod,
3636
4161
  DroidSession,
3637
4162
  DroidWorkingState,
3638
4163
  DroidWorkingStateChangedNotificationSchema,
3639
4164
  EditToolConfirmationDetailsSchema,
4165
+ EmptyResultSchema,
3640
4166
  ErrorDetailSchema,
3641
4167
  ErrorNotificationSchema,
4168
+ ExecToolInfoSchema,
4169
+ ExecuteRewindRequestParamsSchema,
4170
+ ExecuteRewindRequestSchema,
4171
+ ExecuteRewindResponseSchema,
4172
+ ExecuteRewindResultSchema,
3642
4173
  ExecuteToolConfirmationDetailsSchema,
3643
4174
  ExitSpecModeConfirmationDetailsSchema,
3644
4175
  FACTORY_CLIENT_HEADER,
3645
4176
  FACTORY_CLIENT_VERSION,
3646
4177
  FACTORY_PROTOCOL_VERSION,
4178
+ FactoryDroidMessageRole,
3647
4179
  FactoryDroidMessageSchema,
3648
4180
  FeatureStatus,
3649
4181
  FeatureSuccessState,
3650
4182
  FeatureSuccessStateSchema,
4183
+ ForkSessionRequestParamsSchema,
4184
+ ForkSessionRequestSchema,
4185
+ ForkSessionResponseSchema,
4186
+ ForkSessionResultSchema,
4187
+ GetContextStatsRequestParamsSchema,
4188
+ GetContextStatsRequestSchema,
4189
+ GetContextStatsResponseSchema,
4190
+ GetContextStatsResultSchema,
4191
+ GetRewindInfoRequestParamsSchema,
4192
+ GetRewindInfoRequestSchema,
4193
+ GetRewindInfoResponseSchema,
4194
+ GetRewindInfoResultSchema,
3651
4195
  GitRepoInfoSchema,
3652
4196
  HandoffItemsDismissedEntrySchema,
3653
4197
  HandoffSchema,
@@ -3665,6 +4209,8 @@ async function resumeSession(sessionId, options = {}) {
3665
4209
  InterruptSessionResultSchema,
3666
4210
  IssueSeverity,
3667
4211
  JSONRPC_VERSION,
4212
+ JsonArraySchema,
4213
+ JsonObjectSchema,
3668
4214
  JsonRpcEnvelopeSchema,
3669
4215
  JsonRpcErrorCode,
3670
4216
  JsonRpcErrorSchema,
@@ -3675,6 +4221,7 @@ async function resumeSession(sessionId, options = {}) {
3675
4221
  JsonRpcResponseFailureSchema,
3676
4222
  JsonRpcResponseSchema,
3677
4223
  JsonRpcResponseSuccessSchema,
4224
+ JsonValueSchema,
3678
4225
  KillWorkerSessionRequestParamsSchema,
3679
4226
  KillWorkerSessionRequestSchema,
3680
4227
  KillWorkerSessionResponseSchema,
@@ -3696,6 +4243,10 @@ async function resumeSession(sessionId, options = {}) {
3696
4243
  ListSkillsRequestSchema,
3697
4244
  ListSkillsResponseSchema,
3698
4245
  ListSkillsResultSchema,
4246
+ ListToolsRequestParamsSchema,
4247
+ ListToolsRequestSchema,
4248
+ ListToolsResponseSchema,
4249
+ ListToolsResultSchema,
3699
4250
  LoadSessionRequestParamsSchema,
3700
4251
  LoadSessionRequestSchema,
3701
4252
  LoadSessionResponseSchema,
@@ -3733,6 +4284,8 @@ async function resumeSession(sessionId, options = {}) {
3733
4284
  MissionWorkerCompletedNotificationSchema,
3734
4285
  MissionWorkerStartedNotificationSchema,
3735
4286
  ModelProvider,
4287
+ OutputFormatSchema,
4288
+ OutputFormatType,
3736
4289
  PermissionResolvedNotificationSchema,
3737
4290
  ProcessExitError,
3738
4291
  ProcessTransport,
@@ -3741,26 +4294,40 @@ async function resumeSession(sessionId, options = {}) {
3741
4294
  ProposeMissionConfirmationDetailsSchema,
3742
4295
  ProtocolEngine,
3743
4296
  ProtocolError,
4297
+ REWIND_TIMEOUT,
3744
4298
  ReasoningEffort,
3745
4299
  RedactedThinkingBlockSchema,
3746
4300
  RemoveMcpServerRequestParamsSchema,
3747
4301
  RemoveMcpServerRequestSchema,
3748
4302
  RemoveMcpServerResponseSchema,
3749
4303
  RemoveMcpServerResultSchema,
4304
+ RenameSessionRequestParamsSchema,
4305
+ RenameSessionRequestSchema,
4306
+ RenameSessionResponseSchema,
4307
+ RenameSessionResultSchema,
3750
4308
  RequestPermissionRequestParamsSchema,
3751
4309
  RequestPermissionRequestSchema,
3752
4310
  RequestPermissionResponseSchema,
3753
4311
  RequestPermissionResultSchema,
4312
+ RewindEvictedFileSchema,
4313
+ RewindFileCreationSchema,
4314
+ RewindFileSnapshotSchema,
4315
+ SDK_TAG,
4316
+ SDK_VERSION,
3754
4317
  SESSION_INIT_TIMEOUT,
4318
+ SdkMcpServer,
3755
4319
  SessionError,
4320
+ SessionMetadataSchema,
3756
4321
  SessionNotFoundError,
3757
4322
  SessionNotificationParamsSchema,
3758
4323
  SessionNotificationPayloadSchema,
3759
4324
  SessionNotificationSchema,
3760
4325
  SessionNotificationSchemaList,
3761
4326
  SessionNotificationType,
4327
+ SessionSettingsFileSchema,
3762
4328
  SessionSettingsSchema,
3763
4329
  SessionSourceSchema,
4330
+ SessionStartEventSchema,
3764
4331
  SessionTagSchema,
3765
4332
  SessionTitleUpdatedNotificationSchema,
3766
4333
  SessionTokenUsageChangedNotificationSchema,
@@ -3784,6 +4351,7 @@ async function resumeSession(sessionId, options = {}) {
3784
4351
  SubmitMcpAuthCodeRequestSchema,
3785
4352
  SubmitMcpAuthCodeResponseSchema,
3786
4353
  SubmitMcpAuthCodeResultSchema,
4354
+ SuccessResultSchema,
3787
4355
  TestCaseSchema,
3788
4356
  TestFileSchema,
3789
4357
  TestsSchema,
@@ -3809,6 +4377,7 @@ async function resumeSession(sessionId, options = {}) {
3809
4377
  ToolProgressUpdateSchema,
3810
4378
  ToolResultBlockSchema,
3811
4379
  ToolResultNotificationSchema,
4380
+ ToolSelectionOverridesSchema,
3812
4381
  ToolUseBlockSchema,
3813
4382
  ToolUseSchema,
3814
4383
  TraceContextMetaSchema,
@@ -3825,8 +4394,12 @@ async function resumeSession(sessionId, options = {}) {
3825
4394
  WorkerStartedEntrySchema,
3826
4395
  WorkerStateInfoSchema,
3827
4396
  convertNotificationToStreamMessage,
4397
+ createSdkMcpServer,
3828
4398
  createSession,
4399
+ listSessions,
3829
4400
  query,
3830
- resumeSession
4401
+ resumeSession,
4402
+ run,
4403
+ tool
3831
4404
  });
3832
4405
  //# sourceMappingURL=index.cjs.map