@factory/droid-sdk 0.2.0 → 0.4.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 (41) hide show
  1. package/README.md +214 -82
  2. package/dist/index.cjs +2345 -692
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +2570 -232
  5. package/dist/index.d.ts +2570 -232
  6. package/dist/index.js +2298 -697
  7. package/dist/index.js.map +1 -1
  8. package/docs/daemon-usage-guide.md +544 -0
  9. package/docs/sdk-usage-guide.md +748 -0
  10. package/examples/abort-session-stream.ts +23 -56
  11. package/examples/daemon-multi-session.ts +67 -0
  12. package/examples/droid-dev-structured-output.ts +5 -5
  13. package/examples/fork-session.ts +33 -7
  14. package/examples/hook-execution.ts +68 -0
  15. package/examples/init-metadata.ts +14 -66
  16. package/examples/interrupt-session.ts +23 -55
  17. package/examples/list-sessions.ts +9 -55
  18. package/examples/multi-turn-session.ts +27 -54
  19. package/examples/permission-handler.ts +27 -84
  20. package/examples/readme-structured-output.ts +26 -0
  21. package/examples/result-metadata.ts +2 -1
  22. package/examples/run.ts +2 -1
  23. package/examples/sdk-mcp-tool.ts +14 -8
  24. package/examples/session-stream.ts +57 -0
  25. package/examples/spec-mode-new-session.ts +39 -99
  26. package/examples/spec-mode-same-session.ts +50 -111
  27. package/examples/structured-output.ts +17 -10
  28. package/examples/test-compact.ts +9 -4
  29. package/examples/test-rewind.ts +49 -117
  30. package/examples/tool-controls.ts +23 -55
  31. package/package.json +3 -1
  32. package/docs/examples/init-metadata.md +0 -79
  33. package/docs/examples/list-sessions.md +0 -64
  34. package/docs/examples/multi-turn-session.md +0 -77
  35. package/docs/examples/one-shot-query.md +0 -73
  36. package/docs/examples/permission-handler.md +0 -102
  37. package/docs/examples/run.md +0 -52
  38. package/docs/examples/spec-mode.md +0 -101
  39. package/docs/examples/tool-controls.md +0 -90
  40. package/docs/typescript-sdk-reference.md +0 -372
  41. package/examples/simple-query.ts +0 -53
package/dist/index.cjs CHANGED
@@ -46,6 +46,7 @@ __export(index_exports, {
46
46
  AskUserRequestSchema: () => AskUserRequestSchema,
47
47
  AskUserResponseSchema: () => AskUserResponseSchema,
48
48
  AskUserResultSchema: () => AskUserResultSchema,
49
+ AssistantTextCompleteNotificationSchema: () => AssistantTextCompleteNotificationSchema,
49
50
  AssistantTextDeltaNotificationSchema: () => AssistantTextDeltaNotificationSchema,
50
51
  AuthenticateMcpServerRequestParamsSchema: () => AuthenticateMcpServerRequestParamsSchema,
51
52
  AuthenticateMcpServerRequestSchema: () => AuthenticateMcpServerRequestSchema,
@@ -70,17 +71,30 @@ __export(index_exports, {
70
71
  ClearMcpAuthResultSchema: () => ClearMcpAuthResultSchema,
71
72
  CliRequestOrNotificationSchema: () => CliRequestOrNotificationSchema,
72
73
  ClientRequestSchema: () => ClientRequestSchema,
74
+ CloseSessionRequestParamsSchema: () => CloseSessionRequestParamsSchema,
75
+ CloseSessionRequestSchema: () => CloseSessionRequestSchema,
76
+ CloseSessionResponseSchema: () => CloseSessionResponseSchema,
77
+ CloseSessionResultSchema: () => CloseSessionResultSchema,
73
78
  CompactSessionRequestParamsSchema: () => CompactSessionRequestParamsSchema,
74
79
  CompactSessionRequestSchema: () => CompactSessionRequestSchema,
75
80
  CompactSessionResponseSchema: () => CompactSessionResponseSchema,
76
81
  CompactSessionResultSchema: () => CompactSessionResultSchema,
82
+ ComputerListResponseSchema: () => ComputerListResponseSchema,
83
+ ComputerMetricSchema: () => ComputerMetricSchema,
84
+ ComputerMetricsResponseSchema: () => ComputerMetricsResponseSchema,
85
+ ComputerSchema: () => ComputerSchema,
77
86
  ConnectionError: () => ConnectionError,
78
87
  ContentBlockSchema: () => ContentBlockSchema,
88
+ ContextBreakdownCategorySchema: () => ContextBreakdownCategorySchema,
89
+ ContextBreakdownResultSchema: () => ContextBreakdownResultSchema,
79
90
  ContextStatsAccuracy: () => ContextStatsAccuracy,
80
91
  ContextStatsSchema: () => ContextStatsSchema,
81
92
  CreateMessageNotificationSchema: () => CreateMessageNotificationSchema,
82
93
  CreateToolConfirmationDetailsSchema: () => CreateToolConfirmationDetailsSchema,
83
94
  DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
95
+ DaemonClient: () => DaemonClient,
96
+ DaemonConnection: () => DaemonConnection,
97
+ DaemonSession: () => DaemonSession,
84
98
  DecompSessionType: () => DecompSessionType,
85
99
  DiscoveredIssueSchema: () => DiscoveredIssueSchema,
86
100
  DismissalRecordSchema: () => DismissalRecordSchema,
@@ -90,6 +104,10 @@ __export(index_exports, {
90
104
  DroidClient: () => DroidClient,
91
105
  DroidClientMethod: () => DroidClientMethod,
92
106
  DroidErrorType: () => DroidErrorType,
107
+ DroidHookEventSchema: () => DroidHookEventSchema,
108
+ DroidHookExecutionResultSchema: () => DroidHookExecutionResultSchema,
109
+ DroidHookOutputSchema: () => DroidHookOutputSchema,
110
+ DroidHookSpecificOutputSchema: () => DroidHookSpecificOutputSchema,
93
111
  DroidInteractionMode: () => DroidInteractionMode,
94
112
  DroidMessageType: () => DroidMessageType,
95
113
  DroidServerMethod: () => DroidServerMethod,
@@ -130,6 +148,10 @@ __export(index_exports, {
130
148
  GitRepoInfoSchema: () => GitRepoInfoSchema,
131
149
  HandoffItemsDismissedEntrySchema: () => HandoffItemsDismissedEntrySchema,
132
150
  HandoffSchema: () => HandoffSchema,
151
+ HookCommandSchema: () => HookCommandSchema,
152
+ HookExecutionCompletedNotificationSchema: () => HookExecutionCompletedNotificationSchema,
153
+ HookExecutionStartedNotificationSchema: () => HookExecutionStartedNotificationSchema,
154
+ HookResultSchema: () => HookResultSchema,
133
155
  HttpHeaderSchema: () => HttpHeaderSchema,
134
156
  HttpMcpConfigSchema: () => HttpMcpConfigSchema,
135
157
  ImageBlockSchema: () => ImageBlockSchema,
@@ -187,6 +209,10 @@ __export(index_exports, {
187
209
  LoadSessionResponseSchema: () => LoadSessionResponseSchema,
188
210
  LoadSessionResultSchema: () => LoadSessionResultSchema,
189
211
  MCP_AUTH_TIMEOUT: () => MCP_AUTH_TIMEOUT,
212
+ MachineTemplateBuildStatusSchema: () => MachineTemplateBuildStatusSchema,
213
+ MachineTemplateListResponseSchema: () => MachineTemplateListResponseSchema,
214
+ MachineTemplateSchema: () => MachineTemplateSchema,
215
+ MachineType: () => MachineType,
190
216
  McpAuthCompletedNotificationSchema: () => McpAuthCompletedNotificationSchema,
191
217
  McpAuthOutcome: () => McpAuthOutcome,
192
218
  McpAuthRequiredNotificationSchema: () => McpAuthRequiredNotificationSchema,
@@ -232,6 +258,9 @@ __export(index_exports, {
232
258
  REWIND_TIMEOUT: () => REWIND_TIMEOUT,
233
259
  ReasoningEffort: () => ReasoningEffort,
234
260
  RedactedThinkingBlockSchema: () => RedactedThinkingBlockSchema,
261
+ RefreshComputerResponseSchema: () => RefreshComputerResponseSchema,
262
+ RemoteSessionListResponseSchema: () => RemoteSessionListResponseSchema,
263
+ RemoteSessionSchema: () => RemoteSessionSchema,
235
264
  RemoveMcpServerRequestParamsSchema: () => RemoveMcpServerRequestParamsSchema,
236
265
  RemoveMcpServerRequestSchema: () => RemoveMcpServerRequestSchema,
237
266
  RemoveMcpServerResponseSchema: () => RemoveMcpServerResponseSchema,
@@ -251,6 +280,7 @@ __export(index_exports, {
251
280
  SDK_VERSION: () => SDK_VERSION,
252
281
  SESSION_INIT_TIMEOUT: () => SESSION_INIT_TIMEOUT,
253
282
  SdkMcpServer: () => SdkMcpServer,
283
+ ServerRequestHandlerType: () => ServerRequestHandlerType,
254
284
  SessionError: () => SessionError,
255
285
  SessionMetadataSchema: () => SessionMetadataSchema,
256
286
  SessionNotFoundError: () => SessionNotFoundError,
@@ -278,6 +308,8 @@ __export(index_exports, {
278
308
  StartMissionRunConfirmationDetailsSchema: () => StartMissionRunConfirmationDetailsSchema,
279
309
  StdioMcpConfigSchema: () => StdioMcpConfigSchema,
280
310
  StreamStateTracker: () => StreamStateTracker,
311
+ StructuredOutputErrorSchema: () => StructuredOutputErrorSchema,
312
+ StructuredOutputNotificationSchema: () => StructuredOutputNotificationSchema,
281
313
  SubmitBugReportRequestParamsSchema: () => SubmitBugReportRequestParamsSchema,
282
314
  SubmitBugReportRequestSchema: () => SubmitBugReportRequestSchema,
283
315
  SubmitBugReportResponseSchema: () => SubmitBugReportResponseSchema,
@@ -292,6 +324,7 @@ __export(index_exports, {
292
324
  TestsSchema: () => TestsSchema,
293
325
  TextBlockSchema: () => TextBlockSchema,
294
326
  ThinkingBlockSchema: () => ThinkingBlockSchema,
327
+ ThinkingTextCompleteNotificationSchema: () => ThinkingTextCompleteNotificationSchema,
295
328
  ThinkingTextDeltaNotificationSchema: () => ThinkingTextDeltaNotificationSchema,
296
329
  TimeoutError: () => TimeoutError,
297
330
  ToggleMcpServerRequestParamsSchema: () => ToggleMcpServerRequestParamsSchema,
@@ -303,6 +336,7 @@ __export(index_exports, {
303
336
  ToggleMcpToolResponseSchema: () => ToggleMcpToolResponseSchema,
304
337
  ToggleMcpToolResultSchema: () => ToggleMcpToolResultSchema,
305
338
  TokenUsageSchema: () => TokenUsageSchema,
339
+ ToolCallNotificationSchema: () => ToolCallNotificationSchema,
306
340
  ToolConfirmationDetailsSchema: () => ToolConfirmationDetailsSchema,
307
341
  ToolConfirmationInfoSchema: () => ToolConfirmationInfoSchema,
308
342
  ToolConfirmationListItemSchema: () => ToolConfirmationListItemSchema,
@@ -322,20 +356,38 @@ __export(index_exports, {
322
356
  UpdateSessionSettingsResultSchema: () => UpdateSessionSettingsResultSchema,
323
357
  VerificationCommandSchema: () => VerificationCommandSchema,
324
358
  VerificationSchema: () => VerificationSchema,
359
+ WebSocketTransport: () => WebSocketTransport,
325
360
  WorkerCompletedEntrySchema: () => WorkerCompletedEntrySchema,
326
361
  WorkerFailedEntrySchema: () => WorkerFailedEntrySchema,
327
362
  WorkerPausedEntrySchema: () => WorkerPausedEntrySchema,
328
363
  WorkerSelectedFeatureEntrySchema: () => WorkerSelectedFeatureEntrySchema,
329
364
  WorkerStartedEntrySchema: () => WorkerStartedEntrySchema,
330
365
  WorkerStateInfoSchema: () => WorkerStateInfoSchema,
366
+ connectDaemon: () => connectDaemon,
331
367
  convertNotificationToStreamMessage: () => convertNotificationToStreamMessage,
368
+ createComputer: () => createComputer,
369
+ createResponseSchema: () => createResponseSchema,
332
370
  createSdkMcpServer: () => createSdkMcpServer,
333
371
  createSession: () => createSession,
372
+ deleteComputer: () => deleteComputer,
373
+ dispatchNotification: () => dispatchNotification,
374
+ ensureLocalDaemon: () => ensureLocalDaemon,
375
+ getComputer: () => getComputer,
376
+ getComputerByName: () => getComputerByName,
377
+ getComputerMetrics: () => getComputerMetrics,
378
+ getMachineTemplate: () => getMachineTemplate,
379
+ listComputers: () => listComputers,
380
+ listMachineTemplates: () => listMachineTemplates,
381
+ listRemoteSessions: () => listRemoteSessions,
334
382
  listSessions: () => listSessions,
335
- query: () => query,
383
+ refreshComputer: () => refreshComputer,
384
+ resolveWebSocketUrl: () => resolveWebSocketUrl,
385
+ restartComputer: () => restartComputer,
336
386
  resumeSession: () => resumeSession,
387
+ retryInstallDeps: () => retryInstallDeps,
337
388
  run: () => run,
338
- tool: () => tool
389
+ tool: () => tool,
390
+ updateComputer: () => updateComputer
339
391
  });
340
392
  module.exports = __toCommonJS(index_exports);
341
393
 
@@ -344,6 +396,7 @@ var DroidServerMethod = /* @__PURE__ */ ((DroidServerMethod2) => {
344
396
  DroidServerMethod2["INITIALIZE_SESSION"] = "droid.initialize_session";
345
397
  DroidServerMethod2["LOAD_SESSION"] = "droid.load_session";
346
398
  DroidServerMethod2["ADD_USER_MESSAGE"] = "droid.add_user_message";
399
+ DroidServerMethod2["CLOSE_SESSION"] = "droid.close_session";
347
400
  DroidServerMethod2["INTERRUPT_SESSION"] = "droid.interrupt_session";
348
401
  DroidServerMethod2["KILL_WORKER_SESSION"] = "droid.kill_worker_session";
349
402
  DroidServerMethod2["UPDATE_SESSION_SETTINGS"] = "droid.update_session_settings";
@@ -386,7 +439,10 @@ var SessionNotificationType = /* @__PURE__ */ ((SessionNotificationType2) => {
386
439
  SessionNotificationType2["SESSION_TITLE_UPDATED"] = "session_title_updated";
387
440
  SessionNotificationType2["MCP_STATUS_CHANGED"] = "mcp_status_changed";
388
441
  SessionNotificationType2["ASSISTANT_TEXT_DELTA"] = "assistant_text_delta";
442
+ SessionNotificationType2["ASSISTANT_TEXT_COMPLETE"] = "assistant_text_complete";
389
443
  SessionNotificationType2["THINKING_TEXT_DELTA"] = "thinking_text_delta";
444
+ SessionNotificationType2["THINKING_TEXT_COMPLETE"] = "thinking_text_complete";
445
+ SessionNotificationType2["TOOL_CALL"] = "tool_call";
390
446
  SessionNotificationType2["SESSION_TOKEN_USAGE_CHANGED"] = "session_token_usage_changed";
391
447
  SessionNotificationType2["MISSION_STATE_CHANGED"] = "mission_state_changed";
392
448
  SessionNotificationType2["MISSION_FEATURES_CHANGED"] = "mission_features_changed";
@@ -396,6 +452,9 @@ var SessionNotificationType = /* @__PURE__ */ ((SessionNotificationType2) => {
396
452
  SessionNotificationType2["MISSION_WORKER_COMPLETED"] = "mission_worker_completed";
397
453
  SessionNotificationType2["MCP_AUTH_REQUIRED"] = "mcp_auth_required";
398
454
  SessionNotificationType2["MCP_AUTH_COMPLETED"] = "mcp_auth_completed";
455
+ SessionNotificationType2["HOOK_EXECUTION_STARTED"] = "hook_execution_started";
456
+ SessionNotificationType2["HOOK_EXECUTION_COMPLETED"] = "hook_execution_completed";
457
+ SessionNotificationType2["STRUCTURED_OUTPUT"] = "structured_output";
399
458
  return SessionNotificationType2;
400
459
  })(SessionNotificationType || {});
401
460
  var ToolConfirmationOutcome = /* @__PURE__ */ ((ToolConfirmationOutcome3) => {
@@ -589,6 +648,11 @@ var JsonRpcMessageType = /* @__PURE__ */ ((JsonRpcMessageType2) => {
589
648
  JsonRpcMessageType2["Notification"] = "notification";
590
649
  return JsonRpcMessageType2;
591
650
  })(JsonRpcMessageType || {});
651
+ var ServerRequestHandlerType = /* @__PURE__ */ ((ServerRequestHandlerType2) => {
652
+ ServerRequestHandlerType2["Permission"] = "permission";
653
+ ServerRequestHandlerType2["AskUser"] = "askUser";
654
+ return ServerRequestHandlerType2;
655
+ })(ServerRequestHandlerType || {});
592
656
  var SettingsLevel = /* @__PURE__ */ ((SettingsLevel2) => {
593
657
  SettingsLevel2["Org"] = "org";
594
658
  SettingsLevel2["Runtime"] = "runtime";
@@ -609,7 +673,7 @@ var SkillLocation = /* @__PURE__ */ ((SkillLocation2) => {
609
673
  // src/schemas/constants.ts
610
674
  var JSONRPC_VERSION = "2.0";
611
675
  var LEGACY_FACTORY_API_VERSION = "1.0.0";
612
- var FACTORY_PROTOCOL_VERSION = "1.3.0";
676
+ var FACTORY_PROTOCOL_VERSION = "1.51.0";
613
677
  var FACTORY_CLIENT_HEADER = "X-Factory-Client";
614
678
  var FACTORY_CLIENT_VERSION = "X-Client-Version";
615
679
  var DEFAULT_REQUEST_TIMEOUT = 3e4;
@@ -700,6 +764,12 @@ var JsonRpcMessageSchema = import_zod.z.discriminatedUnion("type", [
700
764
  }),
701
765
  JsonRpcNotificationSchema
702
766
  ]);
767
+ function createResponseSchema(resultSchema) {
768
+ return import_zod.z.union([
769
+ JsonRpcResponseSuccessSchema.extend({ result: resultSchema }),
770
+ JsonRpcResponseFailureSchema
771
+ ]);
772
+ }
703
773
 
704
774
  // src/schemas/session-metadata.ts
705
775
  var import_zod6 = require("zod");
@@ -1147,6 +1217,9 @@ var AddUserMessageRequestParamsSchema = import_zod5.z.object({
1147
1217
  outputFormat: OutputFormatSchema.optional()
1148
1218
  }).strict();
1149
1219
  var InterruptSessionRequestParamsSchema = import_zod5.z.object({}).strict();
1220
+ var CloseSessionRequestParamsSchema = import_zod5.z.object({
1221
+ reason: import_zod5.z.enum(["clear", "logout", "prompt_input_exit", "other"]).optional()
1222
+ }).strict();
1150
1223
  var KillWorkerSessionRequestParamsSchema = import_zod5.z.object({
1151
1224
  workerSessionId: import_zod5.z.string()
1152
1225
  }).strict();
@@ -1263,6 +1336,10 @@ var InterruptSessionRequestSchema = JsonRpcRequestSchema.extend({
1263
1336
  method: import_zod5.z.literal("droid.interrupt_session" /* INTERRUPT_SESSION */),
1264
1337
  params: InterruptSessionRequestParamsSchema
1265
1338
  });
1339
+ var CloseSessionRequestSchema = JsonRpcRequestSchema.extend({
1340
+ method: import_zod5.z.literal("droid.close_session" /* CLOSE_SESSION */),
1341
+ params: CloseSessionRequestParamsSchema
1342
+ });
1266
1343
  var KillWorkerSessionRequestSchema = JsonRpcRequestSchema.extend({
1267
1344
  method: import_zod5.z.literal("droid.kill_worker_session" /* KILL_WORKER_SESSION */),
1268
1345
  params: KillWorkerSessionRequestParamsSchema
@@ -1355,6 +1432,7 @@ var ClientRequestSchema = import_zod5.z.discriminatedUnion("method", [
1355
1432
  InitializeSessionRequestSchema,
1356
1433
  LoadSessionRequestSchema,
1357
1434
  AddUserMessageRequestSchema,
1435
+ CloseSessionRequestSchema,
1358
1436
  InterruptSessionRequestSchema,
1359
1437
  KillWorkerSessionRequestSchema,
1360
1438
  UpdateSessionSettingsRequestSchema,
@@ -1415,6 +1493,7 @@ var LoadSessionResultSchema = import_zod5.z.object({
1415
1493
  }).passthrough();
1416
1494
  var AddUserMessageResultSchema = EmptyResultSchema;
1417
1495
  var InterruptSessionResultSchema = EmptyResultSchema;
1496
+ var CloseSessionResultSchema = EmptyResultSchema;
1418
1497
  var KillWorkerSessionResultSchema = EmptyResultSchema;
1419
1498
  var UpdateSessionSettingsResultSchema = EmptyResultSchema;
1420
1499
  var ToggleMcpServerResultSchema = SuccessResultSchema;
@@ -1454,128 +1533,102 @@ var ForkSessionResultSchema = import_zod5.z.object({
1454
1533
  newSessionId: import_zod5.z.string()
1455
1534
  }).passthrough();
1456
1535
  var GetContextStatsResultSchema = ContextStatsSchema;
1536
+ var ContextBreakdownCategorySchema = import_zod5.z.object({
1537
+ name: import_zod5.z.string(),
1538
+ tokens: import_zod5.z.number(),
1539
+ colorKey: import_zod5.z.string()
1540
+ }).passthrough();
1541
+ var ContextBreakdownResultSchema = import_zod5.z.object({
1542
+ modelId: import_zod5.z.string(),
1543
+ modelDisplayName: import_zod5.z.string(),
1544
+ contextBudget: import_zod5.z.number(),
1545
+ usedTokens: import_zod5.z.number(),
1546
+ freeTokens: import_zod5.z.number(),
1547
+ categories: import_zod5.z.array(ContextBreakdownCategorySchema)
1548
+ }).passthrough();
1457
1549
  var RenameSessionResultSchema = SuccessResultSchema;
1458
- var InitializeSessionResponseSchema = import_zod5.z.union([
1459
- JsonRpcResponseSuccessSchema.extend({
1460
- result: InitializeSessionResultSchema
1461
- }),
1462
- JsonRpcResponseFailureSchema
1463
- ]);
1464
- var _LoadSessionResponseSchema = import_zod5.z.union([
1465
- JsonRpcResponseSuccessSchema.extend({ result: LoadSessionResultSchema }),
1466
- JsonRpcResponseFailureSchema
1467
- ]);
1550
+ var InitializeSessionResponseSchema = createResponseSchema(
1551
+ InitializeSessionResultSchema
1552
+ );
1553
+ var _LoadSessionResponseSchema = createResponseSchema(
1554
+ LoadSessionResultSchema
1555
+ );
1468
1556
  var LoadSessionResponseSchema = _LoadSessionResponseSchema;
1469
- var AddUserMessageResponseSchema = import_zod5.z.union([
1470
- JsonRpcResponseSuccessSchema.extend({ result: AddUserMessageResultSchema }),
1471
- JsonRpcResponseFailureSchema
1472
- ]);
1473
- var InterruptSessionResponseSchema = import_zod5.z.union([
1474
- JsonRpcResponseSuccessSchema.extend({
1475
- result: InterruptSessionResultSchema
1476
- }),
1477
- JsonRpcResponseFailureSchema
1478
- ]);
1479
- var KillWorkerSessionResponseSchema = import_zod5.z.union([
1480
- JsonRpcResponseSuccessSchema.extend({
1481
- result: KillWorkerSessionResultSchema
1482
- }),
1483
- JsonRpcResponseFailureSchema
1484
- ]);
1485
- var UpdateSessionSettingsResponseSchema = import_zod5.z.union([
1486
- JsonRpcResponseSuccessSchema.extend({
1487
- result: UpdateSessionSettingsResultSchema
1488
- }),
1489
- JsonRpcResponseFailureSchema
1490
- ]);
1491
- var ToggleMcpServerResponseSchema = import_zod5.z.union([
1492
- JsonRpcResponseSuccessSchema.extend({
1493
- result: ToggleMcpServerResultSchema
1494
- }),
1495
- JsonRpcResponseFailureSchema
1496
- ]);
1497
- var AuthenticateMcpServerResponseSchema = import_zod5.z.union([
1498
- JsonRpcResponseSuccessSchema.extend({
1499
- result: AuthenticateMcpServerResultSchema
1500
- }),
1501
- JsonRpcResponseFailureSchema
1502
- ]);
1503
- var CancelMcpAuthResponseSchema = import_zod5.z.union([
1504
- JsonRpcResponseSuccessSchema.extend({ result: CancelMcpAuthResultSchema }),
1505
- JsonRpcResponseFailureSchema
1506
- ]);
1507
- var ClearMcpAuthResponseSchema = import_zod5.z.union([
1508
- JsonRpcResponseSuccessSchema.extend({ result: ClearMcpAuthResultSchema }),
1509
- JsonRpcResponseFailureSchema
1510
- ]);
1511
- var SubmitMcpAuthCodeResponseSchema = import_zod5.z.union([
1512
- JsonRpcResponseSuccessSchema.extend({
1513
- result: SubmitMcpAuthCodeResultSchema
1514
- }),
1515
- JsonRpcResponseFailureSchema
1516
- ]);
1517
- var AddMcpServerResponseSchema = import_zod5.z.union([
1518
- JsonRpcResponseSuccessSchema.extend({ result: AddMcpServerResultSchema }),
1519
- JsonRpcResponseFailureSchema
1520
- ]);
1521
- var RemoveMcpServerResponseSchema = import_zod5.z.union([
1522
- JsonRpcResponseSuccessSchema.extend({ result: RemoveMcpServerResultSchema }),
1523
- JsonRpcResponseFailureSchema
1524
- ]);
1525
- var ListMcpRegistryResponseSchema = import_zod5.z.union([
1526
- JsonRpcResponseSuccessSchema.extend({
1527
- result: ListMcpRegistryResultSchema
1528
- }),
1529
- JsonRpcResponseFailureSchema
1530
- ]);
1531
- var ListMcpToolsResponseSchema = import_zod5.z.union([
1532
- JsonRpcResponseSuccessSchema.extend({ result: ListMcpToolsResultSchema }),
1533
- JsonRpcResponseFailureSchema
1534
- ]);
1535
- var ListToolsResponseSchema = import_zod5.z.union([
1536
- JsonRpcResponseSuccessSchema.extend({ result: ListToolsResultSchema }),
1537
- JsonRpcResponseFailureSchema
1538
- ]);
1539
- var ListMcpServersResponseSchema = import_zod5.z.union([
1540
- JsonRpcResponseSuccessSchema.extend({ result: ListMcpServersResultSchema }),
1541
- JsonRpcResponseFailureSchema
1542
- ]);
1543
- var ToggleMcpToolResponseSchema = import_zod5.z.union([
1544
- JsonRpcResponseSuccessSchema.extend({ result: ToggleMcpToolResultSchema }),
1545
- JsonRpcResponseFailureSchema
1546
- ]);
1547
- var ListSkillsResponseSchema = import_zod5.z.union([
1548
- JsonRpcResponseSuccessSchema.extend({ result: ListSkillsResultSchema }),
1549
- JsonRpcResponseFailureSchema
1550
- ]);
1551
- var SubmitBugReportResponseSchema = import_zod5.z.union([
1552
- JsonRpcResponseSuccessSchema.extend({ result: SubmitBugReportResultSchema }),
1553
- JsonRpcResponseFailureSchema
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
- ]);
1557
+ var AddUserMessageResponseSchema = createResponseSchema(
1558
+ AddUserMessageResultSchema
1559
+ );
1560
+ var InterruptSessionResponseSchema = createResponseSchema(
1561
+ InterruptSessionResultSchema
1562
+ );
1563
+ var CloseSessionResponseSchema = createResponseSchema(
1564
+ CloseSessionResultSchema
1565
+ );
1566
+ var KillWorkerSessionResponseSchema = createResponseSchema(
1567
+ KillWorkerSessionResultSchema
1568
+ );
1569
+ var UpdateSessionSettingsResponseSchema = createResponseSchema(
1570
+ UpdateSessionSettingsResultSchema
1571
+ );
1572
+ var ToggleMcpServerResponseSchema = createResponseSchema(
1573
+ ToggleMcpServerResultSchema
1574
+ );
1575
+ var AuthenticateMcpServerResponseSchema = createResponseSchema(
1576
+ AuthenticateMcpServerResultSchema
1577
+ );
1578
+ var CancelMcpAuthResponseSchema = createResponseSchema(
1579
+ CancelMcpAuthResultSchema
1580
+ );
1581
+ var ClearMcpAuthResponseSchema = createResponseSchema(
1582
+ ClearMcpAuthResultSchema
1583
+ );
1584
+ var SubmitMcpAuthCodeResponseSchema = createResponseSchema(
1585
+ SubmitMcpAuthCodeResultSchema
1586
+ );
1587
+ var AddMcpServerResponseSchema = createResponseSchema(
1588
+ AddMcpServerResultSchema
1589
+ );
1590
+ var RemoveMcpServerResponseSchema = createResponseSchema(
1591
+ RemoveMcpServerResultSchema
1592
+ );
1593
+ var ListMcpRegistryResponseSchema = createResponseSchema(
1594
+ ListMcpRegistryResultSchema
1595
+ );
1596
+ var ListMcpToolsResponseSchema = createResponseSchema(
1597
+ ListMcpToolsResultSchema
1598
+ );
1599
+ var ListToolsResponseSchema = createResponseSchema(
1600
+ ListToolsResultSchema
1601
+ );
1602
+ var ListMcpServersResponseSchema = createResponseSchema(
1603
+ ListMcpServersResultSchema
1604
+ );
1605
+ var ToggleMcpToolResponseSchema = createResponseSchema(
1606
+ ToggleMcpToolResultSchema
1607
+ );
1608
+ var ListSkillsResponseSchema = createResponseSchema(
1609
+ ListSkillsResultSchema
1610
+ );
1611
+ var SubmitBugReportResponseSchema = createResponseSchema(
1612
+ SubmitBugReportResultSchema
1613
+ );
1614
+ var GetRewindInfoResponseSchema = createResponseSchema(
1615
+ GetRewindInfoResultSchema
1616
+ );
1617
+ var ExecuteRewindResponseSchema = createResponseSchema(
1618
+ ExecuteRewindResultSchema
1619
+ );
1620
+ var CompactSessionResponseSchema = createResponseSchema(
1621
+ CompactSessionResultSchema
1622
+ );
1623
+ var ForkSessionResponseSchema = createResponseSchema(
1624
+ ForkSessionResultSchema
1625
+ );
1626
+ var GetContextStatsResponseSchema = createResponseSchema(
1627
+ GetContextStatsResultSchema
1628
+ );
1629
+ var RenameSessionResponseSchema = createResponseSchema(
1630
+ RenameSessionResultSchema
1631
+ );
1579
1632
 
1580
1633
  // src/schemas/session-metadata.ts
1581
1634
  var SessionMetadataSchema = import_zod6.z.object({
@@ -1606,140 +1659,231 @@ var SessionSettingsFileSchema = import_zod6.z.object({
1606
1659
  tags: import_zod6.z.array(SessionTagSchema).optional()
1607
1660
  }).passthrough();
1608
1661
 
1609
- // src/schemas/server.ts
1662
+ // src/schemas/hooks.ts
1610
1663
  var import_zod7 = require("zod");
1664
+ var DroidHookEventSchema = import_zod7.z.enum([
1665
+ "PreToolUse",
1666
+ "PostToolUse",
1667
+ "Notification",
1668
+ "UserPromptSubmit",
1669
+ "Stop",
1670
+ "SubagentStop",
1671
+ "PreCompact",
1672
+ "SessionStart",
1673
+ "SessionEnd"
1674
+ ]);
1675
+ var DroidHookSpecificOutputSchema = import_zod7.z.object({
1676
+ hookEventName: DroidHookEventSchema.optional(),
1677
+ permissionDecision: import_zod7.z.enum(["allow", "deny", "ask"]).optional(),
1678
+ permissionDecisionReason: import_zod7.z.string().optional(),
1679
+ additionalContext: import_zod7.z.string().optional(),
1680
+ updatedInput: import_zod7.z.record(import_zod7.z.unknown()).optional()
1681
+ }).passthrough();
1682
+ var DroidHookOutputSchema = import_zod7.z.object({
1683
+ continue: import_zod7.z.boolean().optional(),
1684
+ stopReason: import_zod7.z.string().optional(),
1685
+ suppressOutput: import_zod7.z.boolean().optional(),
1686
+ systemMessage: import_zod7.z.string().optional(),
1687
+ decision: import_zod7.z.enum(["block", "approve"]).optional(),
1688
+ reason: import_zod7.z.string().optional(),
1689
+ hookSpecificOutput: DroidHookSpecificOutputSchema.optional()
1690
+ }).passthrough();
1691
+ var DroidHookExecutionResultSchema = DroidHookOutputSchema.extend({
1692
+ exitCode: import_zod7.z.number(),
1693
+ stdout: import_zod7.z.string(),
1694
+ stderr: import_zod7.z.string()
1695
+ });
1696
+
1697
+ // src/schemas/server.ts
1698
+ var import_zod8 = require("zod");
1611
1699
  var ToolUseBlockSchema2 = ToolUseBlockSchema;
1612
1700
  var ToolUseSchema = ToolUseBlockSchema2;
1613
- var ErrorDetailSchema = import_zod7.z.object({
1614
- name: import_zod7.z.string(),
1615
- message: import_zod7.z.string()
1701
+ var ErrorDetailSchema = import_zod8.z.object({
1702
+ name: import_zod8.z.string(),
1703
+ message: import_zod8.z.string()
1616
1704
  }).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(),
1705
+ var ToolProgressUpdateSchema = import_zod8.z.object({
1706
+ type: import_zod8.z.enum(["tool_call", "tool_result", "error", "status", "message"]),
1707
+ toolName: import_zod8.z.string().optional(),
1708
+ status: import_zod8.z.string().optional(),
1709
+ details: import_zod8.z.string().optional(),
1710
+ text: import_zod8.z.string().optional(),
1711
+ error: import_zod8.z.string().optional(),
1712
+ timestamp: import_zod8.z.number().optional(),
1625
1713
  parameters: JsonObjectSchema.optional(),
1626
- valueSnippet: import_zod7.z.string().optional(),
1627
- subagentSessionId: import_zod7.z.string().optional()
1714
+ valueSnippet: import_zod8.z.string().optional(),
1715
+ subagentSessionId: import_zod8.z.string().optional()
1628
1716
  }).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(),
1717
+ var SettingsUpdatedPayloadSchema = import_zod8.z.object({
1718
+ autonomyMode: import_zod8.z.nativeEnum(AutonomyMode).optional(),
1719
+ interactionMode: import_zod8.z.nativeEnum(DroidInteractionMode).optional().catch(void 0),
1720
+ autonomyLevel: import_zod8.z.nativeEnum(AutonomyLevel).optional().catch(void 0),
1721
+ modelId: import_zod8.z.string().optional(),
1722
+ reasoningEffort: import_zod8.z.nativeEnum(ReasoningEffort).optional(),
1723
+ specModeModelId: import_zod8.z.string().optional(),
1724
+ specModeReasoningEffort: import_zod8.z.nativeEnum(ReasoningEffort).optional(),
1637
1725
  ...ToolSelectionOverridesSchema.shape
1638
1726
  }).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(),
1727
+ var ToolResultNotificationSchema = import_zod8.z.object({
1728
+ type: import_zod8.z.literal("tool_result" /* TOOL_RESULT */),
1729
+ messageId: import_zod8.z.string(),
1730
+ toolUseId: import_zod8.z.string(),
1643
1731
  content: JsonValueSchema.optional(),
1644
- isError: import_zod7.z.boolean().optional(),
1645
- id: import_zod7.z.string().optional()
1732
+ isError: import_zod8.z.boolean().optional(),
1733
+ id: import_zod8.z.string().optional()
1646
1734
  }).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(),
1735
+ var ToolProgressUpdateNotificationSchema = import_zod8.z.object({
1736
+ type: import_zod8.z.literal("tool_progress_update" /* TOOL_PROGRESS_UPDATE */),
1737
+ toolUseId: import_zod8.z.string(),
1738
+ toolName: import_zod8.z.string(),
1651
1739
  update: ToolProgressUpdateSchema
1652
1740
  }).passthrough();
1653
- var CreateMessageNotificationSchema = import_zod7.z.object({
1654
- type: import_zod7.z.literal("create_message" /* CREATE_MESSAGE */),
1741
+ var CreateMessageNotificationSchema = import_zod8.z.object({
1742
+ type: import_zod8.z.literal("create_message" /* CREATE_MESSAGE */),
1655
1743
  message: FactoryDroidMessageSchema,
1656
- parentId: import_zod7.z.string().optional(),
1657
- requestId: import_zod7.z.string().optional()
1744
+ parentId: import_zod8.z.string().optional(),
1745
+ requestId: import_zod8.z.string().optional()
1658
1746
  }).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(),
1747
+ var ErrorNotificationSchema = import_zod8.z.object({
1748
+ type: import_zod8.z.literal("error" /* ERROR */),
1749
+ message: import_zod8.z.string(),
1750
+ errorType: import_zod8.z.nativeEnum(DroidErrorType),
1751
+ timestamp: import_zod8.z.string(),
1664
1752
  error: ErrorDetailSchema.optional()
1665
1753
  }).passthrough();
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)
1754
+ var DroidWorkingStateChangedNotificationSchema = import_zod8.z.object({
1755
+ type: import_zod8.z.literal("droid_working_state_changed" /* DROID_WORKING_STATE_CHANGED */),
1756
+ newState: import_zod8.z.nativeEnum(DroidWorkingState)
1669
1757
  }).passthrough();
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)
1758
+ var PermissionResolvedNotificationSchema = import_zod8.z.object({
1759
+ type: import_zod8.z.literal("permission_resolved" /* PERMISSION_RESOLVED */),
1760
+ requestId: import_zod8.z.string(),
1761
+ toolUseIds: import_zod8.z.array(import_zod8.z.string()),
1762
+ selectedOption: import_zod8.z.nativeEnum(ToolConfirmationOutcome)
1675
1763
  }).passthrough();
1676
- var SettingsUpdatedNotificationSchema = import_zod7.z.object({
1677
- type: import_zod7.z.literal("settings_updated" /* SETTINGS_UPDATED */),
1764
+ var SettingsUpdatedNotificationSchema = import_zod8.z.object({
1765
+ type: import_zod8.z.literal("settings_updated" /* SETTINGS_UPDATED */),
1678
1766
  settings: SettingsUpdatedPayloadSchema
1679
1767
  }).passthrough();
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()
1768
+ var SessionTitleUpdatedNotificationSchema = import_zod8.z.object({
1769
+ type: import_zod8.z.literal("session_title_updated" /* SESSION_TITLE_UPDATED */),
1770
+ title: import_zod8.z.string()
1683
1771
  }).passthrough();
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),
1772
+ var McpStatusChangedNotificationSchema = import_zod8.z.object({
1773
+ type: import_zod8.z.literal("mcp_status_changed" /* MCP_STATUS_CHANGED */),
1774
+ servers: import_zod8.z.array(McpServerStatusInfoSchema),
1687
1775
  summary: McpStatusSummarySchema
1688
1776
  }).passthrough();
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()
1777
+ var AssistantTextDeltaNotificationSchema = import_zod8.z.object({
1778
+ type: import_zod8.z.literal("assistant_text_delta" /* ASSISTANT_TEXT_DELTA */),
1779
+ messageId: import_zod8.z.string(),
1780
+ blockIndex: import_zod8.z.number(),
1781
+ textDelta: import_zod8.z.string()
1694
1782
  }).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()
1783
+ var AssistantTextCompleteNotificationSchema = import_zod8.z.object({
1784
+ type: import_zod8.z.literal("assistant_text_complete" /* ASSISTANT_TEXT_COMPLETE */),
1785
+ messageId: import_zod8.z.string(),
1786
+ blockIndex: import_zod8.z.number()
1700
1787
  }).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(),
1788
+ var ThinkingTextDeltaNotificationSchema = import_zod8.z.object({
1789
+ type: import_zod8.z.literal("thinking_text_delta" /* THINKING_TEXT_DELTA */),
1790
+ messageId: import_zod8.z.string(),
1791
+ blockIndex: import_zod8.z.number(),
1792
+ textDelta: import_zod8.z.string()
1793
+ }).passthrough();
1794
+ var ThinkingTextCompleteNotificationSchema = import_zod8.z.object({
1795
+ type: import_zod8.z.literal("thinking_text_complete" /* THINKING_TEXT_COMPLETE */),
1796
+ messageId: import_zod8.z.string(),
1797
+ blockIndex: import_zod8.z.number(),
1798
+ durationMs: import_zod8.z.number().optional()
1799
+ }).passthrough();
1800
+ var ToolCallNotificationSchema = import_zod8.z.object({
1801
+ type: import_zod8.z.literal("tool_call" /* TOOL_CALL */),
1802
+ toolUse: ToolUseBlockSchema2
1803
+ }).passthrough();
1804
+ var SessionTokenUsageChangedNotificationSchema = import_zod8.z.object({
1805
+ type: import_zod8.z.literal("session_token_usage_changed" /* SESSION_TOKEN_USAGE_CHANGED */),
1806
+ sessionId: import_zod8.z.string(),
1704
1807
  tokenUsage: TokenUsageSchema
1705
1808
  }).passthrough();
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)
1809
+ var MissionStateChangedNotificationSchema = import_zod8.z.object({
1810
+ type: import_zod8.z.literal("mission_state_changed" /* MISSION_STATE_CHANGED */),
1811
+ state: import_zod8.z.nativeEnum(MissionState)
1812
+ }).passthrough();
1813
+ var MissionFeaturesChangedNotificationSchema = import_zod8.z.object({
1814
+ type: import_zod8.z.literal("mission_features_changed" /* MISSION_FEATURES_CHANGED */),
1815
+ features: import_zod8.z.array(MissionFeatureSchema)
1709
1816
  }).passthrough();
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)
1817
+ var MissionProgressEntryNotificationSchema = import_zod8.z.object({
1818
+ type: import_zod8.z.literal("mission_progress_entry" /* MISSION_PROGRESS_ENTRY */),
1819
+ progressLog: import_zod8.z.array(ProgressLogEntrySchema)
1713
1820
  }).passthrough();
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)
1821
+ var MissionHeartbeatNotificationSchema = import_zod8.z.object({
1822
+ type: import_zod8.z.literal("mission_heartbeat" /* MISSION_HEARTBEAT */),
1823
+ timestamp: import_zod8.z.string()
1717
1824
  }).passthrough();
1718
- var MissionHeartbeatNotificationSchema = import_zod7.z.object({
1719
- type: import_zod7.z.literal("mission_heartbeat" /* MISSION_HEARTBEAT */),
1720
- timestamp: import_zod7.z.string()
1825
+ var MissionWorkerStartedNotificationSchema = import_zod8.z.object({
1826
+ type: import_zod8.z.literal("mission_worker_started" /* MISSION_WORKER_STARTED */),
1827
+ workerSessionId: import_zod8.z.string()
1721
1828
  }).passthrough();
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()
1829
+ var MissionWorkerCompletedNotificationSchema = import_zod8.z.object({
1830
+ type: import_zod8.z.literal("mission_worker_completed" /* MISSION_WORKER_COMPLETED */),
1831
+ workerSessionId: import_zod8.z.string(),
1832
+ exitCode: import_zod8.z.number()
1725
1833
  }).passthrough();
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()
1834
+ var McpAuthRequiredNotificationSchema = import_zod8.z.object({
1835
+ type: import_zod8.z.literal("mcp_auth_required" /* MCP_AUTH_REQUIRED */),
1836
+ serverName: import_zod8.z.string(),
1837
+ authUrl: import_zod8.z.string(),
1838
+ message: import_zod8.z.string(),
1839
+ state: import_zod8.z.string()
1730
1840
  }).passthrough();
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()
1841
+ var McpAuthCompletedNotificationSchema = import_zod8.z.object({
1842
+ type: import_zod8.z.literal("mcp_auth_completed" /* MCP_AUTH_COMPLETED */),
1843
+ serverName: import_zod8.z.string(),
1844
+ outcome: import_zod8.z.nativeEnum(McpAuthOutcome),
1845
+ message: import_zod8.z.string()
1737
1846
  }).passthrough();
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()
1847
+ var HookCommandSchema = import_zod8.z.object({
1848
+ command: import_zod8.z.string(),
1849
+ timeout: import_zod8.z.number().optional()
1850
+ }).passthrough();
1851
+ var HookResultSchema = import_zod8.z.object({
1852
+ exitCode: import_zod8.z.number(),
1853
+ stdout: import_zod8.z.string(),
1854
+ stderr: import_zod8.z.string(),
1855
+ command: import_zod8.z.string().optional(),
1856
+ timeout: import_zod8.z.number().optional()
1857
+ }).passthrough();
1858
+ var HookExecutionStartedNotificationSchema = import_zod8.z.object({
1859
+ type: import_zod8.z.literal("hook_execution_started" /* HOOK_EXECUTION_STARTED */),
1860
+ hookId: import_zod8.z.string(),
1861
+ hookEventName: DroidHookEventSchema,
1862
+ hookMatcher: import_zod8.z.string().optional(),
1863
+ hookCommands: import_zod8.z.array(HookCommandSchema),
1864
+ hookToolCallId: import_zod8.z.string().optional(),
1865
+ isParallelExecution: import_zod8.z.boolean().optional(),
1866
+ parallelGroupId: import_zod8.z.string().optional()
1867
+ }).passthrough();
1868
+ var HookExecutionCompletedNotificationSchema = import_zod8.z.object({
1869
+ type: import_zod8.z.literal("hook_execution_completed" /* HOOK_EXECUTION_COMPLETED */),
1870
+ hookId: import_zod8.z.string(),
1871
+ hookEventName: DroidHookEventSchema.optional(),
1872
+ hookMatcher: import_zod8.z.string().optional(),
1873
+ hookToolCallId: import_zod8.z.string().optional(),
1874
+ hookStatus: import_zod8.z.enum(["completed", "error"]),
1875
+ hookResults: import_zod8.z.array(HookResultSchema).optional()
1876
+ }).passthrough();
1877
+ var StructuredOutputErrorSchema = import_zod8.z.object({
1878
+ code: import_zod8.z.string(),
1879
+ message: import_zod8.z.string(),
1880
+ details: import_zod8.z.unknown().optional()
1881
+ }).passthrough();
1882
+ var StructuredOutputNotificationSchema = import_zod8.z.object({
1883
+ type: import_zod8.z.literal("structured_output" /* STRUCTURED_OUTPUT */),
1884
+ messageId: import_zod8.z.string(),
1885
+ structuredOutput: JsonObjectSchema.nullable(),
1886
+ structuredOutputError: StructuredOutputErrorSchema.nullable()
1743
1887
  }).passthrough();
1744
1888
  var SessionNotificationSchemaList = [
1745
1889
  ToolResultNotificationSchema,
@@ -1752,7 +1896,10 @@ var SessionNotificationSchemaList = [
1752
1896
  SessionTitleUpdatedNotificationSchema,
1753
1897
  McpStatusChangedNotificationSchema,
1754
1898
  AssistantTextDeltaNotificationSchema,
1899
+ AssistantTextCompleteNotificationSchema,
1755
1900
  ThinkingTextDeltaNotificationSchema,
1901
+ ThinkingTextCompleteNotificationSchema,
1902
+ ToolCallNotificationSchema,
1756
1903
  SessionTokenUsageChangedNotificationSchema,
1757
1904
  MissionStateChangedNotificationSchema,
1758
1905
  MissionFeaturesChangedNotificationSchema,
@@ -1761,88 +1908,91 @@ var SessionNotificationSchemaList = [
1761
1908
  MissionWorkerStartedNotificationSchema,
1762
1909
  MissionWorkerCompletedNotificationSchema,
1763
1910
  McpAuthRequiredNotificationSchema,
1764
- McpAuthCompletedNotificationSchema
1911
+ McpAuthCompletedNotificationSchema,
1912
+ HookExecutionStartedNotificationSchema,
1913
+ HookExecutionCompletedNotificationSchema,
1914
+ StructuredOutputNotificationSchema
1765
1915
  ];
1766
- var SessionNotificationPayloadSchema = import_zod7.z.discriminatedUnion(
1916
+ var SessionNotificationPayloadSchema = import_zod8.z.discriminatedUnion(
1767
1917
  "type",
1768
1918
  SessionNotificationSchemaList
1769
1919
  );
1770
- var _SessionNotificationParamsSchema = import_zod7.z.object({
1920
+ var _SessionNotificationParamsSchema = import_zod8.z.object({
1771
1921
  notification: SessionNotificationPayloadSchema
1772
1922
  }).passthrough();
1773
1923
  var SessionNotificationParamsSchema = _SessionNotificationParamsSchema;
1774
1924
  var _SessionNotificationSchema = JsonRpcNotificationSchema.extend({
1775
- method: import_zod7.z.literal("droid.session_notification" /* SESSION_NOTIFICATION */),
1925
+ method: import_zod8.z.literal("droid.session_notification" /* SESSION_NOTIFICATION */),
1776
1926
  params: SessionNotificationParamsSchema
1777
1927
  });
1778
1928
  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()
1929
+ var EditToolConfirmationDetailsSchema = import_zod8.z.object({
1930
+ type: import_zod8.z.literal("edit" /* Edit */),
1931
+ filePath: import_zod8.z.string(),
1932
+ fileName: import_zod8.z.string(),
1933
+ oldContent: import_zod8.z.string().optional(),
1934
+ newContent: import_zod8.z.string().optional()
1785
1935
  }).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()
1936
+ var ExecuteToolConfirmationDetailsSchema = import_zod8.z.object({
1937
+ type: import_zod8.z.literal("exec" /* Execute */),
1938
+ fullCommand: import_zod8.z.string(),
1939
+ command: import_zod8.z.string(),
1940
+ extractedCommands: import_zod8.z.array(import_zod8.z.string()).optional(),
1941
+ impactLevel: import_zod8.z.string().optional()
1792
1942
  }).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()
1943
+ var CreateToolConfirmationDetailsSchema = import_zod8.z.object({
1944
+ type: import_zod8.z.literal("create" /* Create */),
1945
+ filePath: import_zod8.z.string(),
1946
+ fileName: import_zod8.z.string(),
1947
+ content: import_zod8.z.string()
1798
1948
  }).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())
1949
+ var AskUserQuestionSchema = import_zod8.z.object({
1950
+ index: import_zod8.z.number(),
1951
+ topic: import_zod8.z.string(),
1952
+ question: import_zod8.z.string(),
1953
+ options: import_zod8.z.array(import_zod8.z.string())
1804
1954
  }).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)
1955
+ var AskUserConfirmationDetailsSchema = import_zod8.z.object({
1956
+ type: import_zod8.z.literal("ask_user" /* AskUser */),
1957
+ questionnaire: import_zod8.z.string(),
1958
+ parsed: import_zod8.z.object({
1959
+ questions: import_zod8.z.array(AskUserQuestionSchema)
1810
1960
  }).optional(),
1811
- parseError: import_zod7.z.object({
1812
- message: import_zod7.z.string(),
1813
- line: import_zod7.z.number().optional()
1961
+ parseError: import_zod8.z.object({
1962
+ message: import_zod8.z.string(),
1963
+ line: import_zod8.z.number().optional()
1814
1964
  }).optional()
1815
1965
  }).passthrough();
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()
1966
+ var ExitSpecModeConfirmationDetailsSchema = import_zod8.z.object({
1967
+ type: import_zod8.z.literal("exit_spec_mode" /* ExitSpecMode */),
1968
+ plan: import_zod8.z.string(),
1969
+ title: import_zod8.z.string().optional(),
1970
+ optionNames: import_zod8.z.array(import_zod8.z.string()).optional()
1821
1971
  }).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()
1972
+ var ProposeMissionConfirmationDetailsSchema = import_zod8.z.object({
1973
+ type: import_zod8.z.literal("propose_mission" /* ProposeMission */),
1974
+ proposal: import_zod8.z.string(),
1975
+ title: import_zod8.z.string().optional()
1826
1976
  }).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())
1977
+ var StartMissionRunConfirmationDetailsSchema = import_zod8.z.object({
1978
+ type: import_zod8.z.literal("start_mission_run" /* StartMissionRun */),
1979
+ runningMissionCount: import_zod8.z.number(),
1980
+ runningMissionSessionIds: import_zod8.z.array(import_zod8.z.string())
1831
1981
  }).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()
1982
+ var ApplyPatchToolConfirmationDetailsSchema = import_zod8.z.object({
1983
+ type: import_zod8.z.literal("apply_patch" /* ApplyPatch */),
1984
+ filePath: import_zod8.z.string(),
1985
+ fileName: import_zod8.z.string(),
1986
+ patchContent: import_zod8.z.string(),
1987
+ oldContent: import_zod8.z.string().optional(),
1988
+ newContent: import_zod8.z.string().optional()
1839
1989
  }).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()
1990
+ var McpToolConfirmationDetailsSchema = import_zod8.z.object({
1991
+ type: import_zod8.z.literal("mcp_tool" /* McpTool */),
1992
+ toolName: import_zod8.z.string(),
1993
+ impactLevel: import_zod8.z.string()
1844
1994
  }).passthrough();
1845
- var ToolConfirmationDetailsSchema = import_zod7.z.discriminatedUnion("type", [
1995
+ var ToolConfirmationDetailsSchema = import_zod8.z.discriminatedUnion("type", [
1846
1996
  EditToolConfirmationDetailsSchema,
1847
1997
  ExecuteToolConfirmationDetailsSchema,
1848
1998
  CreateToolConfirmationDetailsSchema,
@@ -1853,51 +2003,45 @@ var ToolConfirmationDetailsSchema = import_zod7.z.discriminatedUnion("type", [
1853
2003
  ApplyPatchToolConfirmationDetailsSchema,
1854
2004
  McpToolConfirmationDetailsSchema
1855
2005
  ]);
1856
- var ToolConfirmationInfoSchema = import_zod7.z.object({
2006
+ var ToolConfirmationInfoSchema = import_zod8.z.object({
1857
2007
  toolUse: ToolUseSchema,
1858
- confirmationType: import_zod7.z.nativeEnum(ToolConfirmationType),
2008
+ confirmationType: import_zod8.z.nativeEnum(ToolConfirmationType),
1859
2009
  details: ToolConfirmationDetailsSchema
1860
2010
  }).passthrough();
1861
- var RequestPermissionRequestParamsSchema = import_zod7.z.object({
1862
- toolUses: import_zod7.z.array(ToolConfirmationInfoSchema),
1863
- options: import_zod7.z.array(ToolConfirmationListItemSchema)
2011
+ var RequestPermissionRequestParamsSchema = import_zod8.z.object({
2012
+ toolUses: import_zod8.z.array(ToolConfirmationInfoSchema),
2013
+ options: import_zod8.z.array(ToolConfirmationListItemSchema)
1864
2014
  }).passthrough();
1865
2015
  var RequestPermissionRequestSchema = JsonRpcRequestSchema.extend({
1866
- method: import_zod7.z.literal("droid.request_permission" /* REQUEST_PERMISSION */),
2016
+ method: import_zod8.z.literal("droid.request_permission" /* REQUEST_PERMISSION */),
1867
2017
  params: RequestPermissionRequestParamsSchema
1868
2018
  });
1869
- var RequestPermissionResultSchema = import_zod7.z.object({
1870
- selectedOption: import_zod7.z.nativeEnum(ToolConfirmationOutcome),
1871
- comment: import_zod7.z.string().optional()
2019
+ var RequestPermissionResultSchema = import_zod8.z.object({
2020
+ selectedOption: import_zod8.z.nativeEnum(ToolConfirmationOutcome),
2021
+ comment: import_zod8.z.string().optional()
1872
2022
  }).strict();
1873
- var RequestPermissionResponseSchema = import_zod7.z.union([
1874
- JsonRpcResponseSuccessSchema.extend({
1875
- result: RequestPermissionResultSchema
1876
- }),
1877
- JsonRpcResponseFailureSchema
1878
- ]);
1879
- var AskUserRequestParamsSchema = import_zod7.z.object({
1880
- toolCallId: import_zod7.z.string(),
1881
- questions: import_zod7.z.array(AskUserQuestionSchema)
2023
+ var RequestPermissionResponseSchema = createResponseSchema(
2024
+ RequestPermissionResultSchema
2025
+ );
2026
+ var AskUserRequestParamsSchema = import_zod8.z.object({
2027
+ toolCallId: import_zod8.z.string(),
2028
+ questions: import_zod8.z.array(AskUserQuestionSchema)
1882
2029
  }).passthrough();
1883
2030
  var AskUserRequestSchema = JsonRpcRequestSchema.extend({
1884
- method: import_zod7.z.literal("droid.ask_user" /* ASK_USER */),
2031
+ method: import_zod8.z.literal("droid.ask_user" /* ASK_USER */),
1885
2032
  params: AskUserRequestParamsSchema
1886
2033
  });
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()
2034
+ var AskUserCollectedAnswerSchema = import_zod8.z.object({
2035
+ index: import_zod8.z.number(),
2036
+ question: import_zod8.z.string(),
2037
+ answer: import_zod8.z.string()
1891
2038
  }).strict();
1892
- var AskUserResultSchema = import_zod7.z.object({
1893
- cancelled: import_zod7.z.boolean().optional(),
1894
- answers: import_zod7.z.array(AskUserCollectedAnswerSchema)
2039
+ var AskUserResultSchema = import_zod8.z.object({
2040
+ cancelled: import_zod8.z.boolean().optional(),
2041
+ answers: import_zod8.z.array(AskUserCollectedAnswerSchema)
1895
2042
  }).strict();
1896
- var AskUserResponseSchema = import_zod7.z.union([
1897
- JsonRpcResponseSuccessSchema.extend({ result: AskUserResultSchema }),
1898
- JsonRpcResponseFailureSchema
1899
- ]);
1900
- var _CliRequestOrNotificationSchema = import_zod7.z.union([
2043
+ var AskUserResponseSchema = createResponseSchema(AskUserResultSchema);
2044
+ var _CliRequestOrNotificationSchema = import_zod8.z.union([
1901
2045
  SessionNotificationSchema,
1902
2046
  RequestPermissionRequestSchema,
1903
2047
  AskUserRequestSchema
@@ -1905,7 +2049,7 @@ var _CliRequestOrNotificationSchema = import_zod7.z.union([
1905
2049
  var CliRequestOrNotificationSchema = _CliRequestOrNotificationSchema;
1906
2050
 
1907
2051
  // src/constants.ts
1908
- var SDK_VERSION = "0.2.0";
2052
+ var SDK_VERSION = "0.4.0";
1909
2053
  var SDK_TAG = {
1910
2054
  name: "sdk",
1911
2055
  metadata: { language: "typescript", version: SDK_VERSION }
@@ -2221,9 +2365,32 @@ var ProcessTransport = class {
2221
2365
 
2222
2366
  // src/protocol.ts
2223
2367
  var import_uuid = require("uuid");
2368
+ function dispatchNotification(notification, listeners) {
2369
+ let notificationType;
2370
+ const parsed = SessionNotificationParamsSchema.safeParse(
2371
+ notification["params"]
2372
+ );
2373
+ if (parsed.success) {
2374
+ notificationType = parsed.data.notification.type;
2375
+ }
2376
+ for (const listener of listeners) {
2377
+ if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2378
+ continue;
2379
+ }
2380
+ try {
2381
+ listener.callback(notification);
2382
+ } catch {
2383
+ }
2384
+ }
2385
+ }
2386
+ var DEFAULT_SERVER_REQUEST_METHOD_MAP = {
2387
+ ["droid.request_permission" /* REQUEST_PERMISSION */]: "permission" /* Permission */,
2388
+ ["droid.ask_user" /* ASK_USER */]: "askUser" /* AskUser */
2389
+ };
2224
2390
  var ProtocolEngine = class {
2225
2391
  _transport;
2226
2392
  _defaultTimeout;
2393
+ _serverRequestMethodMap;
2227
2394
  _pendingRequests = /* @__PURE__ */ new Map();
2228
2395
  _notificationListeners = /* @__PURE__ */ new Set();
2229
2396
  _permissionHandler = null;
@@ -2233,6 +2400,7 @@ var ProtocolEngine = class {
2233
2400
  constructor(options) {
2234
2401
  this._transport = options.transport;
2235
2402
  this._defaultTimeout = options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT;
2403
+ this._serverRequestMethodMap = options.serverRequestMethodMap ?? DEFAULT_SERVER_REQUEST_METHOD_MAP;
2236
2404
  this._transport.onMessage((message) => {
2237
2405
  this._handleMessage(message);
2238
2406
  });
@@ -2385,27 +2553,13 @@ var ProtocolEngine = class {
2385
2553
  pending.resolve(result);
2386
2554
  }
2387
2555
  _handleNotification(notification) {
2388
- let notificationType;
2389
- const parsed = SessionNotificationParamsSchema.safeParse(
2390
- notification["params"]
2391
- );
2392
- if (parsed.success) {
2393
- notificationType = parsed.data.notification.type;
2394
- }
2395
- for (const listener of this._notificationListeners) {
2396
- if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2397
- continue;
2398
- }
2399
- try {
2400
- listener.callback(notification);
2401
- } catch {
2402
- }
2403
- }
2556
+ dispatchNotification(notification, this._notificationListeners);
2404
2557
  }
2405
2558
  async _handleServerRequest(method, requestId, params) {
2406
- if (method === "droid.request_permission" /* REQUEST_PERMISSION */) {
2559
+ const handlerType = this._serverRequestMethodMap[method];
2560
+ if (handlerType === "permission" /* Permission */) {
2407
2561
  await this._handlePermissionRequest(requestId, params);
2408
- } else if (method === "droid.ask_user" /* ASK_USER */) {
2562
+ } else if (handlerType === "askUser" /* AskUser */) {
2409
2563
  await this._handleAskUserRequest(requestId, params);
2410
2564
  }
2411
2565
  }
@@ -2521,10 +2675,6 @@ var DroidClient = class {
2521
2675
  _engine;
2522
2676
  _sessionId = null;
2523
2677
  _closed = false;
2524
- /**
2525
- * Client-level notification listeners.
2526
- * Each entry is [callback, optional notification filter].
2527
- */
2528
2678
  _notificationListeners = [];
2529
2679
  /** Client-level permission handler. */
2530
2680
  _permissionHandler = null;
@@ -2598,6 +2748,13 @@ var DroidClient = class {
2598
2748
  InterruptSessionResultSchema
2599
2749
  );
2600
2750
  }
2751
+ async closeSession(params = {}) {
2752
+ return this._sessionRpc(
2753
+ "droid.close_session" /* CLOSE_SESSION */,
2754
+ params,
2755
+ CloseSessionResultSchema
2756
+ );
2757
+ }
2601
2758
  async killWorkerSession(params) {
2602
2759
  return this._sessionRpc(
2603
2760
  "droid.kill_worker_session" /* KILL_WORKER_SESSION */,
@@ -2786,23 +2943,7 @@ var DroidClient = class {
2786
2943
  await this._engine.close();
2787
2944
  }
2788
2945
  _dispatchNotification(notification) {
2789
- let notificationType;
2790
- const parsed = SessionNotificationParamsSchema.safeParse(
2791
- notification["params"]
2792
- );
2793
- if (parsed.success) {
2794
- notificationType = parsed.data.notification.type;
2795
- }
2796
- const listeners = [...this._notificationListeners];
2797
- for (const listener of listeners) {
2798
- if (listener.filter?.type != null && listener.filter.type !== notificationType) {
2799
- continue;
2800
- }
2801
- try {
2802
- listener.callback(notification);
2803
- } catch {
2804
- }
2805
- }
2946
+ dispatchNotification(notification, [...this._notificationListeners]);
2806
2947
  }
2807
2948
  _dispatchPermissionRequest(params) {
2808
2949
  const handler = this._permissionHandler;
@@ -2836,14 +2977,18 @@ var DroidClient = class {
2836
2977
 
2837
2978
  // src/stream.ts
2838
2979
  var DroidMessageType = {
2980
+ Assistant: "assistant",
2981
+ User: "user",
2982
+ ToolCall: "tool_call",
2839
2983
  AssistantTextDelta: "assistant_text_delta",
2984
+ AssistantTextComplete: "assistant_text_complete",
2840
2985
  ThinkingTextDelta: "thinking_text_delta",
2841
- ToolUse: "tool_use",
2986
+ ThinkingTextComplete: "thinking_text_complete",
2987
+ ToolCallDelta: "tool_call_delta",
2842
2988
  ToolResult: "tool_result",
2843
2989
  ToolProgress: "tool_progress",
2844
2990
  WorkingStateChanged: "working_state_changed",
2845
2991
  TokenUsageUpdate: "token_usage_update",
2846
- CreateMessage: "create_message",
2847
2992
  PermissionResolved: "permission_resolved",
2848
2993
  SettingsUpdated: "settings_updated",
2849
2994
  SessionTitleUpdated: "session_title_updated",
@@ -2856,8 +3001,9 @@ var DroidMessageType = {
2856
3001
  MissionWorkerCompleted: "mission_worker_completed",
2857
3002
  McpAuthRequired: "mcp_auth_required",
2858
3003
  McpAuthCompleted: "mcp_auth_completed",
3004
+ Hook: "hook",
2859
3005
  Error: "error",
2860
- TurnComplete: "turn_complete"
3006
+ Result: "result"
2861
3007
  };
2862
3008
  function convertNotificationToStreamMessage(raw) {
2863
3009
  const parsed = SessionNotificationPayloadSchema.safeParse(raw);
@@ -2873,6 +3019,12 @@ function convertNotificationToStreamMessage(raw) {
2873
3019
  blockIndex: notification.blockIndex,
2874
3020
  text: notification.textDelta
2875
3021
  };
3022
+ case "assistant_text_complete" /* ASSISTANT_TEXT_COMPLETE */:
3023
+ return {
3024
+ type: DroidMessageType.AssistantTextComplete,
3025
+ messageId: notification.messageId,
3026
+ blockIndex: notification.blockIndex
3027
+ };
2876
3028
  case "thinking_text_delta" /* THINKING_TEXT_DELTA */:
2877
3029
  return {
2878
3030
  type: DroidMessageType.ThinkingTextDelta,
@@ -2880,6 +3032,18 @@ function convertNotificationToStreamMessage(raw) {
2880
3032
  blockIndex: notification.blockIndex,
2881
3033
  text: notification.textDelta
2882
3034
  };
3035
+ case "thinking_text_complete" /* THINKING_TEXT_COMPLETE */:
3036
+ return {
3037
+ type: DroidMessageType.ThinkingTextComplete,
3038
+ messageId: notification.messageId,
3039
+ blockIndex: notification.blockIndex,
3040
+ durationMs: notification.durationMs
3041
+ };
3042
+ case "tool_call" /* TOOL_CALL */:
3043
+ return {
3044
+ type: DroidMessageType.ToolCallDelta,
3045
+ toolUse: notification.toolUse
3046
+ };
2883
3047
  case "tool_result" /* TOOL_RESULT */:
2884
3048
  return {
2885
3049
  type: DroidMessageType.ToolResult,
@@ -2919,22 +3083,33 @@ function convertNotificationToStreamMessage(raw) {
2919
3083
  const msg = notification.message;
2920
3084
  const messages = [];
2921
3085
  for (const block of msg.content) {
2922
- if (block.type === DroidMessageType.ToolUse) {
3086
+ if (block.type === "tool_use") {
2923
3087
  messages.push({
2924
- type: DroidMessageType.ToolUse,
2925
- toolName: block.name,
2926
- toolInput: block.input,
2927
- toolUseId: block.id
3088
+ type: DroidMessageType.ToolCall,
3089
+ toolUse: block
2928
3090
  });
2929
3091
  }
2930
3092
  }
2931
- messages.push({
2932
- type: DroidMessageType.CreateMessage,
2933
- messageId: msg.id,
2934
- role: msg.role,
2935
- content: msg.content,
2936
- parentId: notification.parentId
2937
- });
3093
+ if (msg.role === FactoryDroidMessageRole.Assistant) {
3094
+ messages.push({
3095
+ type: DroidMessageType.Assistant,
3096
+ message: msg,
3097
+ text: extractTextFromMessage(msg)
3098
+ });
3099
+ } else if (msg.role === FactoryDroidMessageRole.User) {
3100
+ messages.push({
3101
+ type: DroidMessageType.User,
3102
+ message: msg
3103
+ });
3104
+ } else {
3105
+ messages.push({
3106
+ type: "create_message",
3107
+ messageId: msg.id,
3108
+ role: msg.role,
3109
+ content: msg.content,
3110
+ parentId: notification.parentId
3111
+ });
3112
+ }
2938
3113
  return messages;
2939
3114
  }
2940
3115
  case "error" /* ERROR */:
@@ -3013,42 +3188,205 @@ function convertNotificationToStreamMessage(raw) {
3013
3188
  outcome: notification.outcome,
3014
3189
  message: notification.message
3015
3190
  };
3191
+ case "hook_execution_started" /* HOOK_EXECUTION_STARTED */:
3192
+ return notification.hookCommands.map((hookCommand) => ({
3193
+ type: DroidMessageType.Hook,
3194
+ hookId: notification.hookId,
3195
+ eventName: notification.hookEventName,
3196
+ matcher: notification.hookMatcher,
3197
+ toolCallId: notification.hookToolCallId,
3198
+ command: hookCommand.command,
3199
+ timeout: hookCommand.timeout,
3200
+ status: "started"
3201
+ }));
3202
+ case "hook_execution_completed" /* HOOK_EXECUTION_COMPLETED */:
3203
+ return (notification.hookResults ?? []).map((hookResult) => ({
3204
+ type: DroidMessageType.Hook,
3205
+ hookId: notification.hookId,
3206
+ eventName: notification.hookEventName,
3207
+ matcher: notification.hookMatcher,
3208
+ toolCallId: notification.hookToolCallId,
3209
+ command: hookResult.command,
3210
+ timeout: hookResult.timeout,
3211
+ status: notification.hookStatus,
3212
+ exitCode: hookResult.exitCode,
3213
+ stdout: hookResult.stdout,
3214
+ stderr: hookResult.stderr
3215
+ }));
3216
+ case "structured_output" /* STRUCTURED_OUTPUT */:
3217
+ return {
3218
+ type: "structured_output",
3219
+ messageId: notification.messageId,
3220
+ structuredOutput: notification.structuredOutput,
3221
+ structuredOutputError: notification.structuredOutputError
3222
+ };
3016
3223
  default:
3017
3224
  return null;
3018
3225
  }
3019
3226
  }
3020
3227
  var StreamStateTracker = class {
3228
+ constructor(options = {}) {
3229
+ this.options = options;
3230
+ }
3021
3231
  hasBeenNonIdle = false;
3022
3232
  lastTokenUsage = null;
3233
+ fullText = "";
3234
+ finalAssistantText = "";
3235
+ structuredOutput = null;
3236
+ structuredOutputError = null;
3237
+ errors = [];
3238
+ numTurns = 0;
3239
+ emittedMessages = [];
3023
3240
  toolNameMap = /* @__PURE__ */ new Map();
3024
3241
  getToolName(toolUseId) {
3025
3242
  return this.toolNameMap.get(toolUseId) ?? "";
3026
3243
  }
3027
3244
  processMessage(message) {
3028
3245
  const additional = [];
3029
- if (message.type === DroidMessageType.ToolUse) {
3246
+ if (message.type === "tool_use") {
3030
3247
  this.toolNameMap.set(message.toolUseId, message.toolName);
3031
3248
  }
3249
+ if (message.type === DroidMessageType.ToolCall) {
3250
+ this.toolNameMap.set(message.toolUse.id, message.toolUse.name);
3251
+ }
3252
+ if (message.type === DroidMessageType.ToolCallDelta) {
3253
+ this.toolNameMap.set(message.toolUse.id, message.toolUse.name);
3254
+ }
3032
3255
  if (message.type === DroidMessageType.ToolResult) {
3033
3256
  message = { ...message, toolName: this.getToolName(message.toolUseId) };
3034
3257
  }
3258
+ if (message.type === DroidMessageType.AssistantTextDelta) {
3259
+ this.fullText += message.text;
3260
+ }
3261
+ if (message.type === DroidMessageType.Assistant) {
3262
+ this.finalAssistantText = message.text;
3263
+ if (this.fullText.length === 0) {
3264
+ this.fullText = message.text;
3265
+ }
3266
+ }
3035
3267
  if (message.type === DroidMessageType.TokenUsageUpdate) {
3036
3268
  this.lastTokenUsage = message;
3037
3269
  }
3270
+ if (message.type === DroidMessageType.Error) {
3271
+ this.errors.push(message);
3272
+ }
3273
+ if (message.type === "structured_output") {
3274
+ this.structuredOutput = message.structuredOutput;
3275
+ this.structuredOutputError = message.structuredOutputError;
3276
+ return { message: null, additional };
3277
+ }
3038
3278
  if (message.type === DroidMessageType.WorkingStateChanged) {
3039
3279
  if (message.state !== "idle" /* Idle */) {
3040
3280
  this.hasBeenNonIdle = true;
3041
3281
  } else if (this.hasBeenNonIdle) {
3042
- additional.push({
3043
- type: DroidMessageType.TurnComplete,
3044
- tokenUsage: this.lastTokenUsage
3045
- });
3282
+ this.numTurns++;
3283
+ additional.push(this.createResultMessage());
3046
3284
  this.hasBeenNonIdle = false;
3285
+ this.resetTurnState();
3047
3286
  }
3048
3287
  }
3288
+ if (message.type !== DroidMessageType.WorkingStateChanged) {
3289
+ this.trackEmittedMessage(message);
3290
+ }
3049
3291
  return { message, additional };
3050
3292
  }
3293
+ createResultMessage() {
3294
+ if (this.options.hasOutputFormat && this.structuredOutput === null && this.structuredOutputError === null) {
3295
+ this.structuredOutput = parseJsonObject(this.finalAssistantText || this.fullText) ?? null;
3296
+ }
3297
+ const tokenUsage = this.lastTokenUsage ? stripTokenUsageType(this.lastTokenUsage) : null;
3298
+ const result = this.finalAssistantText || this.fullText;
3299
+ const base = {
3300
+ type: DroidMessageType.Result,
3301
+ sessionId: this.options.sessionId ?? "",
3302
+ durationMs: Date.now() - (this.options.startedAt ?? Date.now()),
3303
+ numTurns: this.numTurns,
3304
+ result,
3305
+ tokenUsage,
3306
+ messages: [...this.emittedMessages],
3307
+ text: result,
3308
+ turnCount: this.numTurns
3309
+ };
3310
+ if (this.structuredOutputError) {
3311
+ return {
3312
+ ...base,
3313
+ subtype: "error_structured_output",
3314
+ isError: true,
3315
+ success: false,
3316
+ errors: [this.structuredOutputError.message],
3317
+ structuredOutput: this.structuredOutput,
3318
+ structuredOutputError: this.structuredOutputError,
3319
+ error: null
3320
+ };
3321
+ }
3322
+ if (this.errors.length > 0) {
3323
+ return {
3324
+ ...base,
3325
+ subtype: "error_during_execution",
3326
+ isError: true,
3327
+ success: false,
3328
+ errors: this.errors.map((error) => error.message),
3329
+ structuredOutput: this.structuredOutput,
3330
+ structuredOutputError: null,
3331
+ error: this.errors[0] ?? null
3332
+ };
3333
+ }
3334
+ return {
3335
+ ...base,
3336
+ subtype: "success",
3337
+ isError: false,
3338
+ success: true,
3339
+ structuredOutput: this.structuredOutput,
3340
+ structuredOutputError: null,
3341
+ error: null
3342
+ };
3343
+ }
3344
+ trackEmittedMessage(message) {
3345
+ if (isDefaultStreamMessage(message)) {
3346
+ this.emittedMessages.push(message);
3347
+ }
3348
+ }
3349
+ resetTurnState() {
3350
+ this.lastTokenUsage = null;
3351
+ this.fullText = "";
3352
+ this.finalAssistantText = "";
3353
+ this.structuredOutput = null;
3354
+ this.structuredOutputError = null;
3355
+ this.errors = [];
3356
+ this.emittedMessages = [];
3357
+ }
3051
3358
  };
3359
+ function isInternalMessage(message) {
3360
+ return message.type === "structured_output" || message.type === "tool_use" || message.type === "create_message";
3361
+ }
3362
+ function isDefaultStreamMessage(message) {
3363
+ return message.type === DroidMessageType.Assistant || message.type === DroidMessageType.User || message.type === DroidMessageType.ToolCall || message.type === DroidMessageType.ToolResult || message.type === DroidMessageType.Hook || message.type === DroidMessageType.Error || message.type === DroidMessageType.Result;
3364
+ }
3365
+ function stripTokenUsageType(message) {
3366
+ const {
3367
+ inputTokens,
3368
+ outputTokens,
3369
+ cacheCreationTokens,
3370
+ cacheReadTokens,
3371
+ thinkingTokens
3372
+ } = message;
3373
+ return {
3374
+ inputTokens,
3375
+ outputTokens,
3376
+ cacheCreationTokens,
3377
+ cacheReadTokens,
3378
+ thinkingTokens
3379
+ };
3380
+ }
3381
+ function parseJsonObject(text) {
3382
+ try {
3383
+ const parsed = JSON.parse(text);
3384
+ const result = JsonObjectSchema.safeParse(parsed);
3385
+ return result.success ? result.data : null;
3386
+ } catch {
3387
+ return null;
3388
+ }
3389
+ }
3052
3390
  function normalizeToolResultContent(content) {
3053
3391
  if (content == null) {
3054
3392
  return "";
@@ -3061,6 +3399,9 @@ function normalizeToolResultContent(content) {
3061
3399
  }
3062
3400
  return String(content);
3063
3401
  }
3402
+ function extractTextFromMessage(message) {
3403
+ return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
3404
+ }
3064
3405
 
3065
3406
  // src/helpers.ts
3066
3407
  function wireAbortSignal(signal, onAbort) {
@@ -3076,15 +3417,88 @@ function wireAbortSignal(signal, onAbort) {
3076
3417
  return () => signal.removeEventListener("abort", listener);
3077
3418
  }
3078
3419
  }
3420
+ function getAbortError(signal) {
3421
+ if (signal.reason instanceof Error) {
3422
+ return signal.reason;
3423
+ }
3424
+ return new Error(
3425
+ typeof signal.reason === "string" ? signal.reason : "Operation aborted"
3426
+ );
3427
+ }
3428
+ function throwIfAborted(signal) {
3429
+ if (signal?.aborted) {
3430
+ throw getAbortError(signal);
3431
+ }
3432
+ }
3433
+ async function* streamFromClient(client, sessionId, activeBridges, prompt, options) {
3434
+ throwIfAborted(options?.abortSignal);
3435
+ const startedAt = Date.now();
3436
+ let resolveDone = () => {
3437
+ };
3438
+ const donePromise = new Promise((resolve2) => {
3439
+ resolveDone = resolve2;
3440
+ });
3441
+ const bridge = new MessageBridge(resolveDone, {
3442
+ includePartialMessages: options?.includePartialMessages,
3443
+ sessionId,
3444
+ startedAt,
3445
+ outputFormat: options?.outputFormat
3446
+ });
3447
+ activeBridges.add(bridge);
3448
+ const unsubscribe = client.onNotification(bridge.notificationHandler);
3449
+ let resolveAbort = () => {
3450
+ };
3451
+ const abortPromise = new Promise((resolve2) => {
3452
+ resolveAbort = resolve2;
3453
+ });
3454
+ const cleanupAbortSignal = wireAbortSignal(options?.abortSignal, () => {
3455
+ bridge.signalDone();
3456
+ resolveAbort();
3457
+ void client.interruptSession().catch(() => {
3458
+ });
3459
+ });
3460
+ try {
3461
+ await Promise.race([
3462
+ client.addUserMessage({
3463
+ text: prompt,
3464
+ images: options?.images,
3465
+ files: options?.files,
3466
+ outputFormat: options?.outputFormat
3467
+ }),
3468
+ donePromise,
3469
+ abortPromise
3470
+ ]);
3471
+ throwIfAborted(options?.abortSignal);
3472
+ for await (const msg of bridge.messages()) {
3473
+ throwIfAborted(options?.abortSignal);
3474
+ yield msg;
3475
+ }
3476
+ throwIfAborted(options?.abortSignal);
3477
+ } finally {
3478
+ cleanupAbortSignal();
3479
+ unsubscribe();
3480
+ activeBridges.delete(bridge);
3481
+ }
3482
+ }
3079
3483
  function extractInnerNotification(notification) {
3080
3484
  const parsed = SessionNotificationSchema.safeParse(notification);
3081
3485
  return parsed.success ? parsed.data.params.notification : null;
3082
3486
  }
3083
3487
  var MessageBridge = class {
3488
+ constructor(onDone, _options = {}) {
3489
+ this._options = _options;
3490
+ this._onDone = onDone;
3491
+ this._stateTracker = new StreamStateTracker({
3492
+ sessionId: _options.sessionId,
3493
+ startedAt: _options.startedAt,
3494
+ hasOutputFormat: _options.outputFormat !== void 0
3495
+ });
3496
+ }
3084
3497
  _queue = [];
3498
+ _onDone;
3085
3499
  _resolveWaiting = null;
3086
3500
  _done = false;
3087
- _stateTracker = new StreamStateTracker();
3501
+ _stateTracker;
3088
3502
  notificationHandler = (notification) => {
3089
3503
  const inner = extractInnerNotification(notification);
3090
3504
  if (!inner) return;
@@ -3093,10 +3507,14 @@ var MessageBridge = class {
3093
3507
  const messages = Array.isArray(converted) ? converted : [converted];
3094
3508
  for (const msg of messages) {
3095
3509
  const { message, additional } = this._stateTracker.processMessage(msg);
3096
- this._enqueue(message);
3510
+ if (message && this._shouldYield(message)) {
3511
+ this._enqueue(message);
3512
+ }
3097
3513
  for (const extra of additional) {
3098
- this._enqueue(extra);
3099
- if (extra.type === DroidMessageType.TurnComplete) {
3514
+ if (this._shouldYield(extra)) {
3515
+ this._enqueue(extra);
3516
+ }
3517
+ if (extra.type === DroidMessageType.Result) {
3100
3518
  this._signalDone();
3101
3519
  }
3102
3520
  }
@@ -3110,7 +3528,7 @@ var MessageBridge = class {
3110
3528
  while (this._queue.length > 0) {
3111
3529
  const msg = this._queue.shift();
3112
3530
  yield msg;
3113
- if (msg.type === DroidMessageType.TurnComplete) {
3531
+ if (msg.type === DroidMessageType.Result) {
3114
3532
  return;
3115
3533
  }
3116
3534
  }
@@ -3122,6 +3540,12 @@ var MessageBridge = class {
3122
3540
  });
3123
3541
  }
3124
3542
  }
3543
+ _shouldYield(message) {
3544
+ if (isInternalMessage(message)) {
3545
+ return false;
3546
+ }
3547
+ return this._options.includePartialMessages ? true : isDefaultStreamMessage(message);
3548
+ }
3125
3549
  _enqueue(msg) {
3126
3550
  this._queue.push(msg);
3127
3551
  if (this._resolveWaiting) {
@@ -3131,7 +3555,11 @@ var MessageBridge = class {
3131
3555
  }
3132
3556
  }
3133
3557
  _signalDone() {
3558
+ const wasDone = this._done;
3134
3559
  this._done = true;
3560
+ if (!wasDone) {
3561
+ this._onDone?.();
3562
+ }
3135
3563
  if (this._resolveWaiting) {
3136
3564
  const resolve2 = this._resolveWaiting;
3137
3565
  this._resolveWaiting = null;
@@ -3147,7 +3575,7 @@ async function createTransport(options) {
3147
3575
  execPath: options.execPath,
3148
3576
  execArgs: options.execArgs,
3149
3577
  cwd: options.cwd,
3150
- env: options.env
3578
+ env: { ...options.env, FACTORY_API_KEY: options.apiKey }
3151
3579
  };
3152
3580
  const processTransport = new ProcessTransport(transportOptions);
3153
3581
  await processTransport.connect();
@@ -3205,6 +3633,9 @@ function buildInitParams(options) {
3205
3633
  ...options.disabledToolIds !== void 0 && {
3206
3634
  disabledToolIds: options.disabledToolIds
3207
3635
  },
3636
+ ...options.sessionSource !== void 0 && {
3637
+ sessionSource: options.sessionSource
3638
+ },
3208
3639
  tags: [...options.tags ?? [], SDK_TAG]
3209
3640
  };
3210
3641
  }
@@ -3214,7 +3645,7 @@ var import_node_events = require("events");
3214
3645
  var import_node_http = __toESM(require("http"), 1);
3215
3646
  var import_mcp4 = require("@modelcontextprotocol/sdk/server/mcp.js");
3216
3647
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
3217
- var import_zod8 = require("zod");
3648
+ var import_zod9 = require("zod");
3218
3649
  function tool(name, description, inputSchemaOrHandler, handler) {
3219
3650
  if (typeof inputSchemaOrHandler === "function") {
3220
3651
  const actualHandler = inputSchemaOrHandler;
@@ -3227,7 +3658,7 @@ function tool(name, description, inputSchemaOrHandler, handler) {
3227
3658
  if (!handler) {
3228
3659
  throw new Error(`Missing handler for SDK MCP tool "${name}"`);
3229
3660
  }
3230
- const inputObjectSchema = import_zod8.z.object(inputSchemaOrHandler);
3661
+ const inputObjectSchema = import_zod9.z.object(inputSchemaOrHandler);
3231
3662
  return {
3232
3663
  name,
3233
3664
  description,
@@ -3404,325 +3835,62 @@ async function startSdkMcpServers(servers) {
3404
3835
  };
3405
3836
  }
3406
3837
 
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;
3838
+ // src/session.ts
3839
+ var DroidSession = class {
3840
+ _client;
3841
+ _sessionId;
3842
+ _initResult;
3843
+ _closed = false;
3844
+ _cleanupAbortSignal = null;
3845
+ _cleanupCallbacks = [];
3846
+ _activeBridges = /* @__PURE__ */ new Set();
3847
+ /** @internal */
3848
+ constructor(client, sessionId, initResult) {
3849
+ this._client = client;
3850
+ this._sessionId = sessionId;
3851
+ this._initResult = initResult;
3422
3852
  }
3423
3853
  get sessionId() {
3424
- return this._getSessionId();
3854
+ return this._sessionId;
3425
3855
  }
3426
3856
  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();
3857
+ return this._initResult;
3437
3858
  }
3438
- next(...args) {
3439
- return this._generator.next(...args);
3859
+ /** @internal */
3860
+ setAbortSignalCleanup(cleanup) {
3861
+ this._cleanupAbortSignal = cleanup;
3440
3862
  }
3441
- return(value) {
3442
- return this._generator.return(value);
3863
+ /** @internal */
3864
+ addCleanup(cleanup) {
3865
+ this._cleanupCallbacks.push(cleanup);
3443
3866
  }
3444
- throw(e) {
3445
- return this._generator.throw(e);
3867
+ async *stream(prompt, options) {
3868
+ this._ensureNotClosed();
3869
+ yield* streamFromClient(
3870
+ this._client,
3871
+ this._sessionId,
3872
+ this._activeBridges,
3873
+ prompt,
3874
+ options
3875
+ );
3446
3876
  }
3447
- [Symbol.asyncIterator]() {
3448
- return this;
3877
+ async interrupt() {
3878
+ this._ensureNotClosed();
3879
+ await this._client.interruptSession();
3449
3880
  }
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 {
3480
- if (aborted) {
3481
- throw new Error("Query aborted before initialization");
3482
- }
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");
3489
- }
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;
3504
- }
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;
3528
- }
3529
- }
3530
- const generator = generateMessages();
3531
- async function* wrappedGenerator() {
3532
- try {
3533
- yield* generator;
3534
- } finally {
3535
- cleanupAbortSignal();
3536
- await closeActiveResources();
3537
- }
3538
- }
3539
- const droidQuery = new DroidQueryImpl(
3540
- wrappedGenerator(),
3541
- () => sessionId,
3542
- () => initResult,
3543
- () => ensureInitialized(),
3544
- async () => {
3545
- if (client && !aborted) {
3546
- await client.interruptSession();
3547
- }
3548
- },
3549
- () => {
3550
- aborted = true;
3551
- bridge.signalDone();
3552
- cleanupAbortSignal();
3553
- void closeActiveResources();
3554
- }
3555
- );
3556
- cleanupAbortSignal = wireAbortSignal(
3557
- options.abortSignal,
3558
- () => droidQuery.abort()
3559
- );
3560
- return droidQuery;
3561
- }
3562
-
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
- }
3595
- var DroidSession = class {
3596
- _client;
3597
- _sessionId;
3598
- _initResult;
3599
- _closed = false;
3600
- _cleanupAbortSignal = null;
3601
- _cleanupCallbacks = [];
3602
- /** @internal */
3603
- constructor(client, sessionId, initResult) {
3604
- this._client = client;
3605
- this._sessionId = sessionId;
3606
- this._initResult = initResult;
3607
- }
3608
- get sessionId() {
3609
- return this._sessionId;
3610
- }
3611
- get initResult() {
3612
- return this._initResult;
3613
- }
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`. */
3623
- async *stream(text, options) {
3624
- this._ensureNotClosed();
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;
3632
- });
3633
- const cleanupAbortSignal = wireAbortSignal(options?.abortSignal, () => {
3634
- bridge.signalDone();
3635
- resolveAbort();
3636
- void this._client.interruptSession().catch(() => {
3637
- });
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;
3653
- }
3654
- throwIfAborted(options?.abortSignal);
3655
- } finally {
3656
- cleanupAbortSignal();
3657
- unsubscribe();
3658
- }
3659
- }
3660
- /** Consumes the stream and returns an aggregated {@link DroidResult}. */
3661
- async send(text, options) {
3662
- this._ensureNotClosed();
3663
- const messages = [];
3664
- let fullText = "";
3665
- let lastTokenUsage = null;
3666
- let firstError = null;
3667
- let structuredOutput = null;
3668
- let finalAssistantText = "";
3669
- let turnCount = 0;
3670
- const startedAt = Date.now();
3671
- for await (const msg of this.stream(text, options)) {
3672
- messages.push(msg);
3673
- if (msg.type === DroidMessageType.AssistantTextDelta) {
3674
- fullText += msg.text;
3675
- }
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) {
3684
- lastTokenUsage = msg;
3685
- }
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
- }
3700
- }
3701
- }
3702
- return {
3703
- sessionId: this._sessionId,
3704
- text: fullText,
3705
- messages,
3706
- tokenUsage: lastTokenUsage,
3707
- durationMs: Date.now() - startedAt,
3708
- turnCount,
3709
- error: firstError,
3710
- structuredOutput,
3711
- success: firstError === null
3712
- };
3713
- }
3714
- async interrupt() {
3715
- this._ensureNotClosed();
3716
- await this._client.interruptSession();
3717
- }
3718
- async close() {
3719
- if (this._closed) {
3720
- return;
3881
+ async close() {
3882
+ if (this._closed) {
3883
+ return;
3721
3884
  }
3722
3885
  this._closed = true;
3723
3886
  this._cleanupAbortSignal?.();
3724
3887
  this._cleanupAbortSignal = null;
3888
+ for (const bridge of this._activeBridges) {
3889
+ bridge.signalDone();
3890
+ }
3725
3891
  try {
3892
+ await this._client.closeSession({ reason: "other" }).catch(() => {
3893
+ });
3726
3894
  await this._client.close();
3727
3895
  } finally {
3728
3896
  const cleanups = this._cleanupCallbacks.splice(0);
@@ -3807,7 +3975,7 @@ var DroidSession = class {
3807
3975
  }
3808
3976
  }
3809
3977
  };
3810
- async function createSession(options = {}) {
3978
+ async function createSession(options) {
3811
3979
  const { client } = await createConfiguredClient(options);
3812
3980
  let cleanupInitAbortSignal = options.abortSignal?.aborted ? () => {
3813
3981
  } : wireAbortSignal(options.abortSignal, () => {
@@ -3837,7 +4005,7 @@ async function createSession(options = {}) {
3837
4005
  throw error;
3838
4006
  }
3839
4007
  }
3840
- async function resumeSession(sessionId, options = {}) {
4008
+ async function resumeSession(sessionId, options) {
3841
4009
  const { client } = await createConfiguredClient(options);
3842
4010
  let sdkMcpServers;
3843
4011
  try {
@@ -3861,10 +4029,18 @@ async function resumeSession(sessionId, options = {}) {
3861
4029
  }
3862
4030
 
3863
4031
  // src/run.ts
3864
- async function run(text, options = {}) {
4032
+ async function run(prompt, options) {
3865
4033
  const session = await createSession(options);
3866
4034
  try {
3867
- return await session.send(text, options);
4035
+ for await (const msg of session.stream(prompt, {
4036
+ ...options,
4037
+ includePartialMessages: false
4038
+ })) {
4039
+ if (msg.type === DroidMessageType.Result) {
4040
+ return msg;
4041
+ }
4042
+ }
4043
+ throw new Error("Stream completed without a result message");
3868
4044
  } finally {
3869
4045
  await session.close();
3870
4046
  }
@@ -4093,6 +4269,1431 @@ async function listSessions(options = {}) {
4093
4269
  }
4094
4270
  return sorted;
4095
4271
  }
4272
+
4273
+ // src/api-types.ts
4274
+ var import_zod10 = require("zod");
4275
+ var EnvironmentVariableSchema = import_zod10.z.object({
4276
+ key: import_zod10.z.string(),
4277
+ value: import_zod10.z.string()
4278
+ });
4279
+ var MachineTemplateBuildStatusSchema = import_zod10.z.object({
4280
+ status: import_zod10.z.enum(["building", "success", "failed"]),
4281
+ failureReason: import_zod10.z.enum(["setup_script_error", "system_error"]).optional(),
4282
+ buildStartedAt: import_zod10.z.number().int().optional(),
4283
+ builtAt: import_zod10.z.number().int().optional(),
4284
+ logs: import_zod10.z.string().optional()
4285
+ });
4286
+ var MachineTemplateSchema = import_zod10.z.object({
4287
+ templateId: import_zod10.z.string(),
4288
+ repoUrl: import_zod10.z.string(),
4289
+ templateName: import_zod10.z.string(),
4290
+ defaultBranch: import_zod10.z.string(),
4291
+ createdBy: import_zod10.z.string(),
4292
+ createdAt: import_zod10.z.number().int().optional(),
4293
+ buildStatus: MachineTemplateBuildStatusSchema.optional(),
4294
+ lastUpdatedAt: import_zod10.z.number().int().nullable().optional(),
4295
+ environmentVariables: import_zod10.z.array(EnvironmentVariableSchema).optional(),
4296
+ userEnvironmentVariablesByUser: import_zod10.z.array(EnvironmentVariableSchema).optional(),
4297
+ setupScript: import_zod10.z.string().optional()
4298
+ });
4299
+ var MachineTemplateListResponseSchema = import_zod10.z.object({
4300
+ templates: import_zod10.z.array(MachineTemplateSchema),
4301
+ pagination: import_zod10.z.object({
4302
+ hasMore: import_zod10.z.boolean(),
4303
+ nextCursor: import_zod10.z.string().nullable()
4304
+ })
4305
+ });
4306
+ var ComputerSchema = import_zod10.z.object({
4307
+ id: import_zod10.z.string(),
4308
+ name: import_zod10.z.string(),
4309
+ hostname: import_zod10.z.string().optional(),
4310
+ providerType: import_zod10.z.enum(["byom", "e2b"]),
4311
+ status: import_zod10.z.enum(["provisioning", "active", "error"]).optional(),
4312
+ createdAt: import_zod10.z.number().int(),
4313
+ relayClientUrl: import_zod10.z.string().optional(),
4314
+ remoteUser: import_zod10.z.string().optional()
4315
+ }).passthrough();
4316
+ var ComputerListResponseSchema = import_zod10.z.object({
4317
+ computers: import_zod10.z.array(ComputerSchema)
4318
+ });
4319
+ var RefreshComputerResponseSchema = import_zod10.z.object({
4320
+ configured: import_zod10.z.number().int()
4321
+ });
4322
+ var ComputerMetricSchema = import_zod10.z.object({
4323
+ timestamp: import_zod10.z.string(),
4324
+ cpuUsedPct: import_zod10.z.number(),
4325
+ cpuCount: import_zod10.z.number(),
4326
+ memUsed: import_zod10.z.number(),
4327
+ memTotal: import_zod10.z.number(),
4328
+ diskUsed: import_zod10.z.number(),
4329
+ diskTotal: import_zod10.z.number()
4330
+ });
4331
+ var ComputerMetricsResponseSchema = import_zod10.z.array(ComputerMetricSchema);
4332
+ var RemoteSessionSchema = import_zod10.z.object({
4333
+ sessionId: import_zod10.z.string(),
4334
+ title: import_zod10.z.string().optional(),
4335
+ status: import_zod10.z.enum(["idle", "pending", "running"]),
4336
+ messageCount: import_zod10.z.number().int(),
4337
+ createdAt: import_zod10.z.number().int(),
4338
+ updatedAt: import_zod10.z.number().int(),
4339
+ completedAt: import_zod10.z.number().int().optional(),
4340
+ computerId: import_zod10.z.string().optional()
4341
+ });
4342
+ var RemoteSessionListResponseSchema = import_zod10.z.object({
4343
+ sessions: import_zod10.z.array(RemoteSessionSchema),
4344
+ pagination: import_zod10.z.object({
4345
+ hasMore: import_zod10.z.boolean(),
4346
+ nextCursor: import_zod10.z.string().nullable()
4347
+ })
4348
+ });
4349
+
4350
+ // src/api.ts
4351
+ var DEFAULT_BASE_URL = "https://api.factory.ai";
4352
+ function extractErrorMessage(body, status) {
4353
+ if (isRecord(body) && typeof body["error"] === "string") {
4354
+ return body["error"];
4355
+ }
4356
+ return `Factory API error (status ${status})`;
4357
+ }
4358
+ async function factoryFetch(path3, apiKey, baseUrl, options) {
4359
+ const url = `${baseUrl ?? DEFAULT_BASE_URL}${path3}`;
4360
+ const method = options?.method ?? "GET";
4361
+ const headers = {
4362
+ Authorization: `Bearer ${apiKey}`,
4363
+ Accept: "application/json"
4364
+ };
4365
+ if (options?.body) {
4366
+ headers["Content-Type"] = "application/json";
4367
+ }
4368
+ let response;
4369
+ try {
4370
+ response = await fetch(url, {
4371
+ method,
4372
+ headers,
4373
+ ...options?.body ? { body: JSON.stringify(options.body) } : {}
4374
+ });
4375
+ } catch (error) {
4376
+ throw new ConnectionError(
4377
+ `Failed to reach Factory API: ${error instanceof Error ? error.message : String(error)}`
4378
+ );
4379
+ }
4380
+ if (response.status === 204) {
4381
+ return void 0;
4382
+ }
4383
+ let body;
4384
+ try {
4385
+ body = await response.json();
4386
+ } catch {
4387
+ throw new ProtocolError(
4388
+ `Factory API returned non-JSON response (status ${response.status})`
4389
+ );
4390
+ }
4391
+ if (!response.ok) {
4392
+ const message = extractErrorMessage(body, response.status);
4393
+ if (response.status === 401 || response.status === 403) {
4394
+ throw new ProtocolError(`Invalid or expired API key: ${message}`, {
4395
+ code: response.status
4396
+ });
4397
+ }
4398
+ throw new ProtocolError(message, { code: response.status });
4399
+ }
4400
+ return body;
4401
+ }
4402
+ function parseResponse(body, schema) {
4403
+ const parsed = schema.safeParse(body);
4404
+ if (!parsed.success) {
4405
+ throw new ProtocolError(
4406
+ `Unexpected response format from Factory API: ${parsed.error.message}`
4407
+ );
4408
+ }
4409
+ return parsed.data;
4410
+ }
4411
+ async function listMachineTemplates(options) {
4412
+ const params = new URLSearchParams();
4413
+ if (options.limit != null) {
4414
+ params.set("limit", String(options.limit));
4415
+ }
4416
+ if (options.cursor != null) {
4417
+ params.set("cursor", options.cursor);
4418
+ }
4419
+ const query = params.toString();
4420
+ const path3 = `/api/v0/machines/templates${query ? `?${query}` : ""}`;
4421
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4422
+ return parseResponse(body, MachineTemplateListResponseSchema);
4423
+ }
4424
+ async function getMachineTemplate(options) {
4425
+ const path3 = `/api/v0/machines/templates/${encodeURIComponent(options.templateId)}`;
4426
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4427
+ return parseResponse(body, MachineTemplateSchema);
4428
+ }
4429
+ async function listComputers(options) {
4430
+ const path3 = "/api/v0/computers";
4431
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4432
+ return parseResponse(body, ComputerListResponseSchema);
4433
+ }
4434
+ async function getComputer(options) {
4435
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}`;
4436
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4437
+ return parseResponse(body, ComputerSchema);
4438
+ }
4439
+ async function createComputer(options) {
4440
+ const path3 = "/api/v0/computers";
4441
+ const reqBody = {
4442
+ name: options.name,
4443
+ remoteUser: options.remoteUser
4444
+ };
4445
+ if (options.provider != null) reqBody["provider"] = options.provider;
4446
+ if (options.hostId != null) reqBody["hostId"] = options.hostId;
4447
+ if (options.repos != null) reqBody["repos"] = options.repos;
4448
+ if (options.autoInstallDeps != null)
4449
+ reqBody["autoInstallDeps"] = options.autoInstallDeps;
4450
+ if (options.serviceAccountId != null)
4451
+ reqBody["serviceAccountId"] = options.serviceAccountId;
4452
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl, {
4453
+ method: "POST",
4454
+ body: reqBody
4455
+ });
4456
+ return parseResponse(body, ComputerSchema);
4457
+ }
4458
+ async function getComputerByName(options) {
4459
+ const path3 = `/api/v0/computers/name/${encodeURIComponent(options.name)}`;
4460
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4461
+ return parseResponse(body, ComputerSchema);
4462
+ }
4463
+ async function updateComputer(options) {
4464
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}`;
4465
+ const reqBody = {};
4466
+ if (options.name != null) reqBody["name"] = options.name;
4467
+ if (options.remoteUser != null) reqBody["remoteUser"] = options.remoteUser;
4468
+ if (options.hostId != null) reqBody["hostId"] = options.hostId;
4469
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl, {
4470
+ method: "PATCH",
4471
+ body: reqBody
4472
+ });
4473
+ return parseResponse(body, ComputerSchema);
4474
+ }
4475
+ async function deleteComputer(options) {
4476
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}`;
4477
+ await factoryFetch(path3, options.apiKey, options.baseUrl, {
4478
+ method: "DELETE"
4479
+ });
4480
+ }
4481
+ async function restartComputer(options) {
4482
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}/restart`;
4483
+ await factoryFetch(path3, options.apiKey, options.baseUrl, {
4484
+ method: "POST"
4485
+ });
4486
+ }
4487
+ async function refreshComputer(options) {
4488
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}/refresh`;
4489
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl, {
4490
+ method: "POST"
4491
+ });
4492
+ return parseResponse(body, RefreshComputerResponseSchema);
4493
+ }
4494
+ async function getComputerMetrics(options) {
4495
+ const params = new URLSearchParams();
4496
+ if (options.start != null) {
4497
+ params.set("start", options.start);
4498
+ }
4499
+ const query = params.toString();
4500
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}/metrics${query ? `?${query}` : ""}`;
4501
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4502
+ return parseResponse(body, ComputerMetricsResponseSchema);
4503
+ }
4504
+ async function retryInstallDeps(options) {
4505
+ const path3 = `/api/v0/computers/${encodeURIComponent(options.computerId)}/install-deps`;
4506
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl, {
4507
+ method: "POST"
4508
+ });
4509
+ return parseResponse(body, ComputerSchema);
4510
+ }
4511
+ async function listRemoteSessions(options) {
4512
+ const params = new URLSearchParams();
4513
+ if (options.computerId != null) {
4514
+ params.set("computerId", options.computerId);
4515
+ }
4516
+ if (options.limit != null) {
4517
+ params.set("limit", String(options.limit));
4518
+ }
4519
+ if (options.cursor != null) {
4520
+ params.set("cursor", options.cursor);
4521
+ }
4522
+ const query = params.toString();
4523
+ const path3 = `/api/v0/sessions${query ? `?${query}` : ""}`;
4524
+ const body = await factoryFetch(path3, options.apiKey, options.baseUrl);
4525
+ return parseResponse(body, RemoteSessionListResponseSchema);
4526
+ }
4527
+
4528
+ // src/daemon/client.ts
4529
+ var DAEMON_SERVER_REQUEST_METHODS = {
4530
+ "daemon.request_permission": "permission" /* Permission */,
4531
+ "daemon.ask_user": "askUser" /* AskUser */
4532
+ };
4533
+ var DaemonClient = class {
4534
+ _engine;
4535
+ _apiKey;
4536
+ _sessionId = null;
4537
+ _closed = false;
4538
+ _notificationListeners = [];
4539
+ _permissionHandler = null;
4540
+ _askUserHandler = null;
4541
+ constructor(options) {
4542
+ this._apiKey = options.apiKey;
4543
+ this._engine = new ProtocolEngine({
4544
+ transport: options.transport,
4545
+ serverRequestMethodMap: DAEMON_SERVER_REQUEST_METHODS
4546
+ });
4547
+ this._engine.onNotification((notification) => {
4548
+ const normalized = notification["method"] === "daemon.session_notification" ? { ...notification, method: "droid.session_notification" } : notification;
4549
+ dispatchNotification(normalized, [...this._notificationListeners]);
4550
+ });
4551
+ this._engine.setPermissionHandler(
4552
+ (params) => this._dispatchPermissionRequest(params)
4553
+ );
4554
+ this._engine.setAskUserHandler(
4555
+ (params) => this._dispatchAskUserRequest(params)
4556
+ );
4557
+ }
4558
+ get sessionId() {
4559
+ return this._sessionId;
4560
+ }
4561
+ get isConnected() {
4562
+ return !this._closed && this._engine.isHealthy;
4563
+ }
4564
+ async initializeSession(params) {
4565
+ this._ensureNotClosed();
4566
+ const result = await this._rpc(
4567
+ "daemon.initialize_session" /* INITIALIZE_SESSION */,
4568
+ { ...params, token: this._apiKey },
4569
+ InitializeSessionResultSchema,
4570
+ SESSION_INIT_TIMEOUT
4571
+ );
4572
+ this._sessionId = result.sessionId;
4573
+ return result;
4574
+ }
4575
+ async loadSession(params) {
4576
+ this._ensureNotClosed();
4577
+ const result = await this._rpc(
4578
+ "daemon.load_session" /* LOAD_SESSION */,
4579
+ { ...params, token: this._apiKey },
4580
+ LoadSessionResultSchema,
4581
+ SESSION_INIT_TIMEOUT
4582
+ );
4583
+ this._sessionId = params.sessionId;
4584
+ return result;
4585
+ }
4586
+ async addUserMessage(params) {
4587
+ return this._sessionRpc(
4588
+ "daemon.add_user_message" /* ADD_USER_MESSAGE */,
4589
+ params,
4590
+ AddUserMessageResultSchema
4591
+ );
4592
+ }
4593
+ async interruptSession() {
4594
+ return this._sessionRpc(
4595
+ "daemon.interrupt_session" /* INTERRUPT_SESSION */,
4596
+ {},
4597
+ InterruptSessionResultSchema
4598
+ );
4599
+ }
4600
+ async closeSession(params = {}) {
4601
+ return this._sessionRpc(
4602
+ "daemon.close_session" /* CLOSE_SESSION */,
4603
+ params,
4604
+ CloseSessionResultSchema
4605
+ );
4606
+ }
4607
+ async updateSessionSettings(params) {
4608
+ return this._sessionRpc(
4609
+ "daemon.update_session_settings" /* UPDATE_SESSION_SETTINGS */,
4610
+ params,
4611
+ UpdateSessionSettingsResultSchema
4612
+ );
4613
+ }
4614
+ async compactSession(params = {}) {
4615
+ return this._sessionRpc(
4616
+ "daemon.compact_session" /* COMPACT_SESSION */,
4617
+ params,
4618
+ CompactSessionResultSchema,
4619
+ COMPACTION_TIMEOUT
4620
+ );
4621
+ }
4622
+ async forkSession() {
4623
+ return this._sessionRpc(
4624
+ "daemon.fork_session" /* FORK_SESSION */,
4625
+ {},
4626
+ ForkSessionResultSchema
4627
+ );
4628
+ }
4629
+ async getContextBreakdown() {
4630
+ return this._sessionRpc(
4631
+ "daemon.get_context_breakdown" /* GET_CONTEXT_STATS */,
4632
+ {},
4633
+ ContextBreakdownResultSchema
4634
+ );
4635
+ }
4636
+ async renameSession(params) {
4637
+ return this._sessionRpc(
4638
+ "daemon.rename_session" /* RENAME_SESSION */,
4639
+ params,
4640
+ RenameSessionResultSchema
4641
+ );
4642
+ }
4643
+ async getRewindInfo(params) {
4644
+ return this._sessionRpc(
4645
+ "daemon.get_rewind_info" /* GET_REWIND_INFO */,
4646
+ params,
4647
+ GetRewindInfoResultSchema,
4648
+ REWIND_TIMEOUT
4649
+ );
4650
+ }
4651
+ async executeRewind(params) {
4652
+ return this._sessionRpc(
4653
+ "daemon.execute_rewind" /* EXECUTE_REWIND */,
4654
+ params,
4655
+ ExecuteRewindResultSchema,
4656
+ REWIND_TIMEOUT
4657
+ );
4658
+ }
4659
+ async addMcpServer(params) {
4660
+ return this._sessionRpc(
4661
+ "daemon.add_mcp_server" /* ADD_MCP_SERVER */,
4662
+ params,
4663
+ AddMcpServerResultSchema
4664
+ );
4665
+ }
4666
+ async removeMcpServer(params) {
4667
+ return this._sessionRpc(
4668
+ "daemon.remove_mcp_server" /* REMOVE_MCP_SERVER */,
4669
+ params,
4670
+ RemoveMcpServerResultSchema
4671
+ );
4672
+ }
4673
+ async toggleMcpServer(params) {
4674
+ return this._sessionRpc(
4675
+ "daemon.toggle_mcp_server" /* TOGGLE_MCP_SERVER */,
4676
+ params,
4677
+ ToggleMcpServerResultSchema
4678
+ );
4679
+ }
4680
+ async listMcpServers() {
4681
+ return this._sessionRpc(
4682
+ "daemon.list_mcp_servers" /* LIST_MCP_SERVERS */,
4683
+ {},
4684
+ ListMcpServersResultSchema
4685
+ );
4686
+ }
4687
+ async listMcpTools() {
4688
+ return this._sessionRpc(
4689
+ "daemon.list_mcp_tools" /* LIST_MCP_TOOLS */,
4690
+ {},
4691
+ ListMcpToolsResultSchema
4692
+ );
4693
+ }
4694
+ async authenticateMcpServer(params) {
4695
+ return this._sessionRpc(
4696
+ "daemon.authenticate_mcp_server" /* AUTHENTICATE_MCP_SERVER */,
4697
+ params,
4698
+ AuthenticateMcpServerResultSchema
4699
+ );
4700
+ }
4701
+ async listSkills() {
4702
+ return this._sessionRpc(
4703
+ "daemon.list_skills" /* LIST_SKILLS */,
4704
+ {},
4705
+ ListSkillsResultSchema
4706
+ );
4707
+ }
4708
+ onNotification(callback, filter) {
4709
+ const entry = { callback, filter };
4710
+ this._notificationListeners.push(entry);
4711
+ let unsubscribed = false;
4712
+ return () => {
4713
+ if (!unsubscribed) {
4714
+ unsubscribed = true;
4715
+ const idx = this._notificationListeners.indexOf(entry);
4716
+ if (idx !== -1) {
4717
+ this._notificationListeners.splice(idx, 1);
4718
+ }
4719
+ }
4720
+ };
4721
+ }
4722
+ setPermissionHandler(handler) {
4723
+ this._permissionHandler = handler;
4724
+ }
4725
+ setAskUserHandler(handler) {
4726
+ this._askUserHandler = handler;
4727
+ }
4728
+ async close() {
4729
+ if (this._closed) {
4730
+ return;
4731
+ }
4732
+ this._closed = true;
4733
+ this._notificationListeners.length = 0;
4734
+ this._permissionHandler = null;
4735
+ this._askUserHandler = null;
4736
+ await this._engine.close();
4737
+ }
4738
+ async _rpc(method, params, schema, timeout) {
4739
+ const raw = await this._engine.sendRequest(method, params, timeout);
4740
+ return schema.parse(raw);
4741
+ }
4742
+ async _sessionRpc(method, params, schema, timeout) {
4743
+ this._ensureNotClosed();
4744
+ this._ensureSession();
4745
+ return this._rpc(
4746
+ method,
4747
+ { sessionId: this._sessionId, ...params },
4748
+ schema,
4749
+ timeout
4750
+ );
4751
+ }
4752
+ _dispatchPermissionRequest(params) {
4753
+ const handler = this._permissionHandler;
4754
+ if (handler == null) {
4755
+ return "cancel" /* Cancel */;
4756
+ }
4757
+ return handler(params);
4758
+ }
4759
+ _dispatchAskUserRequest(params) {
4760
+ const handler = this._askUserHandler;
4761
+ if (handler == null) {
4762
+ return { cancelled: true, answers: [] };
4763
+ }
4764
+ return handler(params);
4765
+ }
4766
+ _ensureNotClosed() {
4767
+ if (this._closed) {
4768
+ throw new ConnectionError(
4769
+ "Daemon client has been closed. Create a new DaemonClient instance."
4770
+ );
4771
+ }
4772
+ }
4773
+ _ensureSession() {
4774
+ if (this._sessionId == null) {
4775
+ throw new SessionError(
4776
+ "No active session. Call initializeSession or loadSession first."
4777
+ );
4778
+ }
4779
+ }
4780
+ };
4781
+
4782
+ // src/daemon/local.ts
4783
+ var import_node_child_process2 = require("child_process");
4784
+ var fs2 = __toESM(require("fs"), 1);
4785
+ var net = __toESM(require("net"), 1);
4786
+ var os2 = __toESM(require("os"), 1);
4787
+ var path2 = __toESM(require("path"), 1);
4788
+ var SOCKET_TIMEOUT_MS = 2e3;
4789
+ var STARTUP_POLL_INTERVAL_MS = 250;
4790
+ var STARTUP_TIMEOUT_MS = 3e4;
4791
+ var MAX_STARTUP_ATTEMPTS = 3;
4792
+ var FACTORY_DIR = ".factory";
4793
+ var DEFAULT_PORT = 37643;
4794
+ var DAEMON_PORT_FILE = "daemon.port";
4795
+ var DEFAULT_HOST = "127.0.0.1";
4796
+ var spawnedDaemonProcess = null;
4797
+ var daemonTarget = null;
4798
+ var daemonEnsureInflight = null;
4799
+ function getFactoryHome() {
4800
+ return process.env.FACTORY_HOME_OVERRIDE || os2.homedir();
4801
+ }
4802
+ function getFactoryDirName() {
4803
+ return FACTORY_DIR;
4804
+ }
4805
+ function getFactoryDir() {
4806
+ return path2.join(getFactoryHome(), getFactoryDirName());
4807
+ }
4808
+ function getSdkDir() {
4809
+ return path2.join(getFactoryDir(), "sdk");
4810
+ }
4811
+ function getDefaultDaemonPort() {
4812
+ return DEFAULT_PORT;
4813
+ }
4814
+ function resolveExecPath() {
4815
+ const override = process.env.FACTORY_DROID_BINARY?.trim();
4816
+ if (override && override.length > 0) {
4817
+ if (override.includes("/") || override.includes("\\")) {
4818
+ try {
4819
+ fs2.accessSync(override, fs2.constants.X_OK);
4820
+ return override;
4821
+ } catch {
4822
+ }
4823
+ } else {
4824
+ return override;
4825
+ }
4826
+ }
4827
+ return "droid";
4828
+ }
4829
+ async function allocatePort() {
4830
+ return new Promise((resolve2, reject) => {
4831
+ const server = net.createServer();
4832
+ server.once("error", reject);
4833
+ server.listen(0, DEFAULT_HOST, () => {
4834
+ const address = server.address();
4835
+ if (!address || typeof address === "string") {
4836
+ server.close();
4837
+ reject(new Error("Failed to determine dynamic port"));
4838
+ return;
4839
+ }
4840
+ const port = address.port;
4841
+ server.close((err) => {
4842
+ if (err) reject(err);
4843
+ else resolve2(port);
4844
+ });
4845
+ });
4846
+ });
4847
+ }
4848
+ async function isDaemonReachable(port) {
4849
+ return new Promise((resolve2) => {
4850
+ const socket = net.createConnection({ host: DEFAULT_HOST, port });
4851
+ const cleanup = () => {
4852
+ socket.removeAllListeners();
4853
+ socket.destroy();
4854
+ };
4855
+ const fail = () => {
4856
+ cleanup();
4857
+ resolve2(false);
4858
+ };
4859
+ socket.setTimeout(SOCKET_TIMEOUT_MS, fail);
4860
+ socket.once("error", fail);
4861
+ socket.once("connect", () => {
4862
+ cleanup();
4863
+ resolve2(true);
4864
+ });
4865
+ });
4866
+ }
4867
+ async function waitForDaemonReady(child, port, timeoutMs = STARTUP_TIMEOUT_MS) {
4868
+ return new Promise((resolve2) => {
4869
+ let settled = false;
4870
+ let exited = false;
4871
+ const deadline = Date.now() + timeoutMs;
4872
+ const settle = (result) => {
4873
+ if (settled) return;
4874
+ settled = true;
4875
+ child.removeListener("exit", onExit);
4876
+ child.removeListener("error", onExit);
4877
+ resolve2(result);
4878
+ };
4879
+ const onExit = () => {
4880
+ exited = true;
4881
+ settle("exited");
4882
+ };
4883
+ child.once("exit", onExit);
4884
+ child.once("error", onExit);
4885
+ const poll = async () => {
4886
+ while (!exited && !settled) {
4887
+ if (await isDaemonReachable(port)) {
4888
+ settle("ready");
4889
+ return;
4890
+ }
4891
+ if (Date.now() >= deadline) {
4892
+ settle("timeout");
4893
+ return;
4894
+ }
4895
+ await new Promise((r) => setTimeout(r, STARTUP_POLL_INTERVAL_MS));
4896
+ }
4897
+ };
4898
+ void poll();
4899
+ });
4900
+ }
4901
+ function readPortFile() {
4902
+ try {
4903
+ const portPath = path2.join(getSdkDir(), DAEMON_PORT_FILE);
4904
+ const content = fs2.readFileSync(portPath, "utf-8").trim();
4905
+ const port = parseInt(content, 10);
4906
+ if (Number.isFinite(port) && port > 0 && port < 65536) {
4907
+ return port;
4908
+ }
4909
+ return null;
4910
+ } catch {
4911
+ return null;
4912
+ }
4913
+ }
4914
+ function writePortFile(port) {
4915
+ try {
4916
+ const sdkDir = getSdkDir();
4917
+ fs2.mkdirSync(sdkDir, { recursive: true });
4918
+ fs2.writeFileSync(path2.join(sdkDir, DAEMON_PORT_FILE), String(port), {
4919
+ mode: 384
4920
+ });
4921
+ } catch {
4922
+ }
4923
+ }
4924
+ function cacheTarget(port) {
4925
+ daemonTarget = { host: DEFAULT_HOST, port };
4926
+ return { port };
4927
+ }
4928
+ function clearSpawnedDaemonProcess(child) {
4929
+ if (spawnedDaemonProcess === child) {
4930
+ spawnedDaemonProcess = null;
4931
+ }
4932
+ }
4933
+ async function spawnDaemon(execPath, port) {
4934
+ const args = ["daemon", "--host", DEFAULT_HOST, "--port", String(port)];
4935
+ let stderrFd;
4936
+ try {
4937
+ const logsDir = path2.join(getSdkDir(), "logs");
4938
+ fs2.mkdirSync(logsDir, { recursive: true });
4939
+ stderrFd = fs2.openSync(path2.join(logsDir, "daemon-stderr.log"), "a");
4940
+ } catch {
4941
+ }
4942
+ const child = (0, import_node_child_process2.spawn)(execPath, args, {
4943
+ detached: true,
4944
+ stdio: ["ignore", "ignore", stderrFd ?? "ignore"],
4945
+ cwd: os2.homedir(),
4946
+ env: { ...process.env }
4947
+ });
4948
+ if (stderrFd !== void 0) {
4949
+ try {
4950
+ fs2.closeSync(stderrFd);
4951
+ } catch {
4952
+ }
4953
+ }
4954
+ spawnedDaemonProcess = child;
4955
+ child.unref();
4956
+ child.once("exit", () => {
4957
+ clearSpawnedDaemonProcess(child);
4958
+ });
4959
+ child.on("error", () => {
4960
+ clearSpawnedDaemonProcess(child);
4961
+ });
4962
+ const result = await waitForDaemonReady(child, port);
4963
+ if (result !== "ready") {
4964
+ clearSpawnedDaemonProcess(child);
4965
+ if (result === "timeout") {
4966
+ try {
4967
+ child.kill("SIGTERM");
4968
+ } catch {
4969
+ }
4970
+ }
4971
+ }
4972
+ return result;
4973
+ }
4974
+ async function _ensureLocalDaemon() {
4975
+ const execPath = resolveExecPath();
4976
+ const wellKnownPort = getDefaultDaemonPort();
4977
+ if (await isDaemonReachable(wellKnownPort)) {
4978
+ return cacheTarget(wellKnownPort);
4979
+ }
4980
+ const portFilePort = readPortFile();
4981
+ if (portFilePort !== null && portFilePort !== wellKnownPort) {
4982
+ if (await isDaemonReachable(portFilePort)) {
4983
+ return cacheTarget(portFilePort);
4984
+ }
4985
+ }
4986
+ const firstResult = await spawnDaemon(execPath, wellKnownPort);
4987
+ if (firstResult === "ready") {
4988
+ writePortFile(wellKnownPort);
4989
+ return cacheTarget(wellKnownPort);
4990
+ }
4991
+ for (let attempt = 2; attempt <= MAX_STARTUP_ATTEMPTS; attempt++) {
4992
+ const port = await allocatePort();
4993
+ const result = await spawnDaemon(execPath, port);
4994
+ if (result === "ready") {
4995
+ writePortFile(port);
4996
+ return cacheTarget(port);
4997
+ }
4998
+ }
4999
+ throw new ConnectionError(
5000
+ `Failed to start local droid daemon after ${MAX_STARTUP_ATTEMPTS} attempts. Ensure the \`droid\` CLI is installed and \`droid auth login\` has been run.`
5001
+ );
5002
+ }
5003
+ async function ensureLocalDaemon() {
5004
+ if (daemonTarget) {
5005
+ if (await isDaemonReachable(daemonTarget.port)) {
5006
+ return { port: daemonTarget.port };
5007
+ }
5008
+ daemonTarget = null;
5009
+ }
5010
+ if (!daemonEnsureInflight) {
5011
+ daemonEnsureInflight = _ensureLocalDaemon().finally(() => {
5012
+ daemonEnsureInflight = null;
5013
+ });
5014
+ }
5015
+ return daemonEnsureInflight;
5016
+ }
5017
+
5018
+ // src/daemon/session.ts
5019
+ var DaemonSession = class {
5020
+ _client;
5021
+ _sessionId;
5022
+ _closed = false;
5023
+ _activeBridges = /* @__PURE__ */ new Set();
5024
+ _cleanupCallbacks = [];
5025
+ /** @internal */
5026
+ constructor(client, sessionId) {
5027
+ this._client = client;
5028
+ this._sessionId = sessionId;
5029
+ }
5030
+ /** @internal */
5031
+ addCleanup(cleanup) {
5032
+ this._cleanupCallbacks.push(cleanup);
5033
+ }
5034
+ get sessionId() {
5035
+ return this._sessionId;
5036
+ }
5037
+ async *stream(prompt, options) {
5038
+ this._ensureNotClosed();
5039
+ yield* streamFromClient(
5040
+ this._client,
5041
+ this._sessionId,
5042
+ this._activeBridges,
5043
+ prompt,
5044
+ options
5045
+ );
5046
+ }
5047
+ async send(prompt, options) {
5048
+ this._ensureNotClosed();
5049
+ await this._client.addUserMessage({
5050
+ text: prompt,
5051
+ images: options?.images,
5052
+ files: options?.files,
5053
+ outputFormat: options?.outputFormat
5054
+ });
5055
+ }
5056
+ async interrupt() {
5057
+ this._ensureNotClosed();
5058
+ await this._client.interruptSession();
5059
+ }
5060
+ async close() {
5061
+ if (this._closed) {
5062
+ return;
5063
+ }
5064
+ this._closed = true;
5065
+ for (const bridge of this._activeBridges) {
5066
+ bridge.signalDone();
5067
+ }
5068
+ try {
5069
+ await this._client.closeSession({ reason: "other" }).catch(() => {
5070
+ });
5071
+ } finally {
5072
+ await this._client.close();
5073
+ for (const cleanup of this._cleanupCallbacks) {
5074
+ try {
5075
+ await cleanup();
5076
+ } catch {
5077
+ }
5078
+ }
5079
+ this._cleanupCallbacks.length = 0;
5080
+ }
5081
+ }
5082
+ async updateSettings(params) {
5083
+ this._ensureNotClosed();
5084
+ return this._client.updateSessionSettings(params);
5085
+ }
5086
+ async enterSpecMode(params = {}) {
5087
+ this._ensureNotClosed();
5088
+ return this._client.updateSessionSettings({
5089
+ interactionMode: "spec" /* Spec */,
5090
+ ...params
5091
+ });
5092
+ }
5093
+ async compactSession(params) {
5094
+ this._ensureNotClosed();
5095
+ return this._client.compactSession(params ?? {});
5096
+ }
5097
+ async forkSession() {
5098
+ this._ensureNotClosed();
5099
+ return this._client.forkSession();
5100
+ }
5101
+ async getContextBreakdown() {
5102
+ this._ensureNotClosed();
5103
+ return this._client.getContextBreakdown();
5104
+ }
5105
+ async renameSession(params) {
5106
+ this._ensureNotClosed();
5107
+ return this._client.renameSession(params);
5108
+ }
5109
+ async getRewindInfo(params) {
5110
+ this._ensureNotClosed();
5111
+ return this._client.getRewindInfo(params);
5112
+ }
5113
+ async executeRewind(params) {
5114
+ this._ensureNotClosed();
5115
+ return this._client.executeRewind(params);
5116
+ }
5117
+ async addMcpServer(params) {
5118
+ this._ensureNotClosed();
5119
+ return this._client.addMcpServer(params);
5120
+ }
5121
+ async removeMcpServer(params) {
5122
+ this._ensureNotClosed();
5123
+ return this._client.removeMcpServer(params);
5124
+ }
5125
+ async toggleMcpServer(params) {
5126
+ this._ensureNotClosed();
5127
+ return this._client.toggleMcpServer(params);
5128
+ }
5129
+ async listMcpServers() {
5130
+ this._ensureNotClosed();
5131
+ return this._client.listMcpServers();
5132
+ }
5133
+ async listMcpTools() {
5134
+ this._ensureNotClosed();
5135
+ return this._client.listMcpTools();
5136
+ }
5137
+ async authenticateMcpServer(params) {
5138
+ this._ensureNotClosed();
5139
+ return this._client.authenticateMcpServer(params);
5140
+ }
5141
+ async listSkills() {
5142
+ this._ensureNotClosed();
5143
+ return this._client.listSkills();
5144
+ }
5145
+ onNotification(callback, filter) {
5146
+ return this._client.onNotification(callback, filter);
5147
+ }
5148
+ _ensureNotClosed() {
5149
+ if (this._closed) {
5150
+ throw new ConnectionError(
5151
+ "Daemon session has been closed. Create a new session to continue."
5152
+ );
5153
+ }
5154
+ }
5155
+ };
5156
+
5157
+ // src/daemon/transport.ts
5158
+ var import_ws = __toESM(require("ws"), 1);
5159
+
5160
+ // src/daemon/types.ts
5161
+ var MachineType = /* @__PURE__ */ ((MachineType2) => {
5162
+ MachineType2["Local"] = "local";
5163
+ MachineType2["Computer"] = "computer";
5164
+ return MachineType2;
5165
+ })(MachineType || {});
5166
+ var DEFAULT_DAEMON_PORT = 37643;
5167
+ var DEFAULT_RELAY_BASE_URL = "wss://relay.factory.ai";
5168
+ var DEFAULT_WS_CONFIG = {
5169
+ maxConnectRetries: 5,
5170
+ initialRetryDelayMs: 500,
5171
+ maxRetryDelayMs: 5e3,
5172
+ connectionTimeoutMs: 5e3
5173
+ };
5174
+ var COMPUTER_WS_CONFIG = {
5175
+ connectionTimeoutMs: 45e3,
5176
+ maxConnectRetries: 10,
5177
+ initialRetryDelayMs: 2e3,
5178
+ maxRetryDelayMs: 1e4
5179
+ };
5180
+
5181
+ // src/daemon/transport.ts
5182
+ var WebSocketTransport = class {
5183
+ maxConnectRetries;
5184
+ initialRetryDelayMs;
5185
+ maxRetryDelayMs;
5186
+ connectionTimeoutMs;
5187
+ ws = null;
5188
+ messageHandler = null;
5189
+ errorHandler = null;
5190
+ _isConnected = false;
5191
+ isClosing = false;
5192
+ constructor(options = {}) {
5193
+ this.maxConnectRetries = options.maxConnectRetries ?? DEFAULT_WS_CONFIG.maxConnectRetries;
5194
+ this.initialRetryDelayMs = options.initialRetryDelayMs ?? DEFAULT_WS_CONFIG.initialRetryDelayMs;
5195
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_WS_CONFIG.maxRetryDelayMs;
5196
+ this.connectionTimeoutMs = options.connectionTimeoutMs ?? DEFAULT_WS_CONFIG.connectionTimeoutMs;
5197
+ }
5198
+ get isConnected() {
5199
+ return this._isConnected;
5200
+ }
5201
+ async connect(url) {
5202
+ if (!url) {
5203
+ throw new ConnectionError("WebSocket URL is required");
5204
+ }
5205
+ if (this._isConnected) {
5206
+ throw new ConnectionError("Transport already connected");
5207
+ }
5208
+ this.isClosing = false;
5209
+ let lastError;
5210
+ for (let attempt = 0; attempt <= this.maxConnectRetries; attempt++) {
5211
+ try {
5212
+ await this._doConnect(url);
5213
+ return;
5214
+ } catch (error) {
5215
+ lastError = error instanceof Error ? error : new Error(String(error));
5216
+ if (attempt < this.maxConnectRetries) {
5217
+ const delay = Math.min(
5218
+ this.initialRetryDelayMs * 2 ** attempt,
5219
+ this.maxRetryDelayMs
5220
+ );
5221
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
5222
+ }
5223
+ }
5224
+ }
5225
+ throw lastError;
5226
+ }
5227
+ send(message) {
5228
+ if (!this._isConnected || !this.ws) {
5229
+ throw new ConnectionError("WebSocket transport not connected");
5230
+ }
5231
+ try {
5232
+ this.ws.send(JSON.stringify(message));
5233
+ } catch (error) {
5234
+ const msg = error instanceof Error ? error.message : String(error);
5235
+ throw new ConnectionError(`Failed to send WebSocket message: ${msg}`);
5236
+ }
5237
+ }
5238
+ onMessage(callback) {
5239
+ this.messageHandler = callback;
5240
+ }
5241
+ onError(callback) {
5242
+ this.errorHandler = callback;
5243
+ }
5244
+ async close() {
5245
+ if (this.isClosing) {
5246
+ return;
5247
+ }
5248
+ this.isClosing = true;
5249
+ this._isConnected = false;
5250
+ const ws = this.ws;
5251
+ this.ws = null;
5252
+ if (ws && ws.readyState === import_ws.default.OPEN) {
5253
+ await new Promise((resolve2) => {
5254
+ ws.once("close", () => resolve2());
5255
+ ws.close(1e3, "Client disconnect");
5256
+ setTimeout(() => resolve2(), 5e3);
5257
+ });
5258
+ }
5259
+ this.isClosing = false;
5260
+ }
5261
+ async _doConnect(url) {
5262
+ return new Promise((resolve2, reject) => {
5263
+ let settled = false;
5264
+ let timeoutId = null;
5265
+ const cleanup = () => {
5266
+ if (timeoutId) {
5267
+ clearTimeout(timeoutId);
5268
+ timeoutId = null;
5269
+ }
5270
+ };
5271
+ const ws = new import_ws.default(url);
5272
+ const handleOpen = () => {
5273
+ if (settled) return;
5274
+ settled = true;
5275
+ cleanup();
5276
+ this.ws = ws;
5277
+ this._isConnected = true;
5278
+ this._setupOngoingHandlers(ws);
5279
+ resolve2();
5280
+ };
5281
+ const handleError = (error) => {
5282
+ if (settled) return;
5283
+ settled = true;
5284
+ cleanup();
5285
+ try {
5286
+ ws.close();
5287
+ } catch {
5288
+ }
5289
+ reject(
5290
+ new ConnectionError(`WebSocket connection failed: ${error.message}`)
5291
+ );
5292
+ };
5293
+ const handleClose = (code, reason) => {
5294
+ if (settled) return;
5295
+ settled = true;
5296
+ cleanup();
5297
+ reject(
5298
+ new ConnectionError(
5299
+ `WebSocket closed before opening (code: ${code}, reason: ${reason.toString()})`
5300
+ )
5301
+ );
5302
+ };
5303
+ ws.once("open", handleOpen);
5304
+ ws.once("error", handleError);
5305
+ ws.once("close", handleClose);
5306
+ timeoutId = setTimeout(() => {
5307
+ if (settled) return;
5308
+ settled = true;
5309
+ try {
5310
+ ws.close();
5311
+ } catch {
5312
+ }
5313
+ reject(
5314
+ new ConnectionError(
5315
+ `WebSocket connection timeout after ${this.connectionTimeoutMs}ms: ${url}`
5316
+ )
5317
+ );
5318
+ }, this.connectionTimeoutMs);
5319
+ });
5320
+ }
5321
+ _setupOngoingHandlers(ws) {
5322
+ ws.on("message", (data) => {
5323
+ if (!this.messageHandler) return;
5324
+ const text = typeof data === "string" ? data : data.toString();
5325
+ try {
5326
+ const parsed = JSON.parse(text);
5327
+ if (isRecord(parsed)) {
5328
+ this.messageHandler(parsed);
5329
+ }
5330
+ } catch {
5331
+ }
5332
+ });
5333
+ ws.on("error", (error) => {
5334
+ if (!this.isClosing && this.errorHandler) {
5335
+ this.errorHandler(
5336
+ new ConnectionError(`WebSocket error: ${error.message}`)
5337
+ );
5338
+ }
5339
+ });
5340
+ ws.on("close", (code, reason) => {
5341
+ this._isConnected = false;
5342
+ this.ws = null;
5343
+ if (!this.isClosing && this.errorHandler) {
5344
+ this.errorHandler(
5345
+ new ConnectionError(
5346
+ `WebSocket closed (code: ${code}, reason: ${reason.toString()})`
5347
+ )
5348
+ );
5349
+ }
5350
+ });
5351
+ }
5352
+ };
5353
+
5354
+ // src/daemon/connection.ts
5355
+ var DAEMON_AUTHENTICATE_METHOD = "daemon.authenticate";
5356
+ var DAEMON_AUTHENTICATE_TIMEOUT = 3e4;
5357
+ var SDK_CALLER = "droid-sdk";
5358
+ function resolveWebSocketUrl(options) {
5359
+ if (options.url) {
5360
+ return options.url;
5361
+ }
5362
+ const machine = options.machine;
5363
+ if (!machine || machine.type === "local" /* Local */) {
5364
+ const port = options._localPort ?? options.daemonPort ?? DEFAULT_DAEMON_PORT;
5365
+ return `ws://127.0.0.1:${port}`;
5366
+ }
5367
+ if (machine.type === "computer" /* Computer */) {
5368
+ const relayBase = options.relayBaseUrl ?? DEFAULT_RELAY_BASE_URL;
5369
+ return `${relayBase}/v0/computer/${machine.computerId}/client`;
5370
+ }
5371
+ const _exhaustive = machine;
5372
+ throw new ConnectionError(`Unsupported machine type: ${String(_exhaustive)}`);
5373
+ }
5374
+ function getWebSocketConfig(machine) {
5375
+ if (machine?.type === "computer" /* Computer */) {
5376
+ return { ...DEFAULT_WS_CONFIG, ...COMPUTER_WS_CONFIG };
5377
+ }
5378
+ if (!machine || machine.type === "local" /* Local */) {
5379
+ return { ...DEFAULT_WS_CONFIG, connectionTimeoutMs: 1e4 };
5380
+ }
5381
+ return { ...DEFAULT_WS_CONFIG };
5382
+ }
5383
+ var SharedTransportMultiplexer = class {
5384
+ constructor(_inner) {
5385
+ this._inner = _inner;
5386
+ this._inner.onMessage((message) => {
5387
+ this._routeMessage(message);
5388
+ });
5389
+ this._inner.onError((error) => {
5390
+ for (const view of this._views) {
5391
+ if (view.errorCallback) {
5392
+ try {
5393
+ view.errorCallback(error);
5394
+ } catch {
5395
+ }
5396
+ }
5397
+ }
5398
+ });
5399
+ }
5400
+ _views = /* @__PURE__ */ new Set();
5401
+ createView() {
5402
+ const inner = this._inner;
5403
+ const viewState = {
5404
+ messageCallback: null,
5405
+ errorCallback: null,
5406
+ pendingRequestIds: /* @__PURE__ */ new Set(),
5407
+ sessionId: null
5408
+ };
5409
+ this._views.add(viewState);
5410
+ const view = {
5411
+ send: (message) => {
5412
+ if (message["type"] === "request" && typeof message["id"] === "string") {
5413
+ viewState.pendingRequestIds.add(message["id"]);
5414
+ }
5415
+ inner.send(message);
5416
+ },
5417
+ onMessage: (callback) => {
5418
+ viewState.messageCallback = callback;
5419
+ },
5420
+ onError: (callback) => {
5421
+ viewState.errorCallback = callback;
5422
+ },
5423
+ close: async () => {
5424
+ viewState.messageCallback = null;
5425
+ viewState.errorCallback = null;
5426
+ viewState.pendingRequestIds.clear();
5427
+ this._views.delete(viewState);
5428
+ },
5429
+ get isConnected() {
5430
+ return inner.isConnected;
5431
+ }
5432
+ };
5433
+ return view;
5434
+ }
5435
+ _routeMessage(message) {
5436
+ const messageType = message["type"];
5437
+ const messageId = message["id"];
5438
+ if (messageType === "response" && typeof messageId === "string") {
5439
+ for (const view of this._views) {
5440
+ if (view.pendingRequestIds.has(messageId)) {
5441
+ view.pendingRequestIds.delete(messageId);
5442
+ const result = message["result"];
5443
+ if (isRecord(result) && typeof result["sessionId"] === "string") {
5444
+ view.sessionId = result["sessionId"];
5445
+ }
5446
+ if (view.messageCallback) {
5447
+ try {
5448
+ view.messageCallback(message);
5449
+ } catch {
5450
+ }
5451
+ }
5452
+ return;
5453
+ }
5454
+ }
5455
+ return;
5456
+ }
5457
+ if (messageType === "notification") {
5458
+ const params = message["params"];
5459
+ const sessionId = isRecord(params) && typeof params["sessionId"] === "string" ? params["sessionId"] : null;
5460
+ if (sessionId) {
5461
+ for (const view of this._views) {
5462
+ if (view.sessionId === sessionId && view.messageCallback) {
5463
+ try {
5464
+ view.messageCallback(message);
5465
+ } catch {
5466
+ }
5467
+ return;
5468
+ }
5469
+ }
5470
+ }
5471
+ for (const view of this._views) {
5472
+ if (view.messageCallback) {
5473
+ try {
5474
+ view.messageCallback(message);
5475
+ } catch {
5476
+ }
5477
+ }
5478
+ }
5479
+ return;
5480
+ }
5481
+ if (messageType === "request") {
5482
+ const params = message["params"];
5483
+ const sessionId = isRecord(params) && typeof params["sessionId"] === "string" ? params["sessionId"] : null;
5484
+ if (sessionId) {
5485
+ for (const view of this._views) {
5486
+ if (view.sessionId === sessionId && view.messageCallback) {
5487
+ try {
5488
+ view.messageCallback(message);
5489
+ } catch {
5490
+ }
5491
+ return;
5492
+ }
5493
+ }
5494
+ }
5495
+ for (const view of this._views) {
5496
+ if (view.messageCallback) {
5497
+ try {
5498
+ view.messageCallback(message);
5499
+ } catch {
5500
+ }
5501
+ }
5502
+ }
5503
+ }
5504
+ }
5505
+ };
5506
+ async function authenticate(transport, options) {
5507
+ const requestId = crypto.randomUUID();
5508
+ const envelope = {
5509
+ jsonrpc: JSONRPC_VERSION,
5510
+ factoryApiVersion: LEGACY_FACTORY_API_VERSION,
5511
+ factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,
5512
+ type: "request" /* Request */,
5513
+ id: requestId,
5514
+ method: DAEMON_AUTHENTICATE_METHOD,
5515
+ params: {
5516
+ apiKey: options.apiKey,
5517
+ caller: SDK_CALLER
5518
+ }
5519
+ };
5520
+ return new Promise((resolve2, reject) => {
5521
+ const timer = setTimeout(() => {
5522
+ transport.onMessage(() => {
5523
+ });
5524
+ reject(
5525
+ new ConnectionError(
5526
+ `Daemon authentication timed out after ${DAEMON_AUTHENTICATE_TIMEOUT}ms`
5527
+ )
5528
+ );
5529
+ }, DAEMON_AUTHENTICATE_TIMEOUT);
5530
+ transport.onMessage((message) => {
5531
+ if (message["id"] !== requestId) {
5532
+ return;
5533
+ }
5534
+ clearTimeout(timer);
5535
+ transport.onMessage(() => {
5536
+ });
5537
+ if (message["error"]) {
5538
+ const error = message["error"];
5539
+ const errorMessage = error && typeof error === "object" && "message" in error ? String(error.message) : "unknown error";
5540
+ reject(
5541
+ new ConnectionError(`Daemon authentication failed: ${errorMessage}`)
5542
+ );
5543
+ return;
5544
+ }
5545
+ resolve2();
5546
+ });
5547
+ transport.send(envelope);
5548
+ });
5549
+ }
5550
+ var DaemonConnection = class {
5551
+ _transport;
5552
+ _multiplexer;
5553
+ _apiKey;
5554
+ _closed = false;
5555
+ /** @internal */
5556
+ constructor(transport, apiKey) {
5557
+ this._transport = transport;
5558
+ this._multiplexer = new SharedTransportMultiplexer(transport);
5559
+ this._apiKey = apiKey;
5560
+ }
5561
+ async createSession(options = {}) {
5562
+ this._ensureNotClosed();
5563
+ const view = this._multiplexer.createView();
5564
+ const client = new DaemonClient({
5565
+ transport: view,
5566
+ apiKey: this._apiKey
5567
+ });
5568
+ if (options.permissionHandler) {
5569
+ client.setPermissionHandler(options.permissionHandler);
5570
+ }
5571
+ if (options.askUserHandler) {
5572
+ client.setAskUserHandler(options.askUserHandler);
5573
+ }
5574
+ let sdkMcpServers;
5575
+ try {
5576
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
5577
+ const initParams = buildInitParams({
5578
+ ...options,
5579
+ mcpServers: sdkMcpServers.mcpServers
5580
+ });
5581
+ const initResult = await client.initializeSession(initParams);
5582
+ const session = new DaemonSession(client, initResult.sessionId);
5583
+ if (sdkMcpServers) {
5584
+ session.addCleanup(sdkMcpServers.cleanup);
5585
+ }
5586
+ return session;
5587
+ } catch (error) {
5588
+ await sdkMcpServers?.cleanup();
5589
+ await client.close();
5590
+ throw error;
5591
+ }
5592
+ }
5593
+ async resumeSession(sessionId, options = {}) {
5594
+ this._ensureNotClosed();
5595
+ const view = this._multiplexer.createView();
5596
+ const client = new DaemonClient({
5597
+ transport: view,
5598
+ apiKey: this._apiKey
5599
+ });
5600
+ if (options.permissionHandler) {
5601
+ client.setPermissionHandler(options.permissionHandler);
5602
+ }
5603
+ if (options.askUserHandler) {
5604
+ client.setAskUserHandler(options.askUserHandler);
5605
+ }
5606
+ let sdkMcpServers;
5607
+ try {
5608
+ sdkMcpServers = await startSdkMcpServers(options.mcpServers);
5609
+ await client.loadSession({
5610
+ sessionId,
5611
+ mcpServers: sdkMcpServers.mcpServers
5612
+ });
5613
+ const session = new DaemonSession(client, sessionId);
5614
+ if (sdkMcpServers) {
5615
+ session.addCleanup(sdkMcpServers.cleanup);
5616
+ }
5617
+ return session;
5618
+ } catch (error) {
5619
+ await sdkMcpServers?.cleanup();
5620
+ await client.close();
5621
+ throw error;
5622
+ }
5623
+ }
5624
+ async interruptSession(sessionId) {
5625
+ this._ensureNotClosed();
5626
+ const view = this._multiplexer.createView();
5627
+ const client = new DaemonClient({
5628
+ transport: view,
5629
+ apiKey: this._apiKey
5630
+ });
5631
+ try {
5632
+ await client.loadSession({ sessionId });
5633
+ await client.interruptSession();
5634
+ } finally {
5635
+ await client.close();
5636
+ }
5637
+ }
5638
+ async close() {
5639
+ if (this._closed) {
5640
+ return;
5641
+ }
5642
+ this._closed = true;
5643
+ await this._transport.close();
5644
+ }
5645
+ _ensureNotClosed() {
5646
+ if (this._closed) {
5647
+ throw new ConnectionError(
5648
+ "Daemon connection has been closed. Call connectDaemon() to create a new connection."
5649
+ );
5650
+ }
5651
+ }
5652
+ };
5653
+ async function connectDaemon(options) {
5654
+ const isLocal = !options.url && (!options.machine || options.machine.type === "local" /* Local */);
5655
+ let resolvedOptions = options;
5656
+ if (isLocal) {
5657
+ const { port } = await ensureLocalDaemon();
5658
+ resolvedOptions = { ...options, _localPort: port };
5659
+ }
5660
+ const url = resolveWebSocketUrl(resolvedOptions);
5661
+ const wsConfig = getWebSocketConfig(resolvedOptions.machine);
5662
+ const transport = new WebSocketTransport(wsConfig);
5663
+ const apiKey = resolvedOptions.apiKey;
5664
+ const maxRetries = resolvedOptions.maxRetries ?? 0;
5665
+ try {
5666
+ if (maxRetries > 0) {
5667
+ let lastError;
5668
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
5669
+ try {
5670
+ await transport.connect(url);
5671
+ await authenticate(transport, resolvedOptions);
5672
+ return new DaemonConnection(transport, apiKey);
5673
+ } catch (error) {
5674
+ lastError = error instanceof Error ? error : new Error(String(error));
5675
+ try {
5676
+ await transport.close();
5677
+ } catch {
5678
+ }
5679
+ if (attempt < maxRetries) {
5680
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
5681
+ }
5682
+ }
5683
+ }
5684
+ throw lastError;
5685
+ }
5686
+ await transport.connect(url);
5687
+ await authenticate(transport, resolvedOptions);
5688
+ return new DaemonConnection(transport, apiKey);
5689
+ } catch (error) {
5690
+ try {
5691
+ await transport.close();
5692
+ } catch {
5693
+ }
5694
+ throw error;
5695
+ }
5696
+ }
4096
5697
  // Annotate the CommonJS export names for ESM import in node:
4097
5698
  0 && (module.exports = {
4098
5699
  AddMcpServerRequestParamsSchema,
@@ -4111,6 +5712,7 @@ async function listSessions(options = {}) {
4111
5712
  AskUserRequestSchema,
4112
5713
  AskUserResponseSchema,
4113
5714
  AskUserResultSchema,
5715
+ AssistantTextCompleteNotificationSchema,
4114
5716
  AssistantTextDeltaNotificationSchema,
4115
5717
  AuthenticateMcpServerRequestParamsSchema,
4116
5718
  AuthenticateMcpServerRequestSchema,
@@ -4135,17 +5737,30 @@ async function listSessions(options = {}) {
4135
5737
  ClearMcpAuthResultSchema,
4136
5738
  CliRequestOrNotificationSchema,
4137
5739
  ClientRequestSchema,
5740
+ CloseSessionRequestParamsSchema,
5741
+ CloseSessionRequestSchema,
5742
+ CloseSessionResponseSchema,
5743
+ CloseSessionResultSchema,
4138
5744
  CompactSessionRequestParamsSchema,
4139
5745
  CompactSessionRequestSchema,
4140
5746
  CompactSessionResponseSchema,
4141
5747
  CompactSessionResultSchema,
5748
+ ComputerListResponseSchema,
5749
+ ComputerMetricSchema,
5750
+ ComputerMetricsResponseSchema,
5751
+ ComputerSchema,
4142
5752
  ConnectionError,
4143
5753
  ContentBlockSchema,
5754
+ ContextBreakdownCategorySchema,
5755
+ ContextBreakdownResultSchema,
4144
5756
  ContextStatsAccuracy,
4145
5757
  ContextStatsSchema,
4146
5758
  CreateMessageNotificationSchema,
4147
5759
  CreateToolConfirmationDetailsSchema,
4148
5760
  DEFAULT_REQUEST_TIMEOUT,
5761
+ DaemonClient,
5762
+ DaemonConnection,
5763
+ DaemonSession,
4149
5764
  DecompSessionType,
4150
5765
  DiscoveredIssueSchema,
4151
5766
  DismissalRecordSchema,
@@ -4155,6 +5770,10 @@ async function listSessions(options = {}) {
4155
5770
  DroidClient,
4156
5771
  DroidClientMethod,
4157
5772
  DroidErrorType,
5773
+ DroidHookEventSchema,
5774
+ DroidHookExecutionResultSchema,
5775
+ DroidHookOutputSchema,
5776
+ DroidHookSpecificOutputSchema,
4158
5777
  DroidInteractionMode,
4159
5778
  DroidMessageType,
4160
5779
  DroidServerMethod,
@@ -4195,6 +5814,10 @@ async function listSessions(options = {}) {
4195
5814
  GitRepoInfoSchema,
4196
5815
  HandoffItemsDismissedEntrySchema,
4197
5816
  HandoffSchema,
5817
+ HookCommandSchema,
5818
+ HookExecutionCompletedNotificationSchema,
5819
+ HookExecutionStartedNotificationSchema,
5820
+ HookResultSchema,
4198
5821
  HttpHeaderSchema,
4199
5822
  HttpMcpConfigSchema,
4200
5823
  ImageBlockSchema,
@@ -4252,6 +5875,10 @@ async function listSessions(options = {}) {
4252
5875
  LoadSessionResponseSchema,
4253
5876
  LoadSessionResultSchema,
4254
5877
  MCP_AUTH_TIMEOUT,
5878
+ MachineTemplateBuildStatusSchema,
5879
+ MachineTemplateListResponseSchema,
5880
+ MachineTemplateSchema,
5881
+ MachineType,
4255
5882
  McpAuthCompletedNotificationSchema,
4256
5883
  McpAuthOutcome,
4257
5884
  McpAuthRequiredNotificationSchema,
@@ -4297,6 +5924,9 @@ async function listSessions(options = {}) {
4297
5924
  REWIND_TIMEOUT,
4298
5925
  ReasoningEffort,
4299
5926
  RedactedThinkingBlockSchema,
5927
+ RefreshComputerResponseSchema,
5928
+ RemoteSessionListResponseSchema,
5929
+ RemoteSessionSchema,
4300
5930
  RemoveMcpServerRequestParamsSchema,
4301
5931
  RemoveMcpServerRequestSchema,
4302
5932
  RemoveMcpServerResponseSchema,
@@ -4316,6 +5946,7 @@ async function listSessions(options = {}) {
4316
5946
  SDK_VERSION,
4317
5947
  SESSION_INIT_TIMEOUT,
4318
5948
  SdkMcpServer,
5949
+ ServerRequestHandlerType,
4319
5950
  SessionError,
4320
5951
  SessionMetadataSchema,
4321
5952
  SessionNotFoundError,
@@ -4343,6 +5974,8 @@ async function listSessions(options = {}) {
4343
5974
  StartMissionRunConfirmationDetailsSchema,
4344
5975
  StdioMcpConfigSchema,
4345
5976
  StreamStateTracker,
5977
+ StructuredOutputErrorSchema,
5978
+ StructuredOutputNotificationSchema,
4346
5979
  SubmitBugReportRequestParamsSchema,
4347
5980
  SubmitBugReportRequestSchema,
4348
5981
  SubmitBugReportResponseSchema,
@@ -4357,6 +5990,7 @@ async function listSessions(options = {}) {
4357
5990
  TestsSchema,
4358
5991
  TextBlockSchema,
4359
5992
  ThinkingBlockSchema,
5993
+ ThinkingTextCompleteNotificationSchema,
4360
5994
  ThinkingTextDeltaNotificationSchema,
4361
5995
  TimeoutError,
4362
5996
  ToggleMcpServerRequestParamsSchema,
@@ -4368,6 +6002,7 @@ async function listSessions(options = {}) {
4368
6002
  ToggleMcpToolResponseSchema,
4369
6003
  ToggleMcpToolResultSchema,
4370
6004
  TokenUsageSchema,
6005
+ ToolCallNotificationSchema,
4371
6006
  ToolConfirmationDetailsSchema,
4372
6007
  ToolConfirmationInfoSchema,
4373
6008
  ToolConfirmationListItemSchema,
@@ -4387,19 +6022,37 @@ async function listSessions(options = {}) {
4387
6022
  UpdateSessionSettingsResultSchema,
4388
6023
  VerificationCommandSchema,
4389
6024
  VerificationSchema,
6025
+ WebSocketTransport,
4390
6026
  WorkerCompletedEntrySchema,
4391
6027
  WorkerFailedEntrySchema,
4392
6028
  WorkerPausedEntrySchema,
4393
6029
  WorkerSelectedFeatureEntrySchema,
4394
6030
  WorkerStartedEntrySchema,
4395
6031
  WorkerStateInfoSchema,
6032
+ connectDaemon,
4396
6033
  convertNotificationToStreamMessage,
6034
+ createComputer,
6035
+ createResponseSchema,
4397
6036
  createSdkMcpServer,
4398
6037
  createSession,
6038
+ deleteComputer,
6039
+ dispatchNotification,
6040
+ ensureLocalDaemon,
6041
+ getComputer,
6042
+ getComputerByName,
6043
+ getComputerMetrics,
6044
+ getMachineTemplate,
6045
+ listComputers,
6046
+ listMachineTemplates,
6047
+ listRemoteSessions,
4399
6048
  listSessions,
4400
- query,
6049
+ refreshComputer,
6050
+ resolveWebSocketUrl,
6051
+ restartComputer,
4401
6052
  resumeSession,
6053
+ retryInstallDeps,
4402
6054
  run,
4403
- tool
6055
+ tool,
6056
+ updateComputer
4404
6057
  });
4405
6058
  //# sourceMappingURL=index.cjs.map