@cloudflare/sandbox 0.0.0-037c848

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts ADDED
@@ -0,0 +1,1960 @@
1
+ import type { DurableObject } from "cloudflare:workers";
2
+ import type { Sandbox } from "./index";
3
+
4
+ interface ExecuteRequest {
5
+ command: string;
6
+ args?: string[];
7
+ }
8
+
9
+ export interface ExecuteResponse {
10
+ success: boolean;
11
+ stdout: string;
12
+ stderr: string;
13
+ exitCode: number;
14
+ command: string;
15
+ args: string[];
16
+ timestamp: string;
17
+ }
18
+
19
+ interface SessionResponse {
20
+ sessionId: string;
21
+ message: string;
22
+ timestamp: string;
23
+ }
24
+
25
+ interface SessionListResponse {
26
+ sessions: Array<{
27
+ sessionId: string;
28
+ hasActiveProcess: boolean;
29
+ createdAt: string;
30
+ }>;
31
+ count: number;
32
+ timestamp: string;
33
+ }
34
+
35
+ interface CommandsResponse {
36
+ availableCommands: string[];
37
+ timestamp: string;
38
+ }
39
+
40
+ interface GitCheckoutRequest {
41
+ repoUrl: string;
42
+ branch?: string;
43
+ targetDir?: string;
44
+ sessionId?: string;
45
+ }
46
+
47
+ export interface GitCheckoutResponse {
48
+ success: boolean;
49
+ stdout: string;
50
+ stderr: string;
51
+ exitCode: number;
52
+ repoUrl: string;
53
+ branch: string;
54
+ targetDir: string;
55
+ timestamp: string;
56
+ }
57
+
58
+ interface MkdirRequest {
59
+ path: string;
60
+ recursive?: boolean;
61
+ sessionId?: string;
62
+ }
63
+
64
+ export interface MkdirResponse {
65
+ success: boolean;
66
+ stdout: string;
67
+ stderr: string;
68
+ exitCode: number;
69
+ path: string;
70
+ recursive: boolean;
71
+ timestamp: string;
72
+ }
73
+
74
+ interface WriteFileRequest {
75
+ path: string;
76
+ content: string;
77
+ encoding?: string;
78
+ sessionId?: string;
79
+ }
80
+
81
+ export interface WriteFileResponse {
82
+ success: boolean;
83
+ exitCode: number;
84
+ path: string;
85
+ timestamp: string;
86
+ }
87
+
88
+ interface ReadFileRequest {
89
+ path: string;
90
+ encoding?: string;
91
+ sessionId?: string;
92
+ }
93
+
94
+ export interface ReadFileResponse {
95
+ success: boolean;
96
+ exitCode: number;
97
+ path: string;
98
+ content: string;
99
+ timestamp: string;
100
+ }
101
+
102
+ interface DeleteFileRequest {
103
+ path: string;
104
+ sessionId?: string;
105
+ }
106
+
107
+ export interface DeleteFileResponse {
108
+ success: boolean;
109
+ exitCode: number;
110
+ path: string;
111
+ timestamp: string;
112
+ }
113
+
114
+ interface RenameFileRequest {
115
+ oldPath: string;
116
+ newPath: string;
117
+ sessionId?: string;
118
+ }
119
+
120
+ export interface RenameFileResponse {
121
+ success: boolean;
122
+ exitCode: number;
123
+ oldPath: string;
124
+ newPath: string;
125
+ timestamp: string;
126
+ }
127
+
128
+ interface MoveFileRequest {
129
+ sourcePath: string;
130
+ destinationPath: string;
131
+ sessionId?: string;
132
+ }
133
+
134
+ export interface MoveFileResponse {
135
+ success: boolean;
136
+ exitCode: number;
137
+ sourcePath: string;
138
+ destinationPath: string;
139
+ timestamp: string;
140
+ }
141
+
142
+ interface PingResponse {
143
+ message: string;
144
+ timestamp: string;
145
+ }
146
+
147
+ interface StreamEvent {
148
+ type: "command_start" | "output" | "command_complete" | "error";
149
+ command?: string;
150
+ args?: string[];
151
+ stream?: "stdout" | "stderr";
152
+ data?: string;
153
+ message?: string;
154
+ path?: string;
155
+ oldPath?: string;
156
+ newPath?: string;
157
+ sourcePath?: string;
158
+ destinationPath?: string;
159
+ content?: string;
160
+ success?: boolean;
161
+ exitCode?: number;
162
+ stdout?: string;
163
+ stderr?: string;
164
+ error?: string;
165
+ timestamp?: string;
166
+ }
167
+
168
+ interface HttpClientOptions {
169
+ stub?: Sandbox;
170
+ baseUrl?: string;
171
+ port?: number;
172
+ onCommandStart?: (command: string, args: string[]) => void;
173
+ onOutput?: (
174
+ stream: "stdout" | "stderr",
175
+ data: string,
176
+ command: string
177
+ ) => void;
178
+ onCommandComplete?: (
179
+ success: boolean,
180
+ exitCode: number,
181
+ stdout: string,
182
+ stderr: string,
183
+ command: string,
184
+ args: string[]
185
+ ) => void;
186
+ onError?: (error: string, command?: string, args?: string[]) => void;
187
+ onStreamEvent?: (event: StreamEvent) => void;
188
+ }
189
+
190
+ export class HttpClient {
191
+ private baseUrl: string;
192
+ private options: HttpClientOptions;
193
+ private sessionId: string | null = null;
194
+
195
+ constructor(options: HttpClientOptions = {}) {
196
+ this.options = {
197
+ ...options,
198
+ };
199
+ this.baseUrl = this.options.baseUrl!;
200
+ }
201
+
202
+ private async doFetch(
203
+ path: string,
204
+ options?: RequestInit
205
+ ): Promise<Response> {
206
+ const url = this.options.stub
207
+ ? `http://localhost:${this.options.port}${path}`
208
+ : `${this.baseUrl}${path}`;
209
+ const method = options?.method || "GET";
210
+
211
+ console.log(`[HTTP Client] Making ${method} request to ${url}`);
212
+
213
+ try {
214
+ let response: Response;
215
+
216
+ if (this.options.stub) {
217
+ response = await this.options.stub.containerFetch(
218
+ url,
219
+ options,
220
+ this.options.port
221
+ );
222
+ } else {
223
+ response = await fetch(url, options);
224
+ }
225
+
226
+ console.log(
227
+ `[HTTP Client] Response: ${response.status} ${response.statusText}`
228
+ );
229
+
230
+ if (!response.ok) {
231
+ console.error(
232
+ `[HTTP Client] Request failed: ${method} ${url} - ${response.status} ${response.statusText}`
233
+ );
234
+ }
235
+
236
+ return response;
237
+ } catch (error) {
238
+ console.error(`[HTTP Client] Request error: ${method} ${url}`, error);
239
+ throw error;
240
+ }
241
+ }
242
+ // Public methods to set event handlers
243
+ setOnOutput(
244
+ handler: (
245
+ stream: "stdout" | "stderr",
246
+ data: string,
247
+ command: string
248
+ ) => void
249
+ ): void {
250
+ this.options.onOutput = handler;
251
+ }
252
+
253
+ setOnCommandComplete(
254
+ handler: (
255
+ success: boolean,
256
+ exitCode: number,
257
+ stdout: string,
258
+ stderr: string,
259
+ command: string,
260
+ args: string[]
261
+ ) => void
262
+ ): void {
263
+ this.options.onCommandComplete = handler;
264
+ }
265
+
266
+ setOnStreamEvent(handler: (event: StreamEvent) => void): void {
267
+ this.options.onStreamEvent = handler;
268
+ }
269
+
270
+ // Public getter methods
271
+ getOnOutput():
272
+ | ((stream: "stdout" | "stderr", data: string, command: string) => void)
273
+ | undefined {
274
+ return this.options.onOutput;
275
+ }
276
+
277
+ getOnCommandComplete():
278
+ | ((
279
+ success: boolean,
280
+ exitCode: number,
281
+ stdout: string,
282
+ stderr: string,
283
+ command: string,
284
+ args: string[]
285
+ ) => void)
286
+ | undefined {
287
+ return this.options.onCommandComplete;
288
+ }
289
+
290
+ getOnStreamEvent(): ((event: StreamEvent) => void) | undefined {
291
+ return this.options.onStreamEvent;
292
+ }
293
+
294
+ async createSession(): Promise<string> {
295
+ try {
296
+ const response = await this.doFetch(`/api/session/create`, {
297
+ headers: {
298
+ "Content-Type": "application/json",
299
+ },
300
+ method: "POST",
301
+ });
302
+
303
+ if (!response.ok) {
304
+ throw new Error(`HTTP error! status: ${response.status}`);
305
+ }
306
+
307
+ const data: SessionResponse = await response.json();
308
+ this.sessionId = data.sessionId;
309
+ console.log(`[HTTP Client] Created session: ${this.sessionId}`);
310
+ return this.sessionId;
311
+ } catch (error) {
312
+ console.error("[HTTP Client] Error creating session:", error);
313
+ throw error;
314
+ }
315
+ }
316
+
317
+ async listSessions(): Promise<SessionListResponse> {
318
+ try {
319
+ const response = await this.doFetch(`/api/session/list`, {
320
+ headers: {
321
+ "Content-Type": "application/json",
322
+ },
323
+ method: "GET",
324
+ });
325
+
326
+ if (!response.ok) {
327
+ throw new Error(`HTTP error! status: ${response.status}`);
328
+ }
329
+
330
+ const data: SessionListResponse = await response.json();
331
+ console.log(`[HTTP Client] Listed ${data.count} sessions`);
332
+ return data;
333
+ } catch (error) {
334
+ console.error("[HTTP Client] Error listing sessions:", error);
335
+ throw error;
336
+ }
337
+ }
338
+
339
+ async execute(
340
+ command: string,
341
+ args: string[] = [],
342
+ sessionId?: string
343
+ ): Promise<ExecuteResponse> {
344
+ try {
345
+ const targetSessionId = sessionId || this.sessionId;
346
+
347
+ const response = await this.doFetch(`/api/execute`, {
348
+ body: JSON.stringify({
349
+ args,
350
+ command,
351
+ sessionId: targetSessionId,
352
+ }),
353
+ headers: {
354
+ "Content-Type": "application/json",
355
+ },
356
+ method: "POST",
357
+ });
358
+
359
+ if (!response.ok) {
360
+ const errorData = (await response.json().catch(() => ({}))) as {
361
+ error?: string;
362
+ };
363
+ throw new Error(
364
+ errorData.error || `HTTP error! status: ${response.status}`
365
+ );
366
+ }
367
+
368
+ const data: ExecuteResponse = await response.json();
369
+ console.log(
370
+ `[HTTP Client] Command executed: ${command}, Success: ${data.success}`
371
+ );
372
+
373
+ // Call the callback if provided
374
+ this.options.onCommandComplete?.(
375
+ data.success,
376
+ data.exitCode,
377
+ data.stdout,
378
+ data.stderr,
379
+ data.command,
380
+ data.args
381
+ );
382
+
383
+ return data;
384
+ } catch (error) {
385
+ console.error("[HTTP Client] Error executing command:", error);
386
+ this.options.onError?.(
387
+ error instanceof Error ? error.message : "Unknown error",
388
+ command,
389
+ args
390
+ );
391
+ throw error;
392
+ }
393
+ }
394
+
395
+ async executeStream(
396
+ command: string,
397
+ args: string[] = [],
398
+ sessionId?: string
399
+ ): Promise<void> {
400
+ try {
401
+ const targetSessionId = sessionId || this.sessionId;
402
+
403
+ const response = await this.doFetch(`/api/execute/stream`, {
404
+ body: JSON.stringify({
405
+ args,
406
+ command,
407
+ sessionId: targetSessionId,
408
+ }),
409
+ headers: {
410
+ "Content-Type": "application/json",
411
+ },
412
+ method: "POST",
413
+ });
414
+
415
+ if (!response.ok) {
416
+ const errorData = (await response.json().catch(() => ({}))) as {
417
+ error?: string;
418
+ };
419
+ throw new Error(
420
+ errorData.error || `HTTP error! status: ${response.status}`
421
+ );
422
+ }
423
+
424
+ if (!response.body) {
425
+ throw new Error("No response body for streaming request");
426
+ }
427
+
428
+ const reader = response.body.getReader();
429
+ const decoder = new TextDecoder();
430
+
431
+ try {
432
+ while (true) {
433
+ const { done, value } = await reader.read();
434
+
435
+ if (done) {
436
+ break;
437
+ }
438
+
439
+ const chunk = decoder.decode(value, { stream: true });
440
+ const lines = chunk.split("\n");
441
+
442
+ for (const line of lines) {
443
+ if (line.startsWith("data: ")) {
444
+ try {
445
+ const eventData = line.slice(6); // Remove 'data: ' prefix
446
+ const event: StreamEvent = JSON.parse(eventData);
447
+
448
+ console.log(`[HTTP Client] Stream event: ${event.type}`);
449
+ this.options.onStreamEvent?.(event);
450
+
451
+ switch (event.type) {
452
+ case "command_start":
453
+ console.log(
454
+ `[HTTP Client] Command started: ${
455
+ event.command
456
+ } ${event.args?.join(" ")}`
457
+ );
458
+ this.options.onCommandStart?.(
459
+ event.command!,
460
+ event.args || []
461
+ );
462
+ break;
463
+
464
+ case "output":
465
+ console.log(`[${event.stream}] ${event.data}`);
466
+ this.options.onOutput?.(
467
+ event.stream!,
468
+ event.data!,
469
+ event.command!
470
+ );
471
+ break;
472
+
473
+ case "command_complete":
474
+ console.log(
475
+ `[HTTP Client] Command completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
476
+ );
477
+ this.options.onCommandComplete?.(
478
+ event.success!,
479
+ event.exitCode!,
480
+ event.stdout!,
481
+ event.stderr!,
482
+ event.command!,
483
+ event.args || []
484
+ );
485
+ break;
486
+
487
+ case "error":
488
+ console.error(
489
+ `[HTTP Client] Command error: ${event.error}`
490
+ );
491
+ this.options.onError?.(
492
+ event.error!,
493
+ event.command,
494
+ event.args
495
+ );
496
+ break;
497
+ }
498
+ } catch (parseError) {
499
+ console.warn(
500
+ "[HTTP Client] Failed to parse stream event:",
501
+ parseError
502
+ );
503
+ }
504
+ }
505
+ }
506
+ }
507
+ } finally {
508
+ reader.releaseLock();
509
+ }
510
+ } catch (error) {
511
+ console.error("[HTTP Client] Error in streaming execution:", error);
512
+ this.options.onError?.(
513
+ error instanceof Error ? error.message : "Unknown error",
514
+ command,
515
+ args
516
+ );
517
+ throw error;
518
+ }
519
+ }
520
+
521
+ async gitCheckout(
522
+ repoUrl: string,
523
+ branch: string = "main",
524
+ targetDir?: string,
525
+ sessionId?: string
526
+ ): Promise<GitCheckoutResponse> {
527
+ try {
528
+ const targetSessionId = sessionId || this.sessionId;
529
+
530
+ const response = await this.doFetch(`/api/git/checkout`, {
531
+ body: JSON.stringify({
532
+ branch,
533
+ repoUrl,
534
+ sessionId: targetSessionId,
535
+ targetDir,
536
+ }),
537
+ headers: {
538
+ "Content-Type": "application/json",
539
+ },
540
+ method: "POST",
541
+ });
542
+
543
+ if (!response.ok) {
544
+ const errorData = (await response.json().catch(() => ({}))) as {
545
+ error?: string;
546
+ };
547
+ throw new Error(
548
+ errorData.error || `HTTP error! status: ${response.status}`
549
+ );
550
+ }
551
+
552
+ const data: GitCheckoutResponse = await response.json();
553
+ console.log(
554
+ `[HTTP Client] Git checkout completed: ${repoUrl}, Success: ${data.success}, Target: ${data.targetDir}`
555
+ );
556
+
557
+ return data;
558
+ } catch (error) {
559
+ console.error("[HTTP Client] Error in git checkout:", error);
560
+ throw error;
561
+ }
562
+ }
563
+
564
+ async gitCheckoutStream(
565
+ repoUrl: string,
566
+ branch: string = "main",
567
+ targetDir?: string,
568
+ sessionId?: string
569
+ ): Promise<void> {
570
+ try {
571
+ const targetSessionId = sessionId || this.sessionId;
572
+
573
+ const response = await this.doFetch(`/api/git/checkout/stream`, {
574
+ body: JSON.stringify({
575
+ branch,
576
+ repoUrl,
577
+ sessionId: targetSessionId,
578
+ targetDir,
579
+ }),
580
+ headers: {
581
+ "Content-Type": "application/json",
582
+ },
583
+ method: "POST",
584
+ });
585
+
586
+ if (!response.ok) {
587
+ const errorData = (await response.json().catch(() => ({}))) as {
588
+ error?: string;
589
+ };
590
+ throw new Error(
591
+ errorData.error || `HTTP error! status: ${response.status}`
592
+ );
593
+ }
594
+
595
+ if (!response.body) {
596
+ throw new Error("No response body for streaming request");
597
+ }
598
+
599
+ const reader = response.body.getReader();
600
+ const decoder = new TextDecoder();
601
+
602
+ try {
603
+ while (true) {
604
+ const { done, value } = await reader.read();
605
+
606
+ if (done) {
607
+ break;
608
+ }
609
+
610
+ const chunk = decoder.decode(value, { stream: true });
611
+ const lines = chunk.split("\n");
612
+
613
+ for (const line of lines) {
614
+ if (line.startsWith("data: ")) {
615
+ try {
616
+ const eventData = line.slice(6); // Remove 'data: ' prefix
617
+ const event: StreamEvent = JSON.parse(eventData);
618
+
619
+ console.log(
620
+ `[HTTP Client] Git checkout stream event: ${event.type}`
621
+ );
622
+ this.options.onStreamEvent?.(event);
623
+
624
+ switch (event.type) {
625
+ case "command_start":
626
+ console.log(
627
+ `[HTTP Client] Git checkout started: ${
628
+ event.command
629
+ } ${event.args?.join(" ")}`
630
+ );
631
+ this.options.onCommandStart?.(
632
+ event.command!,
633
+ event.args || []
634
+ );
635
+ break;
636
+
637
+ case "output":
638
+ console.log(`[${event.stream}] ${event.data}`);
639
+ this.options.onOutput?.(
640
+ event.stream!,
641
+ event.data!,
642
+ event.command!
643
+ );
644
+ break;
645
+
646
+ case "command_complete":
647
+ console.log(
648
+ `[HTTP Client] Git checkout completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
649
+ );
650
+ this.options.onCommandComplete?.(
651
+ event.success!,
652
+ event.exitCode!,
653
+ event.stdout!,
654
+ event.stderr!,
655
+ event.command!,
656
+ event.args || []
657
+ );
658
+ break;
659
+
660
+ case "error":
661
+ console.error(
662
+ `[HTTP Client] Git checkout error: ${event.error}`
663
+ );
664
+ this.options.onError?.(
665
+ event.error!,
666
+ event.command,
667
+ event.args
668
+ );
669
+ break;
670
+ }
671
+ } catch (parseError) {
672
+ console.warn(
673
+ "[HTTP Client] Failed to parse git checkout stream event:",
674
+ parseError
675
+ );
676
+ }
677
+ }
678
+ }
679
+ }
680
+ } finally {
681
+ reader.releaseLock();
682
+ }
683
+ } catch (error) {
684
+ console.error("[HTTP Client] Error in streaming git checkout:", error);
685
+ this.options.onError?.(
686
+ error instanceof Error ? error.message : "Unknown error",
687
+ "git clone",
688
+ [branch, repoUrl, targetDir || ""]
689
+ );
690
+ throw error;
691
+ }
692
+ }
693
+
694
+ async mkdir(
695
+ path: string,
696
+ recursive: boolean = false,
697
+ sessionId?: string
698
+ ): Promise<MkdirResponse> {
699
+ try {
700
+ const targetSessionId = sessionId || this.sessionId;
701
+
702
+ const response = await this.doFetch(`/api/mkdir`, {
703
+ body: JSON.stringify({
704
+ path,
705
+ recursive,
706
+ sessionId: targetSessionId,
707
+ }),
708
+ headers: {
709
+ "Content-Type": "application/json",
710
+ },
711
+ method: "POST",
712
+ });
713
+
714
+ if (!response.ok) {
715
+ const errorData = (await response.json().catch(() => ({}))) as {
716
+ error?: string;
717
+ };
718
+ throw new Error(
719
+ errorData.error || `HTTP error! status: ${response.status}`
720
+ );
721
+ }
722
+
723
+ const data: MkdirResponse = await response.json();
724
+ console.log(
725
+ `[HTTP Client] Directory created: ${path}, Success: ${data.success}, Recursive: ${data.recursive}`
726
+ );
727
+
728
+ return data;
729
+ } catch (error) {
730
+ console.error("[HTTP Client] Error creating directory:", error);
731
+ throw error;
732
+ }
733
+ }
734
+
735
+ async mkdirStream(
736
+ path: string,
737
+ recursive: boolean = false,
738
+ sessionId?: string
739
+ ): Promise<void> {
740
+ try {
741
+ const targetSessionId = sessionId || this.sessionId;
742
+
743
+ const response = await this.doFetch(`/api/mkdir/stream`, {
744
+ body: JSON.stringify({
745
+ path,
746
+ recursive,
747
+ sessionId: targetSessionId,
748
+ }),
749
+ headers: {
750
+ "Content-Type": "application/json",
751
+ },
752
+ method: "POST",
753
+ });
754
+
755
+ if (!response.ok) {
756
+ const errorData = (await response.json().catch(() => ({}))) as {
757
+ error?: string;
758
+ };
759
+ throw new Error(
760
+ errorData.error || `HTTP error! status: ${response.status}`
761
+ );
762
+ }
763
+
764
+ if (!response.body) {
765
+ throw new Error("No response body for streaming request");
766
+ }
767
+
768
+ const reader = response.body.getReader();
769
+ const decoder = new TextDecoder();
770
+
771
+ try {
772
+ while (true) {
773
+ const { done, value } = await reader.read();
774
+
775
+ if (done) {
776
+ break;
777
+ }
778
+
779
+ const chunk = decoder.decode(value, { stream: true });
780
+ const lines = chunk.split("\n");
781
+
782
+ for (const line of lines) {
783
+ if (line.startsWith("data: ")) {
784
+ try {
785
+ const eventData = line.slice(6); // Remove 'data: ' prefix
786
+ const event: StreamEvent = JSON.parse(eventData);
787
+
788
+ console.log(`[HTTP Client] Mkdir stream event: ${event.type}`);
789
+ this.options.onStreamEvent?.(event);
790
+
791
+ switch (event.type) {
792
+ case "command_start":
793
+ console.log(
794
+ `[HTTP Client] Mkdir started: ${
795
+ event.command
796
+ } ${event.args?.join(" ")}`
797
+ );
798
+ this.options.onCommandStart?.(
799
+ event.command!,
800
+ event.args || []
801
+ );
802
+ break;
803
+
804
+ case "output":
805
+ console.log(`[${event.stream}] ${event.data}`);
806
+ this.options.onOutput?.(
807
+ event.stream!,
808
+ event.data!,
809
+ event.command!
810
+ );
811
+ break;
812
+
813
+ case "command_complete":
814
+ console.log(
815
+ `[HTTP Client] Mkdir completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
816
+ );
817
+ this.options.onCommandComplete?.(
818
+ event.success!,
819
+ event.exitCode!,
820
+ event.stdout!,
821
+ event.stderr!,
822
+ event.command!,
823
+ event.args || []
824
+ );
825
+ break;
826
+
827
+ case "error":
828
+ console.error(`[HTTP Client] Mkdir error: ${event.error}`);
829
+ this.options.onError?.(
830
+ event.error!,
831
+ event.command,
832
+ event.args
833
+ );
834
+ break;
835
+ }
836
+ } catch (parseError) {
837
+ console.warn(
838
+ "[HTTP Client] Failed to parse mkdir stream event:",
839
+ parseError
840
+ );
841
+ }
842
+ }
843
+ }
844
+ }
845
+ } finally {
846
+ reader.releaseLock();
847
+ }
848
+ } catch (error) {
849
+ console.error("[HTTP Client] Error in streaming mkdir:", error);
850
+ this.options.onError?.(
851
+ error instanceof Error ? error.message : "Unknown error",
852
+ "mkdir",
853
+ recursive ? ["-p", path] : [path]
854
+ );
855
+ throw error;
856
+ }
857
+ }
858
+
859
+ async writeFile(
860
+ path: string,
861
+ content: string,
862
+ encoding: string = "utf-8",
863
+ sessionId?: string
864
+ ): Promise<WriteFileResponse> {
865
+ try {
866
+ const targetSessionId = sessionId || this.sessionId;
867
+
868
+ const response = await this.doFetch(`/api/write`, {
869
+ body: JSON.stringify({
870
+ content,
871
+ encoding,
872
+ path,
873
+ sessionId: targetSessionId,
874
+ }),
875
+ headers: {
876
+ "Content-Type": "application/json",
877
+ },
878
+ method: "POST",
879
+ });
880
+
881
+ if (!response.ok) {
882
+ const errorData = (await response.json().catch(() => ({}))) as {
883
+ error?: string;
884
+ };
885
+ throw new Error(
886
+ errorData.error || `HTTP error! status: ${response.status}`
887
+ );
888
+ }
889
+
890
+ const data: WriteFileResponse = await response.json();
891
+ console.log(
892
+ `[HTTP Client] File written: ${path}, Success: ${data.success}`
893
+ );
894
+
895
+ return data;
896
+ } catch (error) {
897
+ console.error("[HTTP Client] Error writing file:", error);
898
+ throw error;
899
+ }
900
+ }
901
+
902
+ async writeFileStream(
903
+ path: string,
904
+ content: string,
905
+ encoding: string = "utf-8",
906
+ sessionId?: string
907
+ ): Promise<void> {
908
+ try {
909
+ const targetSessionId = sessionId || this.sessionId;
910
+
911
+ const response = await this.doFetch(`/api/write/stream`, {
912
+ body: JSON.stringify({
913
+ content,
914
+ encoding,
915
+ path,
916
+ sessionId: targetSessionId,
917
+ }),
918
+ headers: {
919
+ "Content-Type": "application/json",
920
+ },
921
+ method: "POST",
922
+ });
923
+
924
+ if (!response.ok) {
925
+ const errorData = (await response.json().catch(() => ({}))) as {
926
+ error?: string;
927
+ };
928
+ throw new Error(
929
+ errorData.error || `HTTP error! status: ${response.status}`
930
+ );
931
+ }
932
+
933
+ if (!response.body) {
934
+ throw new Error("No response body for streaming request");
935
+ }
936
+
937
+ const reader = response.body.getReader();
938
+ const decoder = new TextDecoder();
939
+
940
+ try {
941
+ while (true) {
942
+ const { done, value } = await reader.read();
943
+
944
+ if (done) {
945
+ break;
946
+ }
947
+
948
+ const chunk = decoder.decode(value, { stream: true });
949
+ const lines = chunk.split("\n");
950
+
951
+ for (const line of lines) {
952
+ if (line.startsWith("data: ")) {
953
+ try {
954
+ const eventData = line.slice(6); // Remove 'data: ' prefix
955
+ const event: StreamEvent = JSON.parse(eventData);
956
+
957
+ console.log(
958
+ `[HTTP Client] Write file stream event: ${event.type}`
959
+ );
960
+ this.options.onStreamEvent?.(event);
961
+
962
+ switch (event.type) {
963
+ case "command_start":
964
+ console.log(
965
+ `[HTTP Client] Write file started: ${event.path}`
966
+ );
967
+ this.options.onCommandStart?.("write", [
968
+ path,
969
+ content,
970
+ encoding,
971
+ ]);
972
+ break;
973
+
974
+ case "output":
975
+ console.log(`[output] ${event.message}`);
976
+ this.options.onOutput?.("stdout", event.message!, "write");
977
+ break;
978
+
979
+ case "command_complete":
980
+ console.log(
981
+ `[HTTP Client] Write file completed: ${event.path}, Success: ${event.success}`
982
+ );
983
+ this.options.onCommandComplete?.(
984
+ event.success!,
985
+ 0,
986
+ "",
987
+ "",
988
+ "write",
989
+ [path, content, encoding]
990
+ );
991
+ break;
992
+
993
+ case "error":
994
+ console.error(
995
+ `[HTTP Client] Write file error: ${event.error}`
996
+ );
997
+ this.options.onError?.(event.error!, "write", [
998
+ path,
999
+ content,
1000
+ encoding,
1001
+ ]);
1002
+ break;
1003
+ }
1004
+ } catch (parseError) {
1005
+ console.warn(
1006
+ "[HTTP Client] Failed to parse write file stream event:",
1007
+ parseError
1008
+ );
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+ } finally {
1014
+ reader.releaseLock();
1015
+ }
1016
+ } catch (error) {
1017
+ console.error("[HTTP Client] Error in streaming write file:", error);
1018
+ this.options.onError?.(
1019
+ error instanceof Error ? error.message : "Unknown error",
1020
+ "write",
1021
+ [path, content, encoding]
1022
+ );
1023
+ throw error;
1024
+ }
1025
+ }
1026
+
1027
+ async readFile(
1028
+ path: string,
1029
+ encoding: string = "utf-8",
1030
+ sessionId?: string
1031
+ ): Promise<ReadFileResponse> {
1032
+ try {
1033
+ const targetSessionId = sessionId || this.sessionId;
1034
+
1035
+ const response = await this.doFetch(`/api/read`, {
1036
+ body: JSON.stringify({
1037
+ encoding,
1038
+ path,
1039
+ sessionId: targetSessionId,
1040
+ }),
1041
+ headers: {
1042
+ "Content-Type": "application/json",
1043
+ },
1044
+ method: "POST",
1045
+ });
1046
+
1047
+ if (!response.ok) {
1048
+ const errorData = (await response.json().catch(() => ({}))) as {
1049
+ error?: string;
1050
+ };
1051
+ throw new Error(
1052
+ errorData.error || `HTTP error! status: ${response.status}`
1053
+ );
1054
+ }
1055
+
1056
+ const data: ReadFileResponse = await response.json();
1057
+ console.log(
1058
+ `[HTTP Client] File read: ${path}, Success: ${data.success}, Content length: ${data.content.length}`
1059
+ );
1060
+
1061
+ return data;
1062
+ } catch (error) {
1063
+ console.error("[HTTP Client] Error reading file:", error);
1064
+ throw error;
1065
+ }
1066
+ }
1067
+
1068
+ async readFileStream(
1069
+ path: string,
1070
+ encoding: string = "utf-8",
1071
+ sessionId?: string
1072
+ ): Promise<void> {
1073
+ try {
1074
+ const targetSessionId = sessionId || this.sessionId;
1075
+
1076
+ const response = await this.doFetch(`/api/read/stream`, {
1077
+ body: JSON.stringify({
1078
+ encoding,
1079
+ path,
1080
+ sessionId: targetSessionId,
1081
+ }),
1082
+ headers: {
1083
+ "Content-Type": "application/json",
1084
+ },
1085
+ method: "POST",
1086
+ });
1087
+
1088
+ if (!response.ok) {
1089
+ const errorData = (await response.json().catch(() => ({}))) as {
1090
+ error?: string;
1091
+ };
1092
+ throw new Error(
1093
+ errorData.error || `HTTP error! status: ${response.status}`
1094
+ );
1095
+ }
1096
+
1097
+ if (!response.body) {
1098
+ throw new Error("No response body for streaming request");
1099
+ }
1100
+
1101
+ const reader = response.body.getReader();
1102
+ const decoder = new TextDecoder();
1103
+
1104
+ try {
1105
+ while (true) {
1106
+ const { done, value } = await reader.read();
1107
+
1108
+ if (done) {
1109
+ break;
1110
+ }
1111
+
1112
+ const chunk = decoder.decode(value, { stream: true });
1113
+ const lines = chunk.split("\n");
1114
+
1115
+ for (const line of lines) {
1116
+ if (line.startsWith("data: ")) {
1117
+ try {
1118
+ const eventData = line.slice(6); // Remove 'data: ' prefix
1119
+ const event: StreamEvent = JSON.parse(eventData);
1120
+
1121
+ console.log(
1122
+ `[HTTP Client] Read file stream event: ${event.type}`
1123
+ );
1124
+ this.options.onStreamEvent?.(event);
1125
+
1126
+ switch (event.type) {
1127
+ case "command_start":
1128
+ console.log(
1129
+ `[HTTP Client] Read file started: ${event.path}`
1130
+ );
1131
+ this.options.onCommandStart?.("read", [path, encoding]);
1132
+ break;
1133
+
1134
+ case "command_complete":
1135
+ console.log(
1136
+ `[HTTP Client] Read file completed: ${
1137
+ event.path
1138
+ }, Success: ${event.success}, Content length: ${
1139
+ event.content?.length || 0
1140
+ }`
1141
+ );
1142
+ this.options.onCommandComplete?.(
1143
+ event.success!,
1144
+ 0,
1145
+ event.content || "",
1146
+ "",
1147
+ "read",
1148
+ [path, encoding]
1149
+ );
1150
+ break;
1151
+
1152
+ case "error":
1153
+ console.error(
1154
+ `[HTTP Client] Read file error: ${event.error}`
1155
+ );
1156
+ this.options.onError?.(event.error!, "read", [
1157
+ path,
1158
+ encoding,
1159
+ ]);
1160
+ break;
1161
+ }
1162
+ } catch (parseError) {
1163
+ console.warn(
1164
+ "[HTTP Client] Failed to parse read file stream event:",
1165
+ parseError
1166
+ );
1167
+ }
1168
+ }
1169
+ }
1170
+ }
1171
+ } finally {
1172
+ reader.releaseLock();
1173
+ }
1174
+ } catch (error) {
1175
+ console.error("[HTTP Client] Error in streaming read file:", error);
1176
+ this.options.onError?.(
1177
+ error instanceof Error ? error.message : "Unknown error",
1178
+ "read",
1179
+ [path, encoding]
1180
+ );
1181
+ throw error;
1182
+ }
1183
+ }
1184
+
1185
+ async deleteFile(
1186
+ path: string,
1187
+ sessionId?: string
1188
+ ): Promise<DeleteFileResponse> {
1189
+ try {
1190
+ const targetSessionId = sessionId || this.sessionId;
1191
+
1192
+ const response = await this.doFetch(`/api/delete`, {
1193
+ body: JSON.stringify({
1194
+ path,
1195
+ sessionId: targetSessionId,
1196
+ }),
1197
+ headers: {
1198
+ "Content-Type": "application/json",
1199
+ },
1200
+ method: "POST",
1201
+ });
1202
+
1203
+ if (!response.ok) {
1204
+ const errorData = (await response.json().catch(() => ({}))) as {
1205
+ error?: string;
1206
+ };
1207
+ throw new Error(
1208
+ errorData.error || `HTTP error! status: ${response.status}`
1209
+ );
1210
+ }
1211
+
1212
+ const data: DeleteFileResponse = await response.json();
1213
+ console.log(
1214
+ `[HTTP Client] File deleted: ${path}, Success: ${data.success}`
1215
+ );
1216
+
1217
+ return data;
1218
+ } catch (error) {
1219
+ console.error("[HTTP Client] Error deleting file:", error);
1220
+ throw error;
1221
+ }
1222
+ }
1223
+
1224
+ async deleteFileStream(path: string, sessionId?: string): Promise<void> {
1225
+ try {
1226
+ const targetSessionId = sessionId || this.sessionId;
1227
+
1228
+ const response = await this.doFetch(`/api/delete/stream`, {
1229
+ body: JSON.stringify({
1230
+ path,
1231
+ sessionId: targetSessionId,
1232
+ }),
1233
+ headers: {
1234
+ "Content-Type": "application/json",
1235
+ },
1236
+ method: "POST",
1237
+ });
1238
+
1239
+ if (!response.ok) {
1240
+ const errorData = (await response.json().catch(() => ({}))) as {
1241
+ error?: string;
1242
+ };
1243
+ throw new Error(
1244
+ errorData.error || `HTTP error! status: ${response.status}`
1245
+ );
1246
+ }
1247
+
1248
+ if (!response.body) {
1249
+ throw new Error("No response body for streaming request");
1250
+ }
1251
+
1252
+ const reader = response.body.getReader();
1253
+ const decoder = new TextDecoder();
1254
+
1255
+ try {
1256
+ while (true) {
1257
+ const { done, value } = await reader.read();
1258
+
1259
+ if (done) {
1260
+ break;
1261
+ }
1262
+
1263
+ const chunk = decoder.decode(value, { stream: true });
1264
+ const lines = chunk.split("\n");
1265
+
1266
+ for (const line of lines) {
1267
+ if (line.startsWith("data: ")) {
1268
+ try {
1269
+ const eventData = line.slice(6); // Remove 'data: ' prefix
1270
+ const event: StreamEvent = JSON.parse(eventData);
1271
+
1272
+ console.log(
1273
+ `[HTTP Client] Delete file stream event: ${event.type}`
1274
+ );
1275
+ this.options.onStreamEvent?.(event);
1276
+
1277
+ switch (event.type) {
1278
+ case "command_start":
1279
+ console.log(
1280
+ `[HTTP Client] Delete file started: ${event.path}`
1281
+ );
1282
+ this.options.onCommandStart?.("delete", [path]);
1283
+ break;
1284
+
1285
+ case "command_complete":
1286
+ console.log(
1287
+ `[HTTP Client] Delete file completed: ${event.path}, Success: ${event.success}`
1288
+ );
1289
+ this.options.onCommandComplete?.(
1290
+ event.success!,
1291
+ 0,
1292
+ "",
1293
+ "",
1294
+ "delete",
1295
+ [path]
1296
+ );
1297
+ break;
1298
+
1299
+ case "error":
1300
+ console.error(
1301
+ `[HTTP Client] Delete file error: ${event.error}`
1302
+ );
1303
+ this.options.onError?.(event.error!, "delete", [path]);
1304
+ break;
1305
+ }
1306
+ } catch (parseError) {
1307
+ console.warn(
1308
+ "[HTTP Client] Failed to parse delete file stream event:",
1309
+ parseError
1310
+ );
1311
+ }
1312
+ }
1313
+ }
1314
+ }
1315
+ } finally {
1316
+ reader.releaseLock();
1317
+ }
1318
+ } catch (error) {
1319
+ console.error("[HTTP Client] Error in streaming delete file:", error);
1320
+ this.options.onError?.(
1321
+ error instanceof Error ? error.message : "Unknown error",
1322
+ "delete",
1323
+ [path]
1324
+ );
1325
+ throw error;
1326
+ }
1327
+ }
1328
+
1329
+ async renameFile(
1330
+ oldPath: string,
1331
+ newPath: string,
1332
+ sessionId?: string
1333
+ ): Promise<RenameFileResponse> {
1334
+ try {
1335
+ const targetSessionId = sessionId || this.sessionId;
1336
+
1337
+ const response = await this.doFetch(`/api/rename`, {
1338
+ body: JSON.stringify({
1339
+ newPath,
1340
+ oldPath,
1341
+ sessionId: targetSessionId,
1342
+ }),
1343
+ headers: {
1344
+ "Content-Type": "application/json",
1345
+ },
1346
+ method: "POST",
1347
+ });
1348
+
1349
+ if (!response.ok) {
1350
+ const errorData = (await response.json().catch(() => ({}))) as {
1351
+ error?: string;
1352
+ };
1353
+ throw new Error(
1354
+ errorData.error || `HTTP error! status: ${response.status}`
1355
+ );
1356
+ }
1357
+
1358
+ const data: RenameFileResponse = await response.json();
1359
+ console.log(
1360
+ `[HTTP Client] File renamed: ${oldPath} -> ${newPath}, Success: ${data.success}`
1361
+ );
1362
+
1363
+ return data;
1364
+ } catch (error) {
1365
+ console.error("[HTTP Client] Error renaming file:", error);
1366
+ throw error;
1367
+ }
1368
+ }
1369
+
1370
+ async renameFileStream(
1371
+ oldPath: string,
1372
+ newPath: string,
1373
+ sessionId?: string
1374
+ ): Promise<void> {
1375
+ try {
1376
+ const targetSessionId = sessionId || this.sessionId;
1377
+
1378
+ const response = await this.doFetch(`/api/rename/stream`, {
1379
+ body: JSON.stringify({
1380
+ newPath,
1381
+ oldPath,
1382
+ sessionId: targetSessionId,
1383
+ }),
1384
+ headers: {
1385
+ "Content-Type": "application/json",
1386
+ },
1387
+ method: "POST",
1388
+ });
1389
+
1390
+ if (!response.ok) {
1391
+ const errorData = (await response.json().catch(() => ({}))) as {
1392
+ error?: string;
1393
+ };
1394
+ throw new Error(
1395
+ errorData.error || `HTTP error! status: ${response.status}`
1396
+ );
1397
+ }
1398
+
1399
+ if (!response.body) {
1400
+ throw new Error("No response body for streaming request");
1401
+ }
1402
+
1403
+ const reader = response.body.getReader();
1404
+ const decoder = new TextDecoder();
1405
+
1406
+ try {
1407
+ while (true) {
1408
+ const { done, value } = await reader.read();
1409
+
1410
+ if (done) {
1411
+ break;
1412
+ }
1413
+
1414
+ const chunk = decoder.decode(value, { stream: true });
1415
+ const lines = chunk.split("\n");
1416
+
1417
+ for (const line of lines) {
1418
+ if (line.startsWith("data: ")) {
1419
+ try {
1420
+ const eventData = line.slice(6); // Remove 'data: ' prefix
1421
+ const event: StreamEvent = JSON.parse(eventData);
1422
+
1423
+ console.log(
1424
+ `[HTTP Client] Rename file stream event: ${event.type}`
1425
+ );
1426
+ this.options.onStreamEvent?.(event);
1427
+
1428
+ switch (event.type) {
1429
+ case "command_start":
1430
+ console.log(
1431
+ `[HTTP Client] Rename file started: ${event.oldPath} -> ${event.newPath}`
1432
+ );
1433
+ this.options.onCommandStart?.("rename", [oldPath, newPath]);
1434
+ break;
1435
+
1436
+ case "command_complete":
1437
+ console.log(
1438
+ `[HTTP Client] Rename file completed: ${event.oldPath} -> ${event.newPath}, Success: ${event.success}`
1439
+ );
1440
+ this.options.onCommandComplete?.(
1441
+ event.success!,
1442
+ 0,
1443
+ "",
1444
+ "",
1445
+ "rename",
1446
+ [oldPath, newPath]
1447
+ );
1448
+ break;
1449
+
1450
+ case "error":
1451
+ console.error(
1452
+ `[HTTP Client] Rename file error: ${event.error}`
1453
+ );
1454
+ this.options.onError?.(event.error!, "rename", [
1455
+ oldPath,
1456
+ newPath,
1457
+ ]);
1458
+ break;
1459
+ }
1460
+ } catch (parseError) {
1461
+ console.warn(
1462
+ "[HTTP Client] Failed to parse rename file stream event:",
1463
+ parseError
1464
+ );
1465
+ }
1466
+ }
1467
+ }
1468
+ }
1469
+ } finally {
1470
+ reader.releaseLock();
1471
+ }
1472
+ } catch (error) {
1473
+ console.error("[HTTP Client] Error in streaming rename file:", error);
1474
+ this.options.onError?.(
1475
+ error instanceof Error ? error.message : "Unknown error",
1476
+ "rename",
1477
+ [oldPath, newPath]
1478
+ );
1479
+ throw error;
1480
+ }
1481
+ }
1482
+
1483
+ async moveFile(
1484
+ sourcePath: string,
1485
+ destinationPath: string,
1486
+ sessionId?: string
1487
+ ): Promise<MoveFileResponse> {
1488
+ try {
1489
+ const targetSessionId = sessionId || this.sessionId;
1490
+
1491
+ const response = await this.doFetch(`/api/move`, {
1492
+ body: JSON.stringify({
1493
+ destinationPath,
1494
+ sessionId: targetSessionId,
1495
+ sourcePath,
1496
+ }),
1497
+ headers: {
1498
+ "Content-Type": "application/json",
1499
+ },
1500
+ method: "POST",
1501
+ });
1502
+
1503
+ if (!response.ok) {
1504
+ const errorData = (await response.json().catch(() => ({}))) as {
1505
+ error?: string;
1506
+ };
1507
+ throw new Error(
1508
+ errorData.error || `HTTP error! status: ${response.status}`
1509
+ );
1510
+ }
1511
+
1512
+ const data: MoveFileResponse = await response.json();
1513
+ console.log(
1514
+ `[HTTP Client] File moved: ${sourcePath} -> ${destinationPath}, Success: ${data.success}`
1515
+ );
1516
+
1517
+ return data;
1518
+ } catch (error) {
1519
+ console.error("[HTTP Client] Error moving file:", error);
1520
+ throw error;
1521
+ }
1522
+ }
1523
+
1524
+ async moveFileStream(
1525
+ sourcePath: string,
1526
+ destinationPath: string,
1527
+ sessionId?: string
1528
+ ): Promise<void> {
1529
+ try {
1530
+ const targetSessionId = sessionId || this.sessionId;
1531
+
1532
+ const response = await this.doFetch(`/api/move/stream`, {
1533
+ body: JSON.stringify({
1534
+ destinationPath,
1535
+ sessionId: targetSessionId,
1536
+ sourcePath,
1537
+ }),
1538
+ headers: {
1539
+ "Content-Type": "application/json",
1540
+ },
1541
+ method: "POST",
1542
+ });
1543
+
1544
+ if (!response.ok) {
1545
+ const errorData = (await response.json().catch(() => ({}))) as {
1546
+ error?: string;
1547
+ };
1548
+ throw new Error(
1549
+ errorData.error || `HTTP error! status: ${response.status}`
1550
+ );
1551
+ }
1552
+
1553
+ if (!response.body) {
1554
+ throw new Error("No response body for streaming request");
1555
+ }
1556
+
1557
+ const reader = response.body.getReader();
1558
+ const decoder = new TextDecoder();
1559
+
1560
+ try {
1561
+ while (true) {
1562
+ const { done, value } = await reader.read();
1563
+
1564
+ if (done) {
1565
+ break;
1566
+ }
1567
+
1568
+ const chunk = decoder.decode(value, { stream: true });
1569
+ const lines = chunk.split("\n");
1570
+
1571
+ for (const line of lines) {
1572
+ if (line.startsWith("data: ")) {
1573
+ try {
1574
+ const eventData = line.slice(6); // Remove 'data: ' prefix
1575
+ const event: StreamEvent = JSON.parse(eventData);
1576
+
1577
+ console.log(
1578
+ `[HTTP Client] Move file stream event: ${event.type}`
1579
+ );
1580
+ this.options.onStreamEvent?.(event);
1581
+
1582
+ switch (event.type) {
1583
+ case "command_start":
1584
+ console.log(
1585
+ `[HTTP Client] Move file started: ${event.sourcePath} -> ${event.destinationPath}`
1586
+ );
1587
+ this.options.onCommandStart?.("move", [
1588
+ sourcePath,
1589
+ destinationPath,
1590
+ ]);
1591
+ break;
1592
+
1593
+ case "command_complete":
1594
+ console.log(
1595
+ `[HTTP Client] Move file completed: ${event.sourcePath} -> ${event.destinationPath}, Success: ${event.success}`
1596
+ );
1597
+ this.options.onCommandComplete?.(
1598
+ event.success!,
1599
+ 0,
1600
+ "",
1601
+ "",
1602
+ "move",
1603
+ [sourcePath, destinationPath]
1604
+ );
1605
+ break;
1606
+
1607
+ case "error":
1608
+ console.error(
1609
+ `[HTTP Client] Move file error: ${event.error}`
1610
+ );
1611
+ this.options.onError?.(event.error!, "move", [
1612
+ sourcePath,
1613
+ destinationPath,
1614
+ ]);
1615
+ break;
1616
+ }
1617
+ } catch (parseError) {
1618
+ console.warn(
1619
+ "[HTTP Client] Failed to parse move file stream event:",
1620
+ parseError
1621
+ );
1622
+ }
1623
+ }
1624
+ }
1625
+ }
1626
+ } finally {
1627
+ reader.releaseLock();
1628
+ }
1629
+ } catch (error) {
1630
+ console.error("[HTTP Client] Error in streaming move file:", error);
1631
+ this.options.onError?.(
1632
+ error instanceof Error ? error.message : "Unknown error",
1633
+ "move",
1634
+ [sourcePath, destinationPath]
1635
+ );
1636
+ throw error;
1637
+ }
1638
+ }
1639
+
1640
+ async ping(): Promise<string> {
1641
+ try {
1642
+ const response = await this.doFetch(`/api/ping`, {
1643
+ headers: {
1644
+ "Content-Type": "application/json",
1645
+ },
1646
+ method: "GET",
1647
+ });
1648
+
1649
+ if (!response.ok) {
1650
+ throw new Error(`HTTP error! status: ${response.status}`);
1651
+ }
1652
+
1653
+ const data: PingResponse = await response.json();
1654
+ console.log(`[HTTP Client] Ping response: ${data.message}`);
1655
+ return data.timestamp;
1656
+ } catch (error) {
1657
+ console.error("[HTTP Client] Error pinging server:", error);
1658
+ throw error;
1659
+ }
1660
+ }
1661
+
1662
+ async getCommands(): Promise<string[]> {
1663
+ try {
1664
+ const response = await fetch(`${this.baseUrl}/api/commands`, {
1665
+ headers: {
1666
+ "Content-Type": "application/json",
1667
+ },
1668
+ method: "GET",
1669
+ });
1670
+
1671
+ if (!response.ok) {
1672
+ throw new Error(`HTTP error! status: ${response.status}`);
1673
+ }
1674
+
1675
+ const data: CommandsResponse = await response.json();
1676
+ console.log(
1677
+ `[HTTP Client] Available commands: ${data.availableCommands.length}`
1678
+ );
1679
+ return data.availableCommands;
1680
+ } catch (error) {
1681
+ console.error("[HTTP Client] Error getting commands:", error);
1682
+ throw error;
1683
+ }
1684
+ }
1685
+
1686
+ getSessionId(): string | null {
1687
+ return this.sessionId;
1688
+ }
1689
+
1690
+ setSessionId(sessionId: string): void {
1691
+ this.sessionId = sessionId;
1692
+ }
1693
+
1694
+ clearSession(): void {
1695
+ this.sessionId = null;
1696
+ }
1697
+ }
1698
+
1699
+ // Example usage and utility functions
1700
+ export function createClient(options?: HttpClientOptions): HttpClient {
1701
+ return new HttpClient(options);
1702
+ }
1703
+
1704
+ // Convenience function for quick command execution
1705
+ export async function quickExecute(
1706
+ command: string,
1707
+ args: string[] = [],
1708
+ options?: HttpClientOptions
1709
+ ): Promise<ExecuteResponse> {
1710
+ const client = createClient(options);
1711
+ await client.createSession();
1712
+
1713
+ try {
1714
+ return await client.execute(command, args);
1715
+ } finally {
1716
+ client.clearSession();
1717
+ }
1718
+ }
1719
+
1720
+ // Convenience function for quick streaming command execution
1721
+ export async function quickExecuteStream(
1722
+ command: string,
1723
+ args: string[] = [],
1724
+ options?: HttpClientOptions
1725
+ ): Promise<void> {
1726
+ const client = createClient(options);
1727
+ await client.createSession();
1728
+
1729
+ try {
1730
+ await client.executeStream(command, args);
1731
+ } finally {
1732
+ client.clearSession();
1733
+ }
1734
+ }
1735
+
1736
+ // Convenience function for quick git checkout
1737
+ export async function quickGitCheckout(
1738
+ repoUrl: string,
1739
+ branch: string = "main",
1740
+ targetDir?: string,
1741
+ options?: HttpClientOptions
1742
+ ): Promise<GitCheckoutResponse> {
1743
+ const client = createClient(options);
1744
+ await client.createSession();
1745
+
1746
+ try {
1747
+ return await client.gitCheckout(repoUrl, branch, targetDir);
1748
+ } finally {
1749
+ client.clearSession();
1750
+ }
1751
+ }
1752
+
1753
+ // Convenience function for quick directory creation
1754
+ export async function quickMkdir(
1755
+ path: string,
1756
+ recursive: boolean = false,
1757
+ options?: HttpClientOptions
1758
+ ): Promise<MkdirResponse> {
1759
+ const client = createClient(options);
1760
+ await client.createSession();
1761
+
1762
+ try {
1763
+ return await client.mkdir(path, recursive);
1764
+ } finally {
1765
+ client.clearSession();
1766
+ }
1767
+ }
1768
+
1769
+ // Convenience function for quick streaming git checkout
1770
+ export async function quickGitCheckoutStream(
1771
+ repoUrl: string,
1772
+ branch: string = "main",
1773
+ targetDir?: string,
1774
+ options?: HttpClientOptions
1775
+ ): Promise<void> {
1776
+ const client = createClient(options);
1777
+ await client.createSession();
1778
+
1779
+ try {
1780
+ await client.gitCheckoutStream(repoUrl, branch, targetDir);
1781
+ } finally {
1782
+ client.clearSession();
1783
+ }
1784
+ }
1785
+
1786
+ // Convenience function for quick streaming directory creation
1787
+ export async function quickMkdirStream(
1788
+ path: string,
1789
+ recursive: boolean = false,
1790
+ options?: HttpClientOptions
1791
+ ): Promise<void> {
1792
+ const client = createClient(options);
1793
+ await client.createSession();
1794
+
1795
+ try {
1796
+ await client.mkdirStream(path, recursive);
1797
+ } finally {
1798
+ client.clearSession();
1799
+ }
1800
+ }
1801
+
1802
+ // Convenience function for quick file writing
1803
+ export async function quickWriteFile(
1804
+ path: string,
1805
+ content: string,
1806
+ encoding: string = "utf-8",
1807
+ options?: HttpClientOptions
1808
+ ): Promise<WriteFileResponse> {
1809
+ const client = createClient(options);
1810
+ await client.createSession();
1811
+
1812
+ try {
1813
+ return await client.writeFile(path, content, encoding);
1814
+ } finally {
1815
+ client.clearSession();
1816
+ }
1817
+ }
1818
+
1819
+ // Convenience function for quick streaming file writing
1820
+ export async function quickWriteFileStream(
1821
+ path: string,
1822
+ content: string,
1823
+ encoding: string = "utf-8",
1824
+ options?: HttpClientOptions
1825
+ ): Promise<void> {
1826
+ const client = createClient(options);
1827
+ await client.createSession();
1828
+
1829
+ try {
1830
+ await client.writeFileStream(path, content, encoding);
1831
+ } finally {
1832
+ client.clearSession();
1833
+ }
1834
+ }
1835
+
1836
+ // Convenience function for quick file reading
1837
+ export async function quickReadFile(
1838
+ path: string,
1839
+ encoding: string = "utf-8",
1840
+ options?: HttpClientOptions
1841
+ ): Promise<ReadFileResponse> {
1842
+ const client = createClient(options);
1843
+ await client.createSession();
1844
+
1845
+ try {
1846
+ return await client.readFile(path, encoding);
1847
+ } finally {
1848
+ client.clearSession();
1849
+ }
1850
+ }
1851
+
1852
+ // Convenience function for quick streaming file reading
1853
+ export async function quickReadFileStream(
1854
+ path: string,
1855
+ encoding: string = "utf-8",
1856
+ options?: HttpClientOptions
1857
+ ): Promise<void> {
1858
+ const client = createClient(options);
1859
+ await client.createSession();
1860
+
1861
+ try {
1862
+ await client.readFileStream(path, encoding);
1863
+ } finally {
1864
+ client.clearSession();
1865
+ }
1866
+ }
1867
+
1868
+ // Convenience function for quick file deletion
1869
+ export async function quickDeleteFile(
1870
+ path: string,
1871
+ options?: HttpClientOptions
1872
+ ): Promise<DeleteFileResponse> {
1873
+ const client = createClient(options);
1874
+ await client.createSession();
1875
+
1876
+ try {
1877
+ return await client.deleteFile(path);
1878
+ } finally {
1879
+ client.clearSession();
1880
+ }
1881
+ }
1882
+
1883
+ // Convenience function for quick streaming file deletion
1884
+ export async function quickDeleteFileStream(
1885
+ path: string,
1886
+ options?: HttpClientOptions
1887
+ ): Promise<void> {
1888
+ const client = createClient(options);
1889
+ await client.createSession();
1890
+
1891
+ try {
1892
+ await client.deleteFileStream(path);
1893
+ } finally {
1894
+ client.clearSession();
1895
+ }
1896
+ }
1897
+
1898
+ // Convenience function for quick file renaming
1899
+ export async function quickRenameFile(
1900
+ oldPath: string,
1901
+ newPath: string,
1902
+ options?: HttpClientOptions
1903
+ ): Promise<RenameFileResponse> {
1904
+ const client = createClient(options);
1905
+ await client.createSession();
1906
+
1907
+ try {
1908
+ return await client.renameFile(oldPath, newPath);
1909
+ } finally {
1910
+ client.clearSession();
1911
+ }
1912
+ }
1913
+
1914
+ // Convenience function for quick streaming file renaming
1915
+ export async function quickRenameFileStream(
1916
+ oldPath: string,
1917
+ newPath: string,
1918
+ options?: HttpClientOptions
1919
+ ): Promise<void> {
1920
+ const client = createClient(options);
1921
+ await client.createSession();
1922
+
1923
+ try {
1924
+ await client.renameFileStream(oldPath, newPath);
1925
+ } finally {
1926
+ client.clearSession();
1927
+ }
1928
+ }
1929
+
1930
+ // Convenience function for quick file moving
1931
+ export async function quickMoveFile(
1932
+ sourcePath: string,
1933
+ destinationPath: string,
1934
+ options?: HttpClientOptions
1935
+ ): Promise<MoveFileResponse> {
1936
+ const client = createClient(options);
1937
+ await client.createSession();
1938
+
1939
+ try {
1940
+ return await client.moveFile(sourcePath, destinationPath);
1941
+ } finally {
1942
+ client.clearSession();
1943
+ }
1944
+ }
1945
+
1946
+ // Convenience function for quick streaming file moving
1947
+ export async function quickMoveFileStream(
1948
+ sourcePath: string,
1949
+ destinationPath: string,
1950
+ options?: HttpClientOptions
1951
+ ): Promise<void> {
1952
+ const client = createClient(options);
1953
+ await client.createSession();
1954
+
1955
+ try {
1956
+ await client.moveFileStream(sourcePath, destinationPath);
1957
+ } finally {
1958
+ client.clearSession();
1959
+ }
1960
+ }