-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.clj
More file actions
1481 lines (1361 loc) · 68.8 KB
/
client.clj
File metadata and controls
1481 lines (1361 loc) · 68.8 KB
1
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns github.copilot-sdk.client
"CopilotClient - manages connection to the Copilot CLI server."
(:require [clojure.core.async :as async :refer [go go-loop <! >! >!! chan close!]]
[clojure.spec.alpha :as s]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.data.json :as json]
[github.copilot-sdk.protocol :as proto]
[github.copilot-sdk.process :as proc]
[github.copilot-sdk.specs :as specs]
[github.copilot-sdk.session :as session]
[github.copilot-sdk.util :as util]
[github.copilot-sdk.logging :as log])
(:import [java.net Socket]
[java.util.concurrent LinkedBlockingQueue]))
(def ^:private sdk-protocol-version-max 3)
(def ^:private sdk-protocol-version-min 2)
(defn- parse-cli-url
"Parse CLI URL into {:host :port}."
[url]
(let [clean (str/replace url #"^https?://" "")]
(if (re-matches #"\d+" clean)
;; Port only
(let [port (parse-long clean)]
(when (or (nil? port) (<= port 0) (> port 65535))
(throw (ex-info "Invalid port in cli-url" {:url url :port port})))
{:host "localhost" :port port})
;; host:port
(let [[host port-str] (str/split clean #":" 2)]
(when (or (str/blank? port-str) (not (re-matches #"-?\d+" port-str)))
(throw (ex-info "Invalid cli-url format" {:url url})))
(let [port (parse-long port-str)]
(when (or (nil? port) (<= port 0) (> port 65535))
(throw (ex-info "Invalid port in cli-url" {:url url :port port})))
{:host (if (str/blank? host) "localhost" host)
:port port})))))
(defn- default-options
"Return default client options."
[]
{:cli-path "copilot"
:cli-args []
:cwd (System/getProperty "user.dir")
:port 0
:use-stdio? true
:log-level :info
:auto-start? true
:auto-restart? true
:notification-queue-size 4096
:router-queue-size 4096
:tool-timeout-ms 120000
:env nil})
(defn- ensure-valid-mcp-servers!
[servers]
(when-not (s/valid? ::specs/mcp-servers servers)
(throw (ex-info "Invalid :mcp-servers config (expected map keyed by server ID)."
{:spec ::specs/mcp-servers
:mcp-servers servers
:explain (s/explain-data ::specs/mcp-servers servers)}))))
;; Client is a simple map with a single state atom
;; The state atom contains all mutable state as an immutable map:
;; {:status :disconnected/:connecting/:connected/:error
;; :connection {:running? :pending-requests :request-handler :writer-thread}
;; :connection-io nil or protocol/Connection (IO resources only)
;; :process nil or process/ManagedProcess
;; :socket nil or Socket (for TCP mode)
;; :sessions {session-id -> {:tool-handlers :permission-handler :destroyed?}}
;; :session-io {session-id -> {:event-chan :event-mult}} (IO resources)
;; :actual-port nil or int
;; :router-ch nil or channel
;; :stopping? false
;; :restarting? false
;; :force-stopping? false
;; :models-cache nil|promise|vector (list-models cache)
;; :lifecycle-handlers {handler-id -> {:handler fn :event-type type-or-nil}}}
(defn- initial-state
"Create initial client state."
[port]
{:status :disconnected
:connection nil ; protocol state (when connected)
:connection-io nil ; protocol/Connection record (IO resources)
:process nil
:socket nil
:sessions {} ; session state by session-id
:session-io {} ; session IO resources by session-id
:actual-port port
:router-ch nil
:router-queue nil
:router-thread nil
:router-running? false
:stopping? false
:restarting? false
:force-stopping? false
:models-cache nil ; nil, promise, or vector of models (cleared on stop)
:lifecycle-handlers {}
:stderr-buffer nil ; atom of recent stderr lines (for error context)
:negotiated-protocol-version 0})
(defn client
"Create a new CopilotClient.
Options:
- :cli-path - Path to CLI executable (default: \"copilot\")
- :cli-args - Extra arguments for CLI
- :cli-url - URL of existing server (e.g., \"localhost:8080\")
- :cwd - Working directory for CLI process
- :port - TCP port (default: 0 for random)
- :use-stdio? - Use stdio transport (default: true)
- :log-level - :none :error :warning :info :debug :all
- :auto-start? - Auto-start on first use (default: true)
- :auto-restart? - Auto-restart on crash (default: true)
- :notification-queue-size - Max queued protocol notifications (default: 4096)
- :router-queue-size - Max queued non-session notifications (default: 4096)
- :tool-timeout-ms - Timeout for tool calls that return a channel (default: 120000)
- :env - Environment variables map
- :github-token - GitHub token for authentication (sets COPILOT_SDK_AUTH_TOKEN env var)
- :use-logged-in-user? - Whether to use logged-in user auth (default: true, false when github-token provided)
- :is-child-process? - When true, SDK is a child of an existing Copilot CLI process and uses stdio to communicate with it (no process spawning)
- :on-list-models - Zero-arg fn returning a seq of model info maps; bypasses the RPC call and does not require start!"
([]
(client {}))
([opts]
(when (and (:cli-url opts) (= true (:use-stdio? opts)))
(throw (ex-info "cli-url is mutually exclusive with use-stdio?" opts)))
(when (and (:cli-url opts) (:cli-path opts))
(throw (ex-info "cli-url is mutually exclusive with cli-path" opts)))
;; Validation: github-token and use-logged-in-user? cannot be used with cli-url
(when (and (:cli-url opts) (or (:github-token opts) (some? (:use-logged-in-user? opts))))
(throw (ex-info "github-token and use-logged-in-user? cannot be used with cli-url (external server manages its own auth)"
{:cli-url (:cli-url opts)
:github-token (when (:github-token opts) "***")
:use-logged-in-user? (:use-logged-in-user? opts)})))
;; Validation: is-child-process? is mutually exclusive with cli-url
(when (and (:is-child-process? opts) (:cli-url opts))
(throw (ex-info "is-child-process? is mutually exclusive with cli-url"
{:is-child-process? true :cli-url (:cli-url opts)})))
;; Validation: is-child-process? requires stdio transport
(when (and (:is-child-process? opts) (= false (:use-stdio? opts)))
(throw (ex-info "is-child-process? requires use-stdio? to be true (or unset)"
{:is-child-process? true :use-stdio? false})))
(when-not (s/valid? ::specs/client-options opts)
(let [unknown (specs/unknown-keys opts specs/client-options-keys)
explain (s/explain-data ::specs/client-options opts)
msg (if (seq unknown)
(format "Invalid client options: unknown keys %s. Valid keys are: %s"
(pr-str unknown)
(pr-str (sort specs/client-options-keys)))
(format "Invalid client options: %s"
(with-out-str (s/explain ::specs/client-options opts))))]
(throw (ex-info msg {:options opts :unknown-keys unknown :explain explain}))))
(when-let [size (:notification-queue-size opts)]
(when (<= size 0)
(throw (ex-info "notification-queue-size must be > 0" {:notification-queue-size size}))))
(when-let [size (:router-queue-size opts)]
(when (<= size 0)
(throw (ex-info "router-queue-size must be > 0" {:router-queue-size size}))))
(when-let [timeout (:tool-timeout-ms opts)]
(when (<= timeout 0)
(throw (ex-info "tool-timeout-ms must be > 0" {:tool-timeout-ms timeout}))))
(let [;; Default use-logged-in-user? to false when github-token is provided, otherwise true
opts-with-defaults (cond-> opts
(and (:github-token opts) (nil? (:use-logged-in-user? opts)))
(assoc :use-logged-in-user? false))
merged (merge (default-options) opts-with-defaults)
child-process? (:is-child-process? opts)
cli-url? (boolean (:cli-url opts))
external? (or cli-url? child-process?)
{:keys [host port]} (when cli-url?
(parse-cli-url (:cli-url opts)))
final-opts (cond-> merged
cli-url? (-> (assoc :use-stdio? false)
(assoc :host host)
(assoc :port port)
(assoc :external-server? true))
child-process? (assoc :external-server? true))]
(cond-> {:options final-opts
:external-server? external?
:actual-host (or host "localhost")
:state (atom (assoc (initial-state port) :options final-opts))}
(:on-list-models opts)
(assoc :on-list-models (:on-list-models opts))))))
(defn state
"Get the current connection state."
[client]
(:status @(:state client)))
(defn options
"Get the client options that were used to create this client.
Returns the user-provided options merged with defaults.
Note: This reflects SDK configuration, not necessarily server state."
[client]
(:options @(:state client)))
(declare stop!)
(declare start!)
(declare maybe-reconnect!)
(declare negotiated-protocol-version)
;; ---------------------------------------------------------------------------
;; Protocol v3 broadcast event handlers
;; ---------------------------------------------------------------------------
(defn- handle-v3-tool-requested!
"Handle v3 external_tool.requested broadcast event.
Calls the session's tool handler and responds via the
session.tools.handlePendingToolCall RPC method."
[client session-id event]
(let [data (:data event)
request-id (:request-id data)
tool-name (:tool-name data)
tool-call-id (:tool-call-id data)
arguments (:arguments data)]
(when (and request-id tool-name)
(go
(try
(let [tool-response (<! (session/handle-tool-call!
client session-id tool-call-id tool-name arguments))
result (:result tool-response)
conn (:connection-io @(:state client))]
(when conn
(<! (proto/send-request conn "session.tools.handlePendingToolCall"
{:session-id session-id
:request-id request-id
:result result}))))
(catch Exception e
(log/debug "v3 tool call error for " request-id ": " (ex-message e))
(try
(let [conn (:connection-io @(:state client))]
(when conn
(<! (proto/send-request conn "session.tools.handlePendingToolCall"
{:session-id session-id
:request-id request-id
:result {:text-result-for-llm
"Invoking this tool produced an error."
:result-type "failure"
:error (ex-message e)
:tool-telemetry {}}}))))
(catch Exception _ nil))))))))
(defn- handle-v3-permission-requested!
"Handle v3 permission.requested broadcast event.
Calls the session's permission handler and responds via the
session.permissions.handlePendingPermissionRequest RPC method."
[client session-id event]
(let [data (:data event)
request-id (:request-id data)
permission-request (:permission-request data)]
(when (and request-id permission-request)
(go
(try
(let [perm-response (<! (session/handle-permission-request!
client session-id permission-request))
result (:result perm-response)
conn (:connection-io @(:state client))]
(when conn
(<! (proto/send-request conn "session.permissions.handlePendingPermissionRequest"
{:session-id session-id
:request-id request-id
:result result}))))
(catch Exception e
(log/debug "v3 permission request error for " request-id ": " (ex-message e))
(try
(let [conn (:connection-io @(:state client))]
(when conn
(<! (proto/send-request conn "session.permissions.handlePendingPermissionRequest"
{:session-id session-id
:request-id request-id
:result {:kind :denied-no-approval-rule-and-could-not-request-from-user}}))))
(catch Exception _ nil))))))))
(defn- handle-v3-broadcast-event!
"Protocol v3: intercept broadcast events for external tools and permissions.
In v3, tool.call and permission.request server→client RPC methods are replaced
by broadcast events that the SDK handles and responds to via new RPC methods."
[client session-id event]
(let [event-type (:type event)]
(case event-type
:copilot/external_tool.requested
(handle-v3-tool-requested! client session-id event)
:copilot/permission.requested
(handle-v3-permission-requested! client session-id event)
nil)))
(defn- start-notification-router!
"Route notifications to appropriate sessions."
[client]
(let [{:keys [connection-io]} @(:state client)
notif-ch (proto/notifications connection-io)
router-ch (chan 1024)
queue-size (or (:router-queue-size (:options client)) 4096)
router-queue (LinkedBlockingQueue. queue-size)
router-thread (Thread.
(fn []
(log/debug "Notification router dispatcher started")
(try
(loop []
(when (:router-running? @(:state client))
(when-let [notif (.poll router-queue 100 java.util.concurrent.TimeUnit/MILLISECONDS)]
(>!! router-ch notif))
(recur)))
(catch InterruptedException _
(log/debug "Notification router dispatcher interrupted"))
(catch Exception e
(log/error "Notification router dispatcher exception: " (ex-message e)))
(finally
(log/debug "Notification router dispatcher ending")))))]
;; Store the router channel
(swap! (:state client) assoc
:router-ch router-ch
:router-queue router-queue
:router-thread router-thread
:router-running? true)
(.setDaemon router-thread true)
(.setName router-thread "notification-router-dispatcher")
(.start router-thread)
;; Simple routing - read from notification-chan and dispatch
(go-loop []
(if-let [notif (<! notif-ch)]
(do
(case (:method notif)
"session.event"
(let [{:keys [session-id event]} (:params notif)
normalized-event (update event :type util/event-type->keyword)
event-type (:type normalized-event)]
(log/debug "Routing event to session " session-id ": type=" event-type)
;; Validate model selection on session.start
(when (= event-type :copilot/session.start)
(let [selected-model (get-in event [:data :selectedModel])
requested-model (get-in @(:state client) [:sessions session-id :config :model])]
(when (and requested-model selected-model
(not= requested-model selected-model))
(log/warn "Model mismatch for session " session-id
": requested " requested-model ", server selected " selected-model))))
(when-not (:destroyed? (get-in @(:state client) [:sessions session-id]))
(when-let [{:keys [event-chan]} (get-in @(:state client) [:session-io session-id])]
(>! event-chan normalized-event))
;; Protocol v3: handle broadcast events for tools and permissions
(when (>= (negotiated-protocol-version client) 3)
(handle-v3-broadcast-event! client session-id normalized-event))))
"session.lifecycle"
(let [params (util/wire->clj (:params notif))
event-type-str (:type params)
event-type-kw (when event-type-str (keyword event-type-str))
lifecycle-event (-> params
(dissoc :type)
(assoc :lifecycle-event-type event-type-kw))
handlers (vals (:lifecycle-handlers @(:state client)))]
(log/debug "Lifecycle event: " event-type-kw " session=" (:session-id lifecycle-event))
(doseq [{:keys [handler event-type]} handlers]
(when (or (nil? event-type) (= event-type event-type-kw))
(try
(handler lifecycle-event)
(catch Exception e
(log/error "Lifecycle handler error: " (ex-message e)))))))
;; default: other notifications go to the router queue
(when-not (.offer router-queue notif)
(log/debug "Dropping notification due to full router queue")))
(recur))
(do
(log/debug "Notification channel closed")
(maybe-reconnect! client "connection-closed"))))))
(defn notifications
"Get the channel that receives non-session notifications.
Notifications are dropped if the channel is full."
[client]
(:router-ch @(:state client)))
(let [counter (atom 0)]
(defn on-lifecycle-event
"Subscribe to session lifecycle events.
Two arities:
(on-lifecycle-event client handler)
Subscribe to ALL lifecycle events. Handler receives the full event map
with keys :lifecycle-event-type, :session-id, and optionally :metadata.
(on-lifecycle-event client event-type handler)
Subscribe to a specific event type only.
event-type is a keyword like :session.created, :session.deleted, etc.
Returns an unsubscribe function (call with no args to remove the handler)."
([client handler]
(let [id (keyword (str "lh-" (swap! counter inc)))]
(swap! (:state client) assoc-in [:lifecycle-handlers id]
{:handler handler :event-type nil})
(fn [] (swap! (:state client) update :lifecycle-handlers dissoc id))))
([client event-type handler]
(let [id (keyword (str "lh-" (swap! counter inc)))]
(swap! (:state client) assoc-in [:lifecycle-handlers id]
{:handler handler :event-type event-type})
(fn [] (swap! (:state client) update :lifecycle-handlers dissoc id))))))
(defn- mark-restarting!
"Atomically mark the client as restarting. Returns true if this caller won."
[client]
(let [state-atom (:state client)]
(loop []
(let [state @state-atom]
(if (or (:stopping? state) (:restarting? state))
false
(if (compare-and-set! state-atom state (assoc state :restarting? true))
true
(recur)))))))
(defn- maybe-reconnect!
"Attempt a stop/start cycle when auto-restart is enabled."
[client reason]
(let [state @(:state client)]
(when (and (:auto-restart? (:options client))
(= :connected (:status state))
(not (:stopping? state)))
(when (mark-restarting! client)
(log/warn "Auto-restart triggered:" reason)
(async/thread
(try
(stop! client)
(start! client)
(catch Exception e
(log/error "Auto-restart failed: " (ex-message e)))
(finally
(swap! (:state client) assoc :restarting? false))))))))
(defn- watch-process-exit!
"Trigger auto-restart when the managed CLI process exits."
[client mp]
(when-let [exit-ch (:exit-chan mp)]
(go
(when-let [{:keys [exit-code]} (<! exit-ch)]
(let [stopping? (:stopping? @(:state client))]
(if stopping?
(log/debug "CLI process exited with code" exit-code "(expected during stop)")
(log/warn "CLI process exited with code" exit-code))
(maybe-reconnect! client (str "cli-process-exit-" exit-code))
(when stopping?
(swap! (:state client) assoc :stopping? false)))))))
(def ^:private stderr-buffer-max-lines
"Maximum number of stderr lines to retain for error context."
100)
(defn- start-stderr-forwarder!
"Start reading stderr from the CLI process, forwarding lines to logging
and capturing recent output for error context. Returns the stderr buffer atom."
[client mp]
(let [stderr-buf (atom [])
stderr-ch (proc/stderr-reader mp)]
(swap! (:state client) assoc :stderr-buffer stderr-buf)
(go-loop []
(when-let [{:keys [line]} (<! stderr-ch)]
(log/debug "[cli-stderr]" line)
(swap! stderr-buf (fn [buf]
(let [buf (conj buf line)]
(if (> (count buf) stderr-buffer-max-lines)
(subvec buf (- (count buf) stderr-buffer-max-lines))
buf))))
(recur)))
stderr-buf))
(defn- get-stderr-output
"Get captured stderr output as a single string, or nil if empty."
[client]
(when-let [buf (:stderr-buffer @(:state client))]
(let [lines @buf]
(when (seq lines)
(str/join "\n" lines)))))
(defn- setup-request-handler!
"Set up handler for incoming requests (tool calls, permission requests, hooks, user input)."
[client]
(let [{:keys [connection-io]} @(:state client)]
(proto/set-request-handler! connection-io
(fn [method params]
(go
(case method
"tool.call"
(let [{:keys [session-id tool-call-id tool-name arguments]} params]
(if-not (get-in @(:state client) [:sessions session-id])
{:error {:code -32001 :message (str "Unknown session: " session-id)}}
{:result (<! (session/handle-tool-call! client session-id tool-call-id tool-name arguments))}))
"permission.request"
(let [{:keys [session-id permission-request]} params]
(if-not (get-in @(:state client) [:sessions session-id])
{:result {:kind :denied-no-approval-rule-and-could-not-request-from-user}}
(let [result (<! (session/handle-permission-request! client session-id permission-request))]
(log/debug "Permission response for session " session-id ": " result)
{:result result})))
;; User input request (PR #269)
"userInput.request"
(let [{:keys [session-id question choices allow-freeform]} params]
(log/debug "User input request for session " session-id ": " question)
(if-not (get-in @(:state client) [:sessions session-id])
{:error {:code -32001 :message (str "Unknown session: " session-id)}}
(<! (session/handle-user-input-request! client session-id
{:question question
:choices choices
:allow-freeform allow-freeform}))))
;; Hooks invocation (PR #269)
"hooks.invoke"
(let [{:keys [session-id hook-type input]} params]
(if-not (get-in @(:state client) [:sessions session-id])
{:result nil}
(<! (session/handle-hooks-invoke! client session-id hook-type input))))
{:error {:code -32601 :message (str "Unknown method: " method)}}))))))
(defn- connect-stdio!
"Connect via stdio to the CLI process."
[client]
(let [{:keys [process]} @(:state client)]
;; Initialize connection state before connecting
(swap! (:state client) assoc :connection (proto/initial-connection-state))
(let [conn (proto/connect (:stdout process) (:stdin process) (:state client))]
(swap! (:state client) assoc :connection-io conn))))
(defn- non-closing-input-stream
"Wrap an InputStream so that .close is a no-op.
Prevents proto/disconnect from closing System/in."
^java.io.InputStream [^java.io.InputStream in]
(proxy [java.io.FilterInputStream] [in]
(close [] nil)))
(defn- non-closing-output-stream
"Wrap an OutputStream so that .close flushes but does not close.
Prevents proto/disconnect from closing System/out while ensuring
buffered bytes are sent."
^java.io.OutputStream [^java.io.OutputStream out]
(proxy [java.io.FilterOutputStream] [out]
(close [] (.flush ^java.io.OutputStream out))))
(defn- connect-parent-stdio!
"Connect via own stdio to a parent Copilot CLI process (child process mode).
Wraps System/in and System/out in non-closing wrappers so that
proto/disconnect does not close the JVM's global stdio streams."
[client]
(swap! (:state client) assoc :connection (proto/initial-connection-state))
(let [in (non-closing-input-stream System/in)
out (non-closing-output-stream System/out)
conn (proto/connect in out (:state client))]
(swap! (:state client) assoc :connection-io conn)))
(defn- connect-tcp!
"Connect via TCP to the CLI server."
[client]
(let [host (:actual-host client)
{:keys [actual-port]} @(:state client)
socket (proc/connect-tcp host actual-port 10000)]
;; Initialize connection state before connecting
(swap! (:state client) assoc :connection (proto/initial-connection-state))
(let [conn (proto/connect (.getInputStream socket) (.getOutputStream socket) (:state client))]
(swap! (:state client) assoc :socket socket :connection-io conn))))
(defn- verify-protocol-version!
"Verify the server's protocol version matches ours.
Races the ping against process exit to detect early CLI failures."
[client]
(let [{:keys [connection-io process]} @(:state client)
ping-ch (proto/send-request connection-io "ping" {})
exit-ch (:exit-chan process)
timeout-ch (async/timeout 60000)
;; Race: wait for ping result or process exit (whichever comes first)
result (if exit-ch
(let [exit-poll (async/poll! exit-ch)]
(if exit-poll
;; Process already exited before we even sent the ping
(let [stderr (get-stderr-output client)]
(throw (ex-info
(cond-> (str "CLI server exited with code " (:exit-code exit-poll))
stderr (str "\nstderr: " stderr))
{:exit-code (:exit-code exit-poll) :stderr stderr})))
;; Process still running — race ping against exit and timeout
(let [[v ch] (async/alts!! [ping-ch exit-ch timeout-ch])]
(cond
;; Timeout
(identical? ch timeout-ch)
(let [stderr (get-stderr-output client)]
(throw (ex-info
(cond-> "Ping request timed out"
stderr (str "\nstderr: " stderr))
{:method "ping" :timeout-ms 60000 :stderr stderr})))
;; Ping completed
(identical? ch ping-ch)
(cond
(nil? v)
(throw (ex-info "Ping channel closed unexpectedly" {:method "ping"}))
(:error v)
(throw (ex-info (get-in v [:error :message] "RPC error")
{:error (:error v) :method "ping"}))
:else (:result v))
;; Process exited first
:else
(let [stderr (get-stderr-output client)]
(throw (ex-info
(cond-> (str "CLI server exited with code " (:exit-code v))
stderr (str "\nstderr: " stderr))
{:exit-code (:exit-code v) :stderr stderr})))))))
;; No process (external server) — just wait for ping with timeout
(let [[v ch] (async/alts!! [ping-ch timeout-ch])]
(cond
(identical? ch timeout-ch)
(throw (ex-info "Ping request timed out"
{:method "ping" :timeout-ms 60000}))
(nil? v)
(throw (ex-info "Ping channel closed" {:method "ping"}))
(:error v)
(throw (ex-info (get-in v [:error :message] "RPC error")
{:error (:error v) :method "ping"}))
:else (:result v))))
server-version (:protocol-version result)]
(when (nil? server-version)
(throw (ex-info
(str "SDK protocol version mismatch: SDK supports versions "
sdk-protocol-version-min "-" sdk-protocol-version-max
", but server does not report a protocol version.")
{:min sdk-protocol-version-min :max sdk-protocol-version-max :actual nil})))
(when (or (< server-version sdk-protocol-version-min)
(> server-version sdk-protocol-version-max))
(throw (ex-info
(str "SDK protocol version mismatch: SDK supports versions "
sdk-protocol-version-min "-" sdk-protocol-version-max
", but server reports version " server-version)
{:min sdk-protocol-version-min :max sdk-protocol-version-max :actual server-version})))
;; Store the negotiated version for conditional v2/v3 behavior
(swap! (:state client) assoc :negotiated-protocol-version server-version)))
(defn- negotiated-protocol-version
"Get the negotiated protocol version from client state."
[client]
(:negotiated-protocol-version @(:state client) 0))
;; ---------------------------------------------------------------------------
;; Permission helpers
;; ---------------------------------------------------------------------------
(defn approve-all
"Permission handler that approves all permission requests.
The SDK uses a **deny-by-default** permission model: all permission requests
(file writes, shell commands, URL fetches, etc.) are denied unless your
session config provides an `:on-permission-request` handler.
Use `approve-all` to opt into approving everything (equivalent to the
upstream `approveAll` export):
(copilot/create-session client {:on-permission-request copilot/approve-all})
For fine-grained control, provide your own handler function instead."
[_request _ctx]
{:kind :approved})
(defn start!
"Start the CLI server and establish connection.
Blocks until connected or throws on error.
Thread safety: do not call start! and stop! concurrently from different
threads. The :stopping? and :restarting? flags guard against concurrent
auto-restart, but explicit concurrent calls are unsupported."
[client]
(when-not (= :connected (:status @(:state client)))
(log/info "Starting Copilot client...")
(swap! (:state client) assoc :stopping? false :status :connecting)
;; Set log level from options
(when-let [level (:log-level (:options client))]
(log/set-log-level! level))
(try
;; Start CLI process if not connecting to external server
(when-not (:external-server? client)
(log/debug "Spawning CLI process")
(let [opts (:options client)
mp (proc/spawn-cli opts)]
(swap! (:state client) assoc :process mp)
(start-stderr-forwarder! client mp)
(watch-process-exit! client mp)
;; For TCP mode, wait for port announcement
(when-not (:use-stdio? opts)
(let [port (proc/wait-for-port mp 10000)]
(swap! (:state client) assoc :actual-port port)))))
;; Connect to server
(cond
;; Child process mode: use own stdin/stdout to talk to parent
(:is-child-process? (:options client))
(do
(log/debug "Connecting via parent stdio (child process mode)")
(connect-parent-stdio! client))
;; External server (cli-url) or TCP mode
(or (:external-server? client)
(not (:use-stdio? (:options client))))
(do
(log/debug "Connecting via TCP")
(connect-tcp! client))
;; Normal stdio to spawned process
:else
(do
(log/debug "Connecting via stdio")
(connect-stdio! client)))
;; Verify protocol version
(verify-protocol-version! client)
;; Set up notification routing and request handling
(start-notification-router! client)
(setup-request-handler! client)
(swap! (:state client) assoc :status :connected)
(log/info "Copilot client connected")
nil
(catch Exception e
(let [stderr (get-stderr-output client)
msg (cond-> (str "Failed to start client: " (ex-message e))
stderr (str "\nstderr: " stderr))]
(log/error msg)
(swap! (:state client) assoc :status :error)
(throw e))))))
(defn stop!
"Stop the CLI server and close all sessions.
Returns a vector of any errors encountered during cleanup.
Thread safety: do not call start! and stop! concurrently from different
threads. Auto-restart is suppressed via the :stopping? flag, but explicit
concurrent calls are unsupported."
[client]
(log/info "Stopping Copilot client...")
(swap! (:state client) assoc :stopping? true)
(let [errors (atom [])
{:keys [sessions session-io process connection-io socket]} @(:state client)]
(try
;; 0. Stop notification routing
(swap! (:state client) assoc :router-running? false)
(when-let [^Thread router-thread (:router-thread @(:state client))]
(.interrupt router-thread)
(try (.join router-thread 500) (catch Exception _)))
(when-let [router-ch (:router-ch @(:state client))]
(close! router-ch))
(swap! (:state client) assoc :router-ch nil :router-queue nil :router-thread nil)
;; 1. Disconnect all sessions
(doseq [[session-id _] sessions]
(try
(session/disconnect! client session-id)
(catch Exception e
(swap! errors conj
(ex-info (str "Failed to disconnect session " session-id)
{:session-id session-id} e)))))
(swap! (:state client) assoc :sessions {} :session-io {})
;; 2. Close connection (non-blocking, may leave read thread blocked for stdio)
(when connection-io
(try
(proto/disconnect connection-io)
(catch Exception e
(swap! errors conj
(ex-info "Failed to close connection" {} e))))
(swap! (:state client) assoc :connection nil :connection-io nil))
;; 3. Close socket (TCP mode)
(when socket
(try
(.close ^Socket socket)
(catch Exception e
(swap! errors conj
(ex-info "Failed to close socket" {} e))))
(swap! (:state client) assoc :socket nil))
;; 4. Kill CLI process (this also unblocks any stdio read thread)
(when (and (not (:external-server? client)) process)
(try
(proc/destroy! process)
(catch Exception e
(swap! errors conj
(ex-info "Failed to kill CLI process" {} e))))
(swap! (:state client) assoc :process nil))
(swap! (:state client) assoc :status :disconnected :actual-port nil
:models-cache nil :lifecycle-handlers {}
:stderr-buffer nil) ; reset caches, handlers, and stderr
(log/info "Copilot client stopped")
@errors)))
(defn force-stop!
"Force stop the CLI server without graceful cleanup."
[client]
(swap! (:state client) assoc :force-stopping? true :stopping? true)
(let [{:keys [connection-io socket process]} @(:state client)]
(try
;; Clear sessions without destroying
(swap! (:state client) assoc :sessions {} :session-io {})
;; Stop notification routing
(swap! (:state client) assoc :router-running? false)
(when-let [^Thread router-thread (:router-thread @(:state client))]
(.interrupt router-thread)
(try (.join router-thread 500) (catch Exception _)))
(when-let [router-ch (:router-ch @(:state client))]
(close! router-ch))
(swap! (:state client) assoc :router-ch nil :router-queue nil :router-thread nil)
;; Force close connection
(when connection-io
(try (proto/disconnect connection-io) (catch Exception _)))
;; Force close socket
(when socket
(try (.close ^Socket socket) (catch Exception _)))
;; Force kill process
(when (and (not (:external-server? client)) process)
(try (proc/destroy-forcibly! process) (catch Exception _)))
(finally
nil)))
(swap! (:state client) merge
{:status :disconnected
:connection nil
:connection-io nil
:socket nil
:process nil
:actual-port nil
:router-ch nil
:router-queue nil
:router-thread nil
:router-running? false
:force-stopping? false
:models-cache nil
:lifecycle-handlers {}
:stderr-buffer nil}) ; reset caches, handlers, and stderr
nil)
(defn- ensure-connected!
"Ensure client is connected, auto-starting if configured."
[client]
(when-not (= :connected (:status @(:state client)))
(if (:auto-start? (:options client))
(start! client)
(throw (ex-info "Client not connected. Call start! first." {})))))
(defn ping
"Ping the server to check connectivity.
Returns {:message :timestamp :protocol-version}."
([client]
(ping client nil))
([client message]
(ensure-connected! client)
(let [{:keys [connection-io]} @(:state client)
result (proto/send-request! connection-io "ping" {:message message})]
{:message (:message result)
:timestamp (:timestamp result)
:protocol-version (:protocol-version result)})))
(defn get-status
"Get CLI status including version and protocol information.
Returns {:version :protocol-version}."
[client]
(ensure-connected! client)
(let [{:keys [connection-io]} @(:state client)
result (proto/send-request! connection-io "status.get" {})]
{:version (:version result)
:protocol-version (:protocol-version result)}))
(defn get-auth-status
"Get current authentication status.
Returns {:authenticated? :auth-type :host :login :status-message}."
[client]
(ensure-connected! client)
(let [{:keys [connection-io]} @(:state client)
result (proto/send-request! connection-io "auth.getStatus" {})]
{:authenticated? (:is-authenticated result)
:auth-type (some-> (:auth-type result) keyword)
:host (:host result)
:login (:login result)
:status-message (:status-message result)}))
(defn- parse-model-info
"Parse a model info map from wire format to Clojure format."
[m]
(let [base {:id (:id m)
:name (:name m)
:vendor (:vendor m)
:family (:family m)
:version (:version m)
:max-input-tokens (:max-input-tokens m)
:max-output-tokens (:max-output-tokens m)
:preview? (:preview m)}
caps (when-let [c (:capabilities m)]
{:model-capabilities
(cond-> {}
(:supports c)
(assoc :model-supports
(cond-> {}
(contains? (:supports c) :vision)
(assoc :supports-vision (:vision (:supports c)))
(contains? (:supports c) :reasoning-effort)
(assoc :supports-reasoning-effort (:reasoning-effort (:supports c)))))
(:limits c)
(assoc :model-limits
(cond-> {}
(:max-prompt-tokens (:limits c))
(assoc :max-prompt-tokens (:max-prompt-tokens (:limits c)))
(:max-context-window-tokens (:limits c))
(assoc :max-context-window-tokens (:max-context-window-tokens (:limits c)))
(:vision (:limits c))
(assoc :vision-capabilities
(select-keys (:vision (:limits c))
[:supported-media-types :max-prompt-images :max-prompt-image-size])))))})
optional (merge
(select-keys m [:default-temperature
:model-picker-priority
:default-reasoning-effort])
(when (contains? m :policy)
(let [mp (:policy m)]
(cond
(map? mp)
{:model-policy mp}
(or (string? mp) (keyword? mp) (symbol? mp))
{:model-policy {:policy-state (name mp)}}
:else
(do
(log/warn "Unexpected model policy value for model "
(or (:id m) (:name m) "<unknown>")
": " (pr-str mp))
nil))))
(when (contains? m :supported-reasoning-efforts)
{:supported-reasoning-efforts (vec (:supported-reasoning-efforts m))})
(when (contains? m :vision-limits)
{:vision-limits (select-keys (:vision-limits m)
[:supported-media-types
:max-prompt-images
:max-prompt-image-size])})
;; Legacy flat key for backward compat
(when (contains? (get-in m [:capabilities :supports] {}) :reasoning-effort)
{:supports-reasoning-effort (get-in m [:capabilities :supports :reasoning-effort])})
(when-let [b (:billing m)]
{:model-billing b})
caps)]
(merge base optional)))
(defn- fetch-models!
"Fetch models from the server (no caching)."
[client]
(let [{:keys [connection-io]} @(:state client)
result (proto/send-request! connection-io "models.list" {})
models (:models result)]
(mapv parse-model-info models)))
(defn list-models
"List available models with their metadata.
Results are cached per client connection to prevent rate limiting under concurrency.
Cache is cleared on stop!/force-stop!.
When :on-list-models handler is provided in client options, calls the handler
instead of the RPC method. The handler does not require a CLI connection.
Requires authentication (unless :on-list-models handler is provided).
Returns a vector of model info maps with keys:
:id :name :vendor :family :version :max-input-tokens :max-output-tokens
:preview? :default-temperature :model-picker-priority
:model-capabilities {:model-supports {:supports-vision :supports-reasoning-effort}
:model-limits {:max-prompt-tokens :max-context-window-tokens
:vision-capabilities {:supported-media-types
:max-prompt-images
:max-prompt-image-size}}}
:model-policy {:policy-state :terms}
:model-billing {:multiplier}
:supported-reasoning-efforts :default-reasoning-effort
:supports-reasoning-effort (legacy flat key)
:vision-limits {:supported-media-types :max-prompt-images :max-prompt-image-size} (legacy)"
[client]
(let [handler (:on-list-models client)]
(when-not handler (ensure-connected! client))
(let [p (promise)
entry (swap! (:state client) update :models-cache #(or % p))
cached (:models-cache entry)]