-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession.clj
More file actions
741 lines (656 loc) · 30.9 KB
/
session.clj
File metadata and controls
741 lines (656 loc) · 30.9 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
(ns github.copilot-sdk.session
"CopilotSession - session operations using centralized client state.
All session state is stored in the client's :state atom under:
- [:sessions session-id] -> {:tool-handlers {} :permission-handler nil :destroyed? false :workspace-path nil}
- [:session-io session-id] -> {:event-chan :event-mult}
Functions take client + session-id, accessing state through the client."
(:require [clojure.core.async :as async :refer [go go-loop <! >! >!! <!! chan close! put! alts!! mult tap untap]]
[clojure.core.async.impl.channels :as channels]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[github.copilot-sdk.protocol :as proto]
[github.copilot-sdk.logging :as log]
[github.copilot-sdk.specs :as specs]
[github.copilot-sdk.util :as util]))
;; -----------------------------------------------------------------------------
;; State accessors - all state lives in client's atom
;; -----------------------------------------------------------------------------
(defn- session-state [client session-id]
(get-in @(:state client) [:sessions session-id]))
(defn- session-io [client session-id]
(get-in @(:state client) [:session-io session-id]))
(defn- update-session! [client session-id f & args]
(apply swap! (:state client) update-in [:sessions session-id] f args))
(defn- connection-io [client]
(:connection-io @(:state client)))
;; -----------------------------------------------------------------------------
;; Session record - lightweight handle returned to users
;; Contains only immutable data + reference to client
;; -----------------------------------------------------------------------------
(defrecord CopilotSession
[session-id
workspace-path
client]) ; reference to owning client
;; -----------------------------------------------------------------------------
;; Internal functions
;; -----------------------------------------------------------------------------
(defn create-session
"Create a new session. Internal use - called by client.
Initializes session state in client's atom and returns a CopilotSession handle."
[client session-id {:keys [tools on-permission-request on-user-input-request hooks workspace-path config]}]
(log/debug "Creating session: " session-id)
(let [event-chan (chan (async/sliding-buffer 4096))
event-mult (mult event-chan)
send-lock (doto (chan 1) (>!! :token))
tool-handlers (into {} (map (fn [t] [(:tool-name t) (:tool-handler t)]) tools))]
;; Store session state and IO in client's atom
(swap! (:state client)
(fn [state]
(-> state
(assoc-in [:sessions session-id]
{:tool-handlers tool-handlers
:permission-handler on-permission-request
:user-input-handler on-user-input-request
:hooks hooks
:destroyed? false
:workspace-path workspace-path
:config config})
(assoc-in [:session-io session-id]
{:event-chan event-chan
:event-mult event-mult
:send-lock send-lock}))))
(log/debug "Session created: " session-id)
;; Return lightweight handle
(->CopilotSession session-id workspace-path client)))
(defn dispatch-event!
"Dispatch an event to all subscribers via the mult. Called by client notification router.
Events are dropped (with warning) if the session event buffer is full."
[client session-id event]
(let [normalized-event (update event :type util/event-type->keyword)]
(log/debug "Dispatching event to session " session-id ": type=" (:type normalized-event))
(when-not (:destroyed? (session-state client session-id))
(when-let [{:keys [event-chan]} (session-io client session-id)]
(when-not (async/offer! event-chan normalized-event)
(log/warn "Dropping event for session " session-id
" type=" (:type normalized-event) " (event buffer full)"))))))
(defn- normalize-tool-result
"Normalize a tool result to the wire format."
[result]
(cond
(nil? result)
{:text-result-for-llm "Tool returned no result"
:result-type "failure"
:error "tool returned no result"
:tool-telemetry {}}
;; Already a result object (duck-type check)
(and (map? result) (:text-result-for-llm result) (:result-type result))
result
;; Backward compatibility for camelCase result maps
(and (map? result) (:textResultForLlm result) (:resultType result))
(util/wire->clj result)
;; String result
(string? result)
{:text-result-for-llm result
:result-type "success"
:tool-telemetry {}}
;; Any other value - JSON encode
:else
{:text-result-for-llm (json/write-str result)
:result-type "success"
:tool-telemetry {}}))
(defn- channel?
"Check if x is a core.async channel."
[x]
(instance? clojure.core.async.impl.channels.ManyToManyChannel x))
(defn handle-tool-call!
"Handle an incoming tool call request. Returns a channel with the result wrapper."
[client session-id tool-call-id tool-name arguments]
(async/thread-call
(fn []
(let [handler (get-in (session-state client session-id) [:tool-handlers tool-name])
timeout-ms (or (:tool-timeout-ms (:options client)) 120000)]
(if-not handler
{:result {:text-result-for-llm (str "Tool '" tool-name "' is not supported by this client instance.")
:result-type "failure"
:error (str "tool '" tool-name "' not supported")
:tool-telemetry {}}}
(try
(let [invocation {:session-id session-id
:tool-call-id tool-call-id
:tool-name tool-name
:arguments arguments}
result (handler arguments invocation)
result (if (channel? result)
(let [timeout-ch (async/timeout timeout-ms)
[value ch] (alts!! [result timeout-ch])]
(if (= ch timeout-ch)
(throw (ex-info "Tool timeout" {:timeout-ms timeout-ms
:tool-name tool-name
:tool-call-id tool-call-id}))
value))
result)]
{:result (normalize-tool-result result)})
(catch Exception e
{:result {:text-result-for-llm "Invoking this tool produced an error. Detailed information is not available."
:result-type "failure"
:error (ex-message e)
:tool-telemetry {}}})))))
:mixed))
(defn handle-permission-request!
"Handle an incoming permission request. Returns a channel with the result."
[client session-id request]
(async/thread-call
(fn []
(let [handler (:permission-handler (session-state client session-id))]
(if-not handler
{:result {:kind :denied-no-approval-rule-and-could-not-request-from-user}}
(try
(let [result (handler request {:session-id session-id})
;; If handler returns a channel, await it
result (if (channel? result)
(<!! result)
result)]
(cond
(and (map? result) (contains? result :kind))
{:result result}
(and (map? result) (contains? result :result)
(map? (:result result)) (contains? (:result result) :kind))
result
:else
(do
(log/warn "Invalid permission response for session " session-id ": " result)
{:result {:kind :denied-no-approval-rule-and-could-not-request-from-user}})))
(catch Exception e
(log/error "Permission handler error for session " session-id ": " (ex-message e))
{:result {:kind :denied-no-approval-rule-and-could-not-request-from-user}})))))
:io))
(defn handle-user-input-request!
"Handle an incoming user input request (ask_user). Returns a channel with the result.
PR #269 feature.
The handler should return a map with :answer (string) and optionally :was-freeform (boolean).
For backwards compatibility, :response is also accepted as an alias for :answer."
[client session-id request]
(async/thread-call
(fn []
(let [handler (:user-input-handler (session-state client session-id))]
(if-not handler
{:error {:code -32001 :message "User input requested but no handler registered"}}
(try
(let [result (handler request {:session-id session-id})
;; If handler returns a channel, await it
result (if (channel? result)
(<!! result)
result)
;; Normalize result to expected wire format
;; Accept :answer or :response, default was-freeform to true if not specified
answer (or (:answer result) (:response result))
was-freeform (if (contains? result :was-freeform)
(:was-freeform result)
true)]
(if (and (string? answer) (not (empty? answer)))
{:result {:answer answer :was-freeform was-freeform}}
(do
(log/warn "Invalid user input response for session " session-id ": " result)
{:error {:code -32001 :message "User input handler returned invalid answer"}})))
(catch Exception e
(log/error "User input handler error for session " session-id ": " (ex-message e))
{:error {:code -32001 :message (str "User input handler error: " (ex-message e))}})))))
:io))
(defn handle-hooks-invoke!
"Handle an incoming hooks invocation. Returns a channel with the result.
PR #269 feature."
[client session-id hook-type input]
(async/thread-call
(fn []
(let [hooks (:hooks (session-state client session-id))]
(if-not hooks
{:result nil}
(let [;; Map hook type strings to handler keywords
handler-key (case hook-type
"preToolUse" :on-pre-tool-use
"postToolUse" :on-post-tool-use
"userPromptSubmitted" :on-user-prompt-submitted
"sessionStart" :on-session-start
"sessionEnd" :on-session-end
"errorOccurred" :on-error-occurred
nil)
handler (when handler-key (get hooks handler-key))]
(if-not handler
{:result nil}
(try
(let [result (handler input {:session-id session-id})
;; If handler returns a channel, await it
result (if (channel? result)
(<!! result)
result)]
{:result result})
(catch Exception e
(log/error "Hook handler error for session " session-id ", hook " hook-type ": " (ex-message e))
{:result nil})))))))
:io))
;; -----------------------------------------------------------------------------
;; Public API - functions that take CopilotSession handle
;; -----------------------------------------------------------------------------
(defn config
"Get the session configuration that was used to create this session.
Returns the user-provided config. Note: This reflects what was requested,
not necessarily what the server is using. The session.start event contains
the actual selectedModel if validation is needed."
[session]
(let [{:keys [session-id client]} session]
(:config (session-state client session-id))))
(defn send!
"Send a message to the session.
Returns the message ID immediately (fire-and-forget).
Options:
- :prompt - The message text (required)
- :attachments - Vector of attachments (file/directory/selection)
- :mode - :enqueue (default) or :immediate"
[session opts]
(when-not (s/valid? ::specs/send-options opts)
(throw (ex-info "Invalid send options"
{:opts opts
:explain (s/explain-data ::specs/send-options opts)})))
(let [{:keys [session-id client]} session]
(log/debug "send! called for session " session-id " with prompt: " (subs (str (:prompt opts)) 0 (min 50 (count (str (:prompt opts))))) "...")
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [conn (connection-io client)
wire-attachments (when (:attachments opts)
(util/attachments->wire (:attachments opts)))
params (cond-> {:session-id session-id
:prompt (:prompt opts)}
wire-attachments (assoc :attachments wire-attachments)
(:mode opts) (assoc :mode (name (:mode opts))))
result (proto/send-request! conn "session.send" params)
msg-id (:message-id result)]
(log/debug "send! completed for session " session-id " message-id=" msg-id)
msg-id)))
(defn send-and-wait!
"Send a message and wait until the session becomes idle.
Returns the final assistant message event, or nil if none received.
Serialized per session to avoid mixing concurrent sends.
Options: same as send!
Additional options:
- :timeout-ms - Timeout in milliseconds (default: 300000)"
([session opts]
(send-and-wait! session opts 300000))
([session opts timeout-ms]
(let [{:keys [session-id client]} session]
(log/debug "send-and-wait! called for session " session-id)
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [event-ch (chan 1024)
last-assistant-msg (atom nil)
{:keys [event-mult send-lock]} (session-io client session-id)]
;; Acquire channel-based lock (blocks calling thread)
(<!! send-lock)
(try
;; Tap the mult BEFORE sending - ensures we don't miss events
(log/debug "send-and-wait! tapping event mult for session " session-id)
(tap event-mult event-ch)
;; Send the message
(log/debug "send-and-wait! sending message")
(send! session opts)
;; Wait for events with single deadline timeout
(log/debug "send-and-wait! waiting for result with timeout " timeout-ms "ms")
(let [deadline-ch (async/timeout timeout-ms)]
(loop []
(let [[event ch] (alts!! [event-ch deadline-ch])]
(cond
(= ch deadline-ch)
(do
(log/error "send-and-wait! timeout after " timeout-ms "ms for session " session-id)
(throw (ex-info (str "Timeout after " timeout-ms "ms waiting for session.idle")
{:timeout-ms timeout-ms})))
(nil? event)
(do
(log/debug "send-and-wait! event channel closed for session " session-id)
(throw (ex-info "Event channel closed unexpectedly" {})))
(= :copilot/assistant.message (:type event))
(do
(log/debug "send-and-wait! got assistant.message, continuing to wait for idle")
(reset! last-assistant-msg event)
(recur))
(= :copilot/session.idle (:type event))
(do
(log/debug "send-and-wait! got session.idle, returning result for session " session-id)
@last-assistant-msg)
(= :copilot/session.error (:type event))
(do
(log/error "send-and-wait! got session.error for session " session-id)
(throw (ex-info (get-in event [:data :message] "Session error")
{:event event})))
:else
(do
(log/debug "send-and-wait! ignoring event type: " (:type event))
(recur))))))
(finally
(log/debug "send-and-wait! cleaning up subscription")
(untap event-mult event-ch)
(close! event-ch)
(put! send-lock :token)))))))
(defn- send-async*
"Send a message and return {:message-id :events-ch}."
([session opts]
(send-async* session opts nil))
([session opts timeout-ms]
(let [{:keys [session-id client]} session]
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [out-ch (chan 1024)
event-ch (chan 1024)
{:keys [event-mult send-lock]} (session-io client session-id)
released? (atom false)
release-lock! (fn []
(when (compare-and-set! released? false true)
(put! send-lock :token)))
deadline-ch (when timeout-ms (async/timeout timeout-ms))
timeout-event {:type :copilot/session.error
:data {:message (str "Timeout after " timeout-ms "ms waiting for session.idle")
:timeout-ms timeout-ms}}
emit! (fn [event]
(when-not (async/offer! out-ch event)
(log/debug "Dropping event for session " session-id " due to full async buffer")))]
;; Acquire channel-based lock (blocks calling thread)
(<!! send-lock)
;; Tap the mult for events, then send
(try
(tap event-mult event-ch)
(let [message-id (send! session opts)]
(go-loop []
(let [[event ch] (if deadline-ch
(async/alts! [event-ch deadline-ch])
[(<! event-ch) event-ch])]
(cond
(and deadline-ch (= ch deadline-ch))
(do
(emit! timeout-event)
(untap event-mult event-ch)
(close! event-ch)
(close! out-ch)
(release-lock!))
(nil? event)
(do
(untap event-mult event-ch)
(close! out-ch)
(release-lock!))
(= :copilot/session.idle (:type event))
(do
(emit! event)
(untap event-mult event-ch)
(close! event-ch)
(close! out-ch)
(release-lock!))
(= :copilot/session.error (:type event))
(do
(emit! event)
(untap event-mult event-ch)
(close! event-ch)
(close! out-ch)
(release-lock!))
:else
(do
(emit! event)
(recur)))))
{:message-id message-id
:events-ch out-ch})
(catch Exception e
(untap event-mult event-ch)
(close! event-ch)
(close! out-ch)
(release-lock!)
(throw e)))))))
(defn- <send-async*
"Fully non-blocking send pipeline for use in go blocks.
Acquires lock, sends message, and processes events — all via parking channel ops.
Returns events-ch immediately; events flow once the go block completes setup."
[session opts timeout-ms]
(let [{:keys [session-id client]} session]
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [out-ch (chan 1024)
event-ch (chan 1024)
{:keys [event-mult send-lock]} (session-io client session-id)
released? (atom false)
release-lock! (fn []
(when (compare-and-set! released? false true)
(put! send-lock :token)))
deadline-ch (when timeout-ms (async/timeout timeout-ms))
timeout-event {:type :copilot/session.error
:data {:message (str "Timeout after " timeout-ms "ms waiting for session.idle")
:timeout-ms timeout-ms}}
emit! (fn [event]
(when-not (async/offer! out-ch event)
(log/debug "Dropping event for session " session-id " due to full async buffer")))
cleanup! (fn []
(untap event-mult event-ch)
(close! event-ch)
(close! out-ch)
(release-lock!))]
(go
(if-not (<! send-lock) ;; park for lock (nil = channel closed)
(do (close! event-ch) (close! out-ch))
(try
(tap event-mult event-ch)
;; Send message via channel-based RPC (no blocking)
(let [conn (connection-io client)
wire-attachments (when (:attachments opts)
(util/attachments->wire (:attachments opts)))
params (cond-> {:session-id session-id
:prompt (:prompt opts)}
wire-attachments (assoc :attachments wire-attachments)
(:mode opts) (assoc :mode (name (:mode opts))))
response-ch (proto/send-request conn "session.send" params)
[result port] (if deadline-ch
(async/alts! [response-ch deadline-ch])
[(<! response-ch) response-ch])]
(cond
;; Timeout during send
(and deadline-ch (= port deadline-ch))
(do (emit! timeout-event) (cleanup!))
;; RPC error or channel closed
(or (nil? result) (:error result))
(do
(when (:error result)
(log/error "Async send RPC error: " (get-in result [:error :message])))
(cleanup!))
;; Success — process events
:else
(loop []
(let [[event ch] (if deadline-ch
(async/alts! [event-ch deadline-ch])
[(<! event-ch) event-ch])]
(cond
(and deadline-ch (= ch deadline-ch))
(do (emit! timeout-event) (cleanup!))
(nil? event)
(do (untap event-mult event-ch) (close! out-ch) (release-lock!))
(#{:copilot/session.idle :copilot/session.error} (:type event))
(do (emit! event) (cleanup!))
:else
(do (emit! event) (recur)))))))
(catch Exception e
(log/error "<send-async* error for session " session-id ": " (ex-message e))
(cleanup!)))))
out-ch)))
(defn send-async
"Send a message and return a channel that receives events until session.idle.
The channel closes after session.idle or session.error.
Serialized per session to avoid mixing concurrent sends.
Safe for use inside go blocks — no blocking operations.
Options:
- :timeout-ms - Timeout in milliseconds (default: 300000, set to nil to disable)"
[session opts]
(let [timeout-ms (if (contains? opts :timeout-ms) (:timeout-ms opts) 300000)
opts (dissoc opts :timeout-ms)]
(<send-async* session opts timeout-ms)))
(defn <send!
"Send a message and return a channel that delivers the final content string.
This is the async equivalent of send-and-wait! - use inside go blocks.
Options:
- :timeout-ms - Timeout in milliseconds (default: 300000, set to nil to disable)
The returned channel delivers a single value (the response content) then closes."
[session opts]
(let [timeout-ms (if (contains? opts :timeout-ms) (:timeout-ms opts) 300000)
events-ch (send-async session (assoc opts :timeout-ms timeout-ms))
out-ch (chan (async/sliding-buffer 1))]
(go
(loop [last-content nil]
(when-let [event (<! events-ch)]
(cond
(= :copilot/assistant.message (:type event))
(recur (get-in event [:data :content]))
(#{:copilot/session.idle :copilot/session.error} (:type event))
(when last-content
(async/offer! out-ch last-content))
:else
(recur last-content))))
(close! out-ch))
out-ch))
(defn send-async-with-id
"Send a message and return {:message-id :events-ch}."
[session opts]
(let [timeout-ms (if (contains? opts :timeout-ms) (:timeout-ms opts) 300000)
opts (dissoc opts :timeout-ms)]
(send-async* session opts timeout-ms)))
(defn abort!
"Abort the currently processing message in this session."
[session]
(let [{:keys [session-id client]} session]
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [conn (connection-io client)]
(proto/send-request! conn "session.abort" {:session-id session-id})
nil)))
(defn get-messages
"Get all events/messages from this session's history."
[session]
(let [{:keys [session-id client]} session]
(when (:destroyed? (session-state client session-id))
(throw (ex-info "Session has been destroyed" {:session-id session-id})))
(let [conn (connection-io client)
result (proto/send-request! conn "session.getMessages" {:session-id session-id})]
(mapv #(update % :type util/event-type->keyword) (:events result)))))
(defn disconnect!
"Disconnect the session and free resources.
Session data on disk is preserved for later resumption via resume-session.
Can be called with either a CopilotSession handle or (client, session-id).
This is the preferred way to close a session. Use delete-session! in
client to permanently remove session data from disk."
([session]
(disconnect! (:client session) (:session-id session)))
([client session-id]
(log/debug "Disconnecting session: " session-id)
(when-not (:destroyed? (session-state client session-id))
(let [conn (connection-io client)]
;; Try to notify server, but don't block forever if connection is broken
(try
(proto/send-request! conn "session.destroy" {:session-id session-id} 5000)
(catch Exception _
;; Ignore errors - we're cleaning up anyway
nil))
;; Atomically update state
(update-session! client session-id assoc
:destroyed? true
:tool-handlers {}
:permission-handler nil)
;; Close the event source channel - this propagates to all tapped channels
(when-let [{:keys [event-chan]} (session-io client session-id)]
(close! event-chan))
(log/debug "Session disconnected: " session-id)
nil))))
(defn destroy!
"Destroy the session and free resources.
Can be called with either a CopilotSession handle or (client, session-id).
Deprecated: Use disconnect! instead. This function will be removed in a
future release. disconnect! is the preferred method for closing sessions."
([session]
(disconnect! session))
([client session-id]
(disconnect! client session-id)))
(defn events
"Get the event mult for this session. Use tap to subscribe:
(let [ch (chan 100)]
(tap (events session) ch)
(go-loop []
(when-let [event (<! ch)]
(println event)
(recur))))
Remember to untap and close your channel when done."
[session]
(let [{:keys [session-id client]} session]
(:event-mult (session-io client session-id))))
(defn subscribe-events
"Subscribe to session events. Returns a channel that receives events.
The channel will receive nil (close) when the session is destroyed.
For explicit cleanup before session destruction, call unsubscribe-events.
Drop behavior: If this subscriber's channel buffer is full when mult tries
to deliver an event, that specific event is silently dropped for this
subscriber only. Other subscribers with available buffer space still receive
the event. The returned channel has a buffer of 1024 events which should be
sufficient for most use cases.
This is a convenience wrapper around (tap (events session) ch)."
[session]
(let [ch (chan 1024)
{:keys [session-id client]} session
{:keys [event-mult]} (session-io client session-id)]
(tap event-mult ch)
ch))
(defn events->chan
"Subscribe to session events with options.
Options:
- :buffer - Channel buffer size (default 1024)
- :xf - Transducer applied to events
Drop behavior: If this subscriber's channel buffer is full when mult tries
to deliver an event, that specific event is silently dropped for this
subscriber only. Other subscribers with available buffer space still receive
the event."
([session]
(events->chan session {}))
([session {:keys [buffer xf] :or {buffer 1024}}]
(let [{:keys [session-id client]} session
{:keys [event-mult]} (session-io client session-id)
ch (if xf (chan buffer xf) (chan buffer))]
(tap event-mult ch)
ch)))
(defn unsubscribe-events
"Unsubscribe a channel from session events."
[session ch]
(let [{:keys [session-id client]} session
{:keys [event-mult]} (session-io client session-id)]
(untap event-mult ch)
(close! ch)))
(defn session-id
"Get the session ID."
[session]
(:session-id session))
(defn workspace-path
"Get the session workspace path when provided by the CLI."
[session]
(:workspace-path session))
(defn get-current-model
"Get the current model for this session.
Returns the model ID string, or nil if none set."
[session]
(let [{:keys [session-id client]} session
conn (connection-io client)
result (proto/send-request! conn "session.model.getCurrent"
{:sessionId session-id})]
(:model-id result)))
(defn switch-model!
"Switch the model for this session.
The new model takes effect for the next message. Conversation history is preserved.
Returns the new model ID string, or nil."
[session model-id]
(let [{:keys [session-id client]} session
conn (connection-io client)
result (proto/send-request! conn "session.model.switchTo"
{:sessionId session-id
:modelId model-id})]
(:model-id result)))
(defn set-model!
"Alias for switch-model!. Matches the upstream SDK's setModel() API.
See switch-model! for details."
[session model-id]
(switch-model! session model-id))