@factory/droid-sdk 0.6.0 → 0.7.0

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