llm-worker 0.2.1

A library for building autonomous LLM-powered systems
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};

use futures::StreamExt;
use tokio::sync::mpsc;
use tracing::{debug, info, trace, warn};

use crate::{
    ContentPart, Message, MessageContent, Role,
    hook::{
        Hook, HookError, HookRegistry, OnAbort, OnPromptSubmit, OnPromptSubmitResult, OnTurnEnd,
        OnTurnEndResult, PostToolCall, PostToolCallContext, PostToolCallResult, PreLlmRequest,
        PreLlmRequestResult, PreToolCall, PreToolCallResult, ToolCall, ToolCallContext, ToolResult,
    },
    llm_client::{
        ClientError, ConfigWarning, LlmClient, Request, RequestConfig,
        ToolDefinition as LlmToolDefinition,
    },
    state::{CacheLocked, Mutable, WorkerState},
    subscriber::{
        ErrorSubscriberAdapter, StatusSubscriberAdapter, TextBlockSubscriberAdapter,
        ToolUseBlockSubscriberAdapter, UsageSubscriberAdapter, WorkerSubscriber,
    },
    timeline::{TextBlockCollector, Timeline, ToolCallCollector},
    tool::{Tool, ToolDefinition, ToolError, ToolMeta},
};

// =============================================================================
// Worker Error
// =============================================================================

/// Workerエラー
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
    /// クライアントエラー
    #[error("Client error: {0}")]
    Client(#[from] ClientError),
    /// ツールエラー
    #[error("Tool error: {0}")]
    Tool(#[from] ToolError),
    /// Hookエラー
    #[error("Hook error: {0}")]
    Hook(#[from] HookError),
    /// 処理が中断された
    #[error("Aborted: {0}")]
    Aborted(String),
    /// Cancellation Tokenによって中断された
    #[error("Cancelled")]
    Cancelled,
    /// 設定に関する警告(未サポートのオプション)
    #[error("Config warnings: {}", .0.iter().map(|w| w.to_string()).collect::<Vec<_>>().join(", "))]
    ConfigWarnings(Vec<ConfigWarning>),
}

/// ツール登録エラー
#[derive(Debug, thiserror::Error)]
pub enum ToolRegistryError {
    /// 同名のツールが既に登録されている
    #[error("Tool with name '{0}' already registered")]
    DuplicateName(String),
}

// =============================================================================
// Worker Config
// =============================================================================

/// Worker設定
#[derive(Debug, Clone, Default)]
pub struct WorkerConfig {
    // 将来の拡張用(現在は空)
    _private: (),
}

// =============================================================================
// Worker Result Types
// =============================================================================

/// Workerの実行結果(ステータス)
#[derive(Debug)]
pub enum WorkerResult {
    /// 完了(ユーザー入力待ち状態)
    Finished,
    /// 一時停止(再開可能)
    Paused,
}

/// 内部用: ツール実行結果
enum ToolExecutionResult {
    Completed(Vec<ToolResult>),
    Paused,
}

// =============================================================================
// ターン制御用コールバック保持
// =============================================================================

/// ターンイベントを通知するためのコールバック (型消去)
trait TurnNotifier: Send + Sync {
    fn on_turn_start(&self, turn: usize);
    fn on_turn_end(&self, turn: usize);
}

struct SubscriberTurnNotifier<S: WorkerSubscriber + 'static> {
    subscriber: Arc<Mutex<S>>,
}

impl<S: WorkerSubscriber + 'static> TurnNotifier for SubscriberTurnNotifier<S> {
    fn on_turn_start(&self, turn: usize) {
        if let Ok(mut s) = self.subscriber.lock() {
            s.on_turn_start(turn);
        }
    }

    fn on_turn_end(&self, turn: usize) {
        if let Ok(mut s) = self.subscriber.lock() {
            s.on_turn_end(turn);
        }
    }
}

// =============================================================================
// Worker
// =============================================================================

/// LLMとの対話を管理する中心コンポーネント
///
/// ユーザーからの入力を受け取り、LLMにリクエストを送信し、
/// ツール呼び出しがあれば自動的に実行してターンを進行させます。
///
/// # 状態遷移(Type-state)
///
/// - [`Mutable`]: 初期状態。システムプロンプトや履歴を自由に編集可能。
/// - [`CacheLocked`]: キャッシュ保護状態。`lock()`で遷移。前方コンテキストは不変。
///
/// # Examples
///
/// ```ignore
/// use llm_worker::{Worker, Message};
///
/// // Workerを作成してツールを登録
/// let mut worker = Worker::new(client)
///     .system_prompt("You are a helpful assistant.");
/// worker.register_tool(my_tool);
///
/// // 対話を実行
/// let history = worker.run("Hello!").await?;
/// ```
///
/// # キャッシュ保護が必要な場合
///
/// ```ignore
/// let mut worker = Worker::new(client)
///     .system_prompt("...");
///
/// // 履歴を設定後、ロックしてキャッシュを保護
/// let mut locked = worker.lock();
/// locked.run("user input").await?;
/// ```
pub struct Worker<C: LlmClient, S: WorkerState = Mutable> {
    /// LLMクライアント
    client: C,
    /// イベントタイムライン
    timeline: Timeline,
    /// テキストブロックコレクター(Timeline用ハンドラ)
    text_block_collector: TextBlockCollector,
    /// ツールコールコレクター(Timeline用ハンドラ)
    tool_call_collector: ToolCallCollector,
    /// 登録されたツール (meta, instance)
    tools: HashMap<String, (ToolMeta, Arc<dyn Tool>)>,
    /// Hook レジストリ
    hooks: HookRegistry,
    /// システムプロンプト
    system_prompt: Option<String>,
    /// メッセージ履歴(Workerが所有)
    history: Vec<Message>,
    /// ロック時点での履歴長(CacheLocked状態でのみ意味を持つ)
    locked_prefix_len: usize,
    /// ターンカウント
    turn_count: usize,
    /// ターン通知用のコールバック
    turn_notifiers: Vec<Box<dyn TurnNotifier>>,
    /// リクエスト設定(max_tokens, temperature等)
    request_config: RequestConfig,
    /// 前回の実行が中断されたかどうか
    last_run_interrupted: bool,
    /// キャンセル通知用チャネル(実行中断用)
    cancel_tx: mpsc::Sender<()>,
    cancel_rx: mpsc::Receiver<()>,
    /// 状態マーカー
    _state: PhantomData<S>,
}

// =============================================================================
// 共通実装(全状態で利用可能)
// =============================================================================

impl<C: LlmClient, S: WorkerState> Worker<C, S> {
    fn reset_interruption_state(&mut self) {
        self.last_run_interrupted = false;
    }

    /// ターンを実行
    ///
    /// 新しいユーザーメッセージを履歴に追加し、LLMにリクエストを送信する。
    /// ツール呼び出しがある場合は自動的にループする。
    pub async fn run(
        &mut self,
        user_input: impl Into<String>,
    ) -> Result<WorkerResult, WorkerError> {
        self.reset_interruption_state();
        // Hook: on_prompt_submit
        let mut user_message = Message::user(user_input);
        let result = self.run_on_prompt_submit_hooks(&mut user_message).await;
        let result = match result {
            Ok(value) => value,
            Err(err) => return self.finalize_interruption(Err(err)).await,
        };
        match result {
            OnPromptSubmitResult::Cancel(reason) => {
                self.last_run_interrupted = true;
                return self.finalize_interruption(Err(WorkerError::Aborted(reason))).await;
            }
            OnPromptSubmitResult::Continue => {}
        }
        self.history.push(user_message);
        let result = self.run_turn_loop().await;
        self.finalize_interruption(result).await
    }

    fn drain_cancel_queue(&mut self) {
        use tokio::sync::mpsc::error::TryRecvError;
        loop {
            match self.cancel_rx.try_recv() {
                Ok(()) => continue,
                Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
            }
        }
    }

    fn try_cancelled(&mut self) -> bool {
        use tokio::sync::mpsc::error::TryRecvError;
        match self.cancel_rx.try_recv() {
            Ok(()) => true,
            Err(TryRecvError::Empty) => false,
            Err(TryRecvError::Disconnected) => true,
        }
    }

    /// イベント購読者を登録する
    ///
    /// 登録したSubscriberは、LLMからのストリーミングイベントを
    /// リアルタイムで受信できます。UIへのストリーム表示などに利用します。
    ///
    /// # 受信できるイベント
    ///
    /// - **ブロックイベント**: `on_text_block`, `on_tool_use_block`
    /// - **メタイベント**: `on_usage`, `on_status`, `on_error`
    /// - **完了イベント**: `on_text_complete`, `on_tool_call_complete`
    /// - **ターン制御**: `on_turn_start`, `on_turn_end`
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use llm_worker::{Worker, WorkerSubscriber, TextBlockEvent};
    ///
    /// struct MyPrinter;
    /// impl WorkerSubscriber for MyPrinter {
    ///     type TextBlockScope = ();
    ///     type ToolUseBlockScope = ();
    ///
    ///     fn on_text_block(&mut self, _: &mut (), event: &TextBlockEvent) {
    ///         if let TextBlockEvent::Delta(text) = event {
    ///             print!("{}", text);
    ///         }
    ///     }
    /// }
    ///
    /// worker.subscribe(MyPrinter);
    /// ```
    pub fn subscribe<Sub: WorkerSubscriber + 'static>(&mut self, subscriber: Sub) {
        let subscriber = Arc::new(Mutex::new(subscriber));

        // TextBlock用ハンドラを登録
        self.timeline
            .on_text_block(TextBlockSubscriberAdapter::new(subscriber.clone()));

        // ToolUseBlock用ハンドラを登録
        self.timeline
            .on_tool_use_block(ToolUseBlockSubscriberAdapter::new(subscriber.clone()));

        // Meta系ハンドラを登録
        self.timeline
            .on_usage(UsageSubscriberAdapter::new(subscriber.clone()));
        self.timeline
            .on_status(StatusSubscriberAdapter::new(subscriber.clone()));
        self.timeline
            .on_error(ErrorSubscriberAdapter::new(subscriber.clone()));

        // ターン制御用コールバックを登録
        self.turn_notifiers
            .push(Box::new(SubscriberTurnNotifier { subscriber }));
    }

    /// ツールを登録する
    ///
    /// 登録されたツールはLLMからの呼び出しで自動的に実行されます。
    /// 同名のツールを登録するとエラーになります。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use llm_worker::tool::{ToolMeta, ToolDefinition, Tool};
    /// use std::sync::Arc;
    ///
    /// let def: ToolDefinition = Arc::new(|| {
    ///     (ToolMeta::new("search").description("..."), Arc::new(MyTool) as Arc<dyn Tool>)
    /// });
    /// worker.register_tool(def)?;
    /// ```
    pub fn register_tool(&mut self, factory: ToolDefinition) -> Result<(), ToolRegistryError> {
        let (meta, instance) = factory();
        if self.tools.contains_key(&meta.name) {
            return Err(ToolRegistryError::DuplicateName(meta.name.clone()));
        }
        self.tools.insert(meta.name.clone(), (meta, instance));
        Ok(())
    }

    /// 複数のツールを登録
    pub fn register_tools(
        &mut self,
        factories: impl IntoIterator<Item = ToolDefinition>,
    ) -> Result<(), ToolRegistryError> {
        for factory in factories {
            self.register_tool(factory)?;
        }
        Ok(())
    }

    /// on_prompt_submit Hookを追加する
    ///
    /// `run()` でユーザーメッセージを受け取った直後に呼び出される。
    pub fn add_on_prompt_submit_hook(&mut self, hook: impl Hook<OnPromptSubmit> + 'static) {
        self.hooks.on_prompt_submit.push(Box::new(hook));
    }

    /// pre_llm_request Hookを追加する
    ///
    /// 各ターンのLLMリクエスト送信前に呼び出される。
    pub fn add_pre_llm_request_hook(&mut self, hook: impl Hook<PreLlmRequest> + 'static) {
        self.hooks.pre_llm_request.push(Box::new(hook));
    }

    /// pre_tool_call Hookを追加する
    pub fn add_pre_tool_call_hook(&mut self, hook: impl Hook<PreToolCall> + 'static) {
        self.hooks.pre_tool_call.push(Box::new(hook));
    }

    /// post_tool_call Hookを追加する
    pub fn add_post_tool_call_hook(&mut self, hook: impl Hook<PostToolCall> + 'static) {
        self.hooks.post_tool_call.push(Box::new(hook));
    }

    /// on_turn_end Hookを追加する
    pub fn add_on_turn_end_hook(&mut self, hook: impl Hook<OnTurnEnd> + 'static) {
        self.hooks.on_turn_end.push(Box::new(hook));
    }

    /// on_abort Hookを追加する
    pub fn add_on_abort_hook(&mut self, hook: impl Hook<OnAbort> + 'static) {
        self.hooks.on_abort.push(Box::new(hook));
    }

    /// タイムラインへの可変参照を取得(追加ハンドラ登録用)
    pub fn timeline_mut(&mut self) -> &mut Timeline {
        &mut self.timeline
    }

    /// 履歴への参照を取得
    pub fn history(&self) -> &[Message] {
        &self.history
    }

    /// システムプロンプトへの参照を取得
    pub fn get_system_prompt(&self) -> Option<&str> {
        self.system_prompt.as_deref()
    }

    /// 現在のターンカウントを取得
    pub fn turn_count(&self) -> usize {
        self.turn_count
    }

    /// 現在のリクエスト設定への参照を取得
    pub fn request_config(&self) -> &RequestConfig {
        &self.request_config
    }

    /// 最大トークン数を設定
    ///
    /// この設定はキャッシュロックとは独立しており、各リクエストに適用されます。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// worker.set_max_tokens(4096);
    /// ```
    pub fn set_max_tokens(&mut self, max_tokens: u32) {
        self.request_config.max_tokens = Some(max_tokens);
    }

    /// temperatureを設定
    ///
    /// 0.0から1.0(または2.0)の範囲で設定します。
    /// 低い値はより決定的な出力を、高い値はより多様な出力を生成します。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// worker.set_temperature(0.7);
    /// ```
    pub fn set_temperature(&mut self, temperature: f32) {
        self.request_config.temperature = Some(temperature);
    }

    /// top_pを設定(nucleus sampling)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// worker.set_top_p(0.9);
    /// ```
    pub fn set_top_p(&mut self, top_p: f32) {
        self.request_config.top_p = Some(top_p);
    }

    /// top_kを設定
    ///
    /// トークン選択時に考慮する上位k個のトークンを指定します。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// worker.set_top_k(40);
    /// ```
    pub fn set_top_k(&mut self, top_k: u32) {
        self.request_config.top_k = Some(top_k);
    }

    /// ストップシーケンスを追加
    ///
    /// # Examples
    ///
    /// ```ignore
    /// worker.add_stop_sequence("\n\n");
    /// ```
    pub fn add_stop_sequence(&mut self, sequence: impl Into<String>) {
        self.request_config.stop_sequences.push(sequence.into());
    }

    /// ストップシーケンスをクリア
    pub fn clear_stop_sequences(&mut self) {
        self.request_config.stop_sequences.clear();
    }

    /// キャンセル通知用Senderを取得する
    pub fn cancel_sender(&self) -> mpsc::Sender<()> {
        self.cancel_tx.clone()
    }

    /// リクエスト設定を一括で設定
    pub fn set_request_config(&mut self, config: RequestConfig) {
        self.request_config = config;
    }

    /// 実行をキャンセルする
    ///
    /// 現在実行中のストリーミングやツール実行を中断します。
    /// 次のイベントループのチェックポイントでWorkerError::Cancelledが返されます。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use std::sync::Arc;
    /// let worker = Arc::new(Mutex::new(Worker::new(client)));
    ///
    /// // 別スレッドで実行
    /// let worker_clone = worker.clone();
    /// tokio::spawn(async move {
    ///     let mut w = worker_clone.lock().unwrap();
    ///     w.run("Long task...").await
    /// });
    ///
    /// // キャンセル
    /// worker.lock().unwrap().cancel();
    /// ```
    pub fn cancel(&self) {
        let _ = self.cancel_tx.try_send(());
    }

    /// キャンセルされているかチェック
    pub fn is_cancelled(&mut self) -> bool {
        self.try_cancelled()
    }

    /// 前回の実行が中断されたかどうか
    pub fn last_run_interrupted(&self) -> bool {
        self.last_run_interrupted
    }

    /// 登録されたツールからLLM用ToolDefinitionのリストを生成
    fn build_tool_definitions(&self) -> Vec<LlmToolDefinition> {
        self.tools
            .values()
            .map(|(meta, _)| {
                LlmToolDefinition::new(&meta.name)
                    .description(&meta.description)
                    .input_schema(meta.input_schema.clone())
            })
            .collect()
    }

    /// テキストブロックとツール呼び出しからアシスタントメッセージを構築
    fn build_assistant_message(
        &self,
        text_blocks: &[String],
        tool_calls: &[ToolCall],
    ) -> Option<Message> {
        // テキストもツール呼び出しもない場合はNone
        if text_blocks.is_empty() && tool_calls.is_empty() {
            return None;
        }

        // テキストのみの場合はシンプルなテキストメッセージ
        if tool_calls.is_empty() {
            let text = text_blocks.join("");
            return Some(Message::assistant(text));
        }

        // ツール呼び出しがある場合は Parts として構築
        let mut parts = Vec::new();

        // テキストパーツを追加
        for text in text_blocks {
            if !text.is_empty() {
                parts.push(ContentPart::Text { text: text.clone() });
            }
        }

        // ツール呼び出しパーツを追加
        for call in tool_calls {
            parts.push(ContentPart::ToolUse {
                id: call.id.clone(),
                name: call.name.clone(),
                input: call.input.clone(),
            });
        }

        Some(Message {
            role: Role::Assistant,
            content: MessageContent::Parts(parts),
        })
    }

    /// リクエストを構築
    fn build_request(
        &self,
        tool_definitions: &[LlmToolDefinition],
        context: &[Message],
    ) -> Request {
        let mut request = Request::new();

        // システムプロンプトを設定
        if let Some(ref system) = self.system_prompt {
            request = request.system(system);
        }

        // メッセージを追加
        for msg in context {
            // Message から llm_client::Message への変換
            request = request.message(crate::llm_client::Message {
                role: match msg.role {
                    Role::User => crate::llm_client::Role::User,
                    Role::Assistant => crate::llm_client::Role::Assistant,
                },
                content: match &msg.content {
                    MessageContent::Text(t) => crate::llm_client::MessageContent::Text(t.clone()),
                    MessageContent::ToolResult {
                        tool_use_id,
                        content,
                    } => crate::llm_client::MessageContent::ToolResult {
                        tool_use_id: tool_use_id.clone(),
                        content: content.clone(),
                    },
                    MessageContent::Parts(parts) => crate::llm_client::MessageContent::Parts(
                        parts
                            .iter()
                            .map(|p| match p {
                                ContentPart::Text { text } => {
                                    crate::llm_client::ContentPart::Text { text: text.clone() }
                                }
                                ContentPart::ToolUse { id, name, input } => {
                                    crate::llm_client::ContentPart::ToolUse {
                                        id: id.clone(),
                                        name: name.clone(),
                                        input: input.clone(),
                                    }
                                }
                                ContentPart::ToolResult {
                                    tool_use_id,
                                    content,
                                } => crate::llm_client::ContentPart::ToolResult {
                                    tool_use_id: tool_use_id.clone(),
                                    content: content.clone(),
                                },
                            })
                            .collect(),
                    ),
                },
            });
        }

        // ツール定義を追加
        for tool_def in tool_definitions {
            request = request.tool(tool_def.clone());
        }

        // リクエスト設定を適用
        request = request.config(self.request_config.clone());

        request
    }

    /// Hooks: on_prompt_submit
    ///
    /// `run()` でユーザーメッセージを受け取った直後に呼び出される(最初だけ)。
    async fn run_on_prompt_submit_hooks(
        &self,
        message: &mut Message,
    ) -> Result<OnPromptSubmitResult, WorkerError> {
        for hook in &self.hooks.on_prompt_submit {
            let result = hook.call(message).await?;
            match result {
                OnPromptSubmitResult::Continue => continue,
                OnPromptSubmitResult::Cancel(reason) => {
                    return Ok(OnPromptSubmitResult::Cancel(reason));
                }
            }
        }
        Ok(OnPromptSubmitResult::Continue)
    }

    /// Hooks: pre_llm_request
    ///
    /// 各ターンのLLMリクエスト送信前に呼び出される(毎ターン)。
    async fn run_pre_llm_request_hooks(
        &self,
    ) -> Result<(PreLlmRequestResult, Vec<Message>), WorkerError> {
        let mut temp_context = self.history.clone();
        for hook in &self.hooks.pre_llm_request {
            let result = hook.call(&mut temp_context).await?;
            match result {
                PreLlmRequestResult::Continue => continue,
                PreLlmRequestResult::Cancel(reason) => {
                    return Ok((PreLlmRequestResult::Cancel(reason), temp_context));
                }
            }
        }
        Ok((PreLlmRequestResult::Continue, temp_context))
    }

    /// Hooks: on_turn_end
    async fn run_on_turn_end_hooks(&self) -> Result<OnTurnEndResult, WorkerError> {
        let mut temp_messages = self.history.clone();
        for hook in &self.hooks.on_turn_end {
            let result = hook.call(&mut temp_messages).await?;
            match result {
                OnTurnEndResult::Finish => continue,
                OnTurnEndResult::ContinueWithMessages(msgs) => {
                    return Ok(OnTurnEndResult::ContinueWithMessages(msgs));
                }
                OnTurnEndResult::Paused => return Ok(OnTurnEndResult::Paused),
            }
        }
        Ok(OnTurnEndResult::Finish)
    }

    /// Hooks: on_abort
    async fn run_on_abort_hooks(&self, reason: &str) -> Result<(), WorkerError> {
        let mut reason = reason.to_string();
        for hook in &self.hooks.on_abort {
            hook.call(&mut reason).await?;
        }
        Ok(())
    }

    async fn finalize_interruption<T>(
        &mut self,
        result: Result<T, WorkerError>,
    ) -> Result<T, WorkerError> {
        match result {
            Ok(value) => Ok(value),
            Err(err) => {
                self.last_run_interrupted = true;
                let reason = match &err {
                    WorkerError::Aborted(reason) => reason.clone(),
                    WorkerError::Cancelled => "Cancelled".to_string(),
                    _ => err.to_string(),
                };
                if let Err(hook_err) = self.run_on_abort_hooks(&reason).await {
                    self.last_run_interrupted = true;
                    return Err(hook_err);
                }
                Err(err)
            }
        }
    }

    /// 未実行のツール呼び出しがあるかチェック(Pauseからの復帰用)
    fn get_pending_tool_calls(&self) -> Option<Vec<ToolCall>> {
        let last_msg = self.history.last()?;
        if last_msg.role != Role::Assistant {
            return None;
        }

        let mut calls = Vec::new();
        if let MessageContent::Parts(parts) = &last_msg.content {
            for part in parts {
                if let ContentPart::ToolUse { id, name, input } = part {
                    calls.push(ToolCall {
                        id: id.clone(),
                        name: name.clone(),
                        input: input.clone(),
                    });
                }
            }
        }

        if calls.is_empty() { None } else { Some(calls) }
    }

    /// ツールを並列実行
    ///
    /// 全てのツールに対してpre_tool_callフックを実行後、
    /// 許可されたツールを並列に実行し、結果にpost_tool_callフックを適用する。
    async fn execute_tools(
        &mut self,
        tool_calls: Vec<ToolCall>,
    ) -> Result<ToolExecutionResult, WorkerError> {
        use futures::future::join_all;

        // ツール呼び出しIDから (ToolCall, Meta, Tool) へのマップ
        // PostToolCallフックで必要になるため保持する
        let mut call_info_map = HashMap::new();

        // Phase 1: pre_tool_call フックを適用(スキップ/中断を判定)
        let mut approved_calls = Vec::new();
        for mut tool_call in tool_calls {
            // ツール定義を取得
            if let Some((meta, tool)) = self.tools.get(&tool_call.name) {
                // コンテキストを作成
                let mut context = ToolCallContext {
                    call: tool_call.clone(),
                    meta: meta.clone(),
                    tool: tool.clone(),
                };

                let mut skip = false;
                for hook in &self.hooks.pre_tool_call {
                    let result = hook
                        .call(&mut context)
                        .await
                        .inspect_err(|_| self.last_run_interrupted = true)?;
                    match result {
                        PreToolCallResult::Continue => {}
                        PreToolCallResult::Skip => {
                            skip = true;
                            break;
                        }
                        PreToolCallResult::Abort(reason) => {
                            self.last_run_interrupted = true;
                            return Err(WorkerError::Aborted(reason));
                        }
                        PreToolCallResult::Pause => {
                            self.last_run_interrupted = true;
                            return Ok(ToolExecutionResult::Paused);
                        }
                    }
                }

                // フックで変更された内容を反映
                tool_call = context.call;

                // マップに保存(実行する場合のみ)
                if !skip {
                    call_info_map.insert(
                        tool_call.id.clone(),
                        (tool_call.clone(), meta.clone(), tool.clone()),
                    );
                    approved_calls.push(tool_call);
                }
            } else {
                // 未知のツールはそのまま承認リストに入れる(実行時にエラーになる)
                // Hookは適用しない(Metaがないため)
                approved_calls.push(tool_call);
            }
        }

        // Phase 2: 許可されたツールを並列実行(キャンセル可能)
        let futures: Vec<_> = approved_calls
            .into_iter()
            .map(|tool_call| {
                let tools = &self.tools;
                async move {
                    if let Some((_, tool)) = tools.get(&tool_call.name) {
                        let input_json =
                            serde_json::to_string(&tool_call.input).unwrap_or_default();
                        match tool.execute(&input_json).await {
                            Ok(content) => ToolResult::success(&tool_call.id, content),
                            Err(e) => ToolResult::error(&tool_call.id, e.to_string()),
                        }
                    } else {
                        ToolResult::error(
                            &tool_call.id,
                            format!("Tool '{}' not found", tool_call.name),
                        )
                    }
                }
            })
            .collect();

        // ツール実行をキャンセル可能にする
        let mut results = tokio::select! {
            results = join_all(futures) => results,
            cancel = self.cancel_rx.recv() => {
                if cancel.is_some() {
                    info!("Tool execution cancelled");
                }
                self.timeline.abort_current_block();
                self.last_run_interrupted = true;
                return Err(WorkerError::Cancelled);
            }
        };

        // Phase 3: post_tool_call フックを適用
        for tool_result in &mut results {
            // 保存しておいた情報を取得
            if let Some((tool_call, meta, tool)) = call_info_map.get(&tool_result.tool_use_id) {
                let mut context = PostToolCallContext {
                    call: tool_call.clone(),
                    result: tool_result.clone(),
                    meta: meta.clone(),
                    tool: tool.clone(),
                };

                for hook in &self.hooks.post_tool_call {
                    let result = hook
                        .call(&mut context)
                        .await
                        .inspect_err(|_| self.last_run_interrupted = true)?;
                    match result {
                        PostToolCallResult::Continue => {}
                        PostToolCallResult::Abort(reason) => {
                            self.last_run_interrupted = true;
                            return Err(WorkerError::Aborted(reason));
                        }
                    }
                }
                // フックで変更された結果を反映
                *tool_result = context.result;
            }
        }

        Ok(ToolExecutionResult::Completed(results))
    }

    /// 内部で使用するターン実行ロジック
    async fn run_turn_loop(&mut self) -> Result<WorkerResult, WorkerError> {
        self.reset_interruption_state();
        self.drain_cancel_queue();
        let tool_definitions = self.build_tool_definitions();

        info!(
            message_count = self.history.len(),
            tool_count = tool_definitions.len(),
            "Starting worker run"
        );

        // Resume check: Pending tool calls
        if let Some(tool_calls) = self.get_pending_tool_calls() {
            info!("Resuming pending tool calls");
            match self.execute_tools(tool_calls).await {
                Ok(ToolExecutionResult::Paused) => {
                    self.last_run_interrupted = true;
                    return Ok(WorkerResult::Paused);
                }
                Ok(ToolExecutionResult::Completed(results)) => {
                    for result in results {
                        self.history
                            .push(Message::tool_result(&result.tool_use_id, &result.content));
                    }
                    // Continue to loop
                }
                Err(err) => {
                    self.last_run_interrupted = true;
                    return Err(err);
                }
            }
        }

        loop {
            // キャンセルチェック
            if self.try_cancelled() {
                info!("Execution cancelled");
                self.timeline.abort_current_block();
                self.last_run_interrupted = true;
                return Err(WorkerError::Cancelled);
            }

            // ターン開始を通知
            let current_turn = self.turn_count;
            debug!(turn = current_turn, "Turn start");
            for notifier in &self.turn_notifiers {
                notifier.on_turn_start(current_turn);
            }

            // Hook: pre_llm_request
            let (control, request_context) = self
                .run_pre_llm_request_hooks()
                .await
                .inspect_err(|_| self.last_run_interrupted = true)?;
            match control {
                PreLlmRequestResult::Cancel(reason) => {
                    info!(reason = %reason, "Aborted by hook");
                    for notifier in &self.turn_notifiers {
                        notifier.on_turn_end(current_turn);
                    }
                    self.last_run_interrupted = true;
                    return Err(WorkerError::Aborted(reason));
                }
                PreLlmRequestResult::Continue => {}
            }

            // リクエスト構築
            let request = self.build_request(&tool_definitions, &request_context);
            debug!(
                message_count = request.messages.len(),
                tool_count = request.tools.len(),
                has_system = request.system_prompt.is_some(),
                "Sending request to LLM"
            );

            // ストリーム処理
            debug!("Starting stream...");
            let mut event_count = 0;

            // ストリームを取得(キャンセル可能)
            let mut stream = tokio::select! {
                stream_result = self.client.stream(request) => stream_result
                    .inspect_err(|_| self.last_run_interrupted = true)?,
                cancel = self.cancel_rx.recv() => {
                    if cancel.is_some() {
                        info!("Cancelled before stream started");
                    }
                    self.timeline.abort_current_block();
                    self.last_run_interrupted = true;
                    return Err(WorkerError::Cancelled);
                }
            };

            loop {
                tokio::select! {
                    // ストリームからイベントを受信
                    event_result = stream.next() => {
                        match event_result {
                            Some(result) => {
                                match &result {
                                    Ok(event) => {
                                        trace!(event = ?event, "Received event");
                                        event_count += 1;
                                    }
                                    Err(e) => {
                                        warn!(error = %e, "Stream error");
                                    }
                                }
                                let event = result
                                    .inspect_err(|_| self.last_run_interrupted = true)?;
                                let timeline_event: crate::timeline::event::Event = event.into();
                                self.timeline.dispatch(&timeline_event);
                            }
                            None => break, // ストリーム終了
                        }
                    }
                    // キャンセル待機
                    cancel = self.cancel_rx.recv() => {
                        if cancel.is_some() {
                            info!("Stream cancelled");
                        }
                        self.timeline.abort_current_block();
                        self.last_run_interrupted = true;
                        return Err(WorkerError::Cancelled);
                    }
                }
            }
            debug!(event_count = event_count, "Stream completed");

            // ターン終了を通知
            for notifier in &self.turn_notifiers {
                notifier.on_turn_end(current_turn);
            }
            self.turn_count += 1;

            // 収集結果を取得
            let text_blocks = self.text_block_collector.take_collected();
            let tool_calls = self.tool_call_collector.take_collected();

            // アシスタントメッセージを履歴に追加
            let assistant_message = self.build_assistant_message(&text_blocks, &tool_calls);
            if let Some(msg) = assistant_message {
                self.history.push(msg);
            }

            if tool_calls.is_empty() {
                // ツール呼び出しなし → ターン終了判定
                let turn_result = self
                    .run_on_turn_end_hooks()
                    .await
                    .inspect_err(|_| self.last_run_interrupted = true)?;
                match turn_result {
                    OnTurnEndResult::Finish => {
                        self.last_run_interrupted = false;
                        return Ok(WorkerResult::Finished);
                    }
                    OnTurnEndResult::ContinueWithMessages(additional) => {
                        self.history.extend(additional);
                        continue;
                    }
                    OnTurnEndResult::Paused => {
                        self.last_run_interrupted = true;
                        return Ok(WorkerResult::Paused);
                    }
                }
            }

            // ツール実行
            match self.execute_tools(tool_calls).await {
                Ok(ToolExecutionResult::Paused) => {
                    self.last_run_interrupted = true;
                    return Ok(WorkerResult::Paused);
                }
                Ok(ToolExecutionResult::Completed(results)) => {
                    for result in results {
                        self.history
                            .push(Message::tool_result(&result.tool_use_id, &result.content));
                    }
                }
                Err(err) => {
                    self.last_run_interrupted = true;
                    return Err(err);
                }
            }
        }
    }

    /// 実行を再開(Pause状態からの復帰)
    ///
    /// 新しいユーザーメッセージを履歴に追加せず、現在の状態からターン処理を再開する。
    pub async fn resume(&mut self) -> Result<WorkerResult, WorkerError> {
        self.reset_interruption_state();
        let result = self.run_turn_loop().await;
        self.finalize_interruption(result).await
    }
}

// =============================================================================
// Mutable状態専用の実装
// =============================================================================

impl<C: LlmClient> Worker<C, Mutable> {
    /// 新しいWorkerを作成(Mutable状態)
    pub fn new(client: C) -> Self {
        let text_block_collector = TextBlockCollector::new();
        let tool_call_collector = ToolCallCollector::new();
        let mut timeline = Timeline::new();
        let (cancel_tx, cancel_rx) = mpsc::channel(1);

        // コレクターをTimelineに登録
        timeline.on_text_block(text_block_collector.clone());
        timeline.on_tool_use_block(tool_call_collector.clone());

        Self {
            client,
            timeline,
            text_block_collector,
            tool_call_collector,
            tools: HashMap::new(),
            hooks: HookRegistry::new(),
            system_prompt: None,
            history: Vec::new(),
            locked_prefix_len: 0,
            turn_count: 0,
            turn_notifiers: Vec::new(),
            request_config: RequestConfig::default(),
            last_run_interrupted: false,
            cancel_tx,
            cancel_rx,
            _state: PhantomData,
        }
    }

    /// システムプロンプトを設定(ビルダーパターン)
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// システムプロンプトを設定(可変参照版)
    pub fn set_system_prompt(&mut self, prompt: impl Into<String>) {
        self.system_prompt = Some(prompt.into());
    }

    /// 最大トークン数を設定(ビルダーパターン)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let worker = Worker::new(client)
    ///     .system_prompt("You are a helpful assistant.")
    ///     .max_tokens(4096);
    /// ```
    pub fn max_tokens(mut self, max_tokens: u32) -> Self {
        self.request_config.max_tokens = Some(max_tokens);
        self
    }

    /// temperatureを設定(ビルダーパターン)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let worker = Worker::new(client)
    ///     .temperature(0.7);
    /// ```
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.request_config.temperature = Some(temperature);
        self
    }

    /// top_pを設定(ビルダーパターン)
    pub fn top_p(mut self, top_p: f32) -> Self {
        self.request_config.top_p = Some(top_p);
        self
    }

    /// top_kを設定(ビルダーパターン)
    pub fn top_k(mut self, top_k: u32) -> Self {
        self.request_config.top_k = Some(top_k);
        self
    }

    /// ストップシーケンスを追加(ビルダーパターン)
    pub fn stop_sequence(mut self, sequence: impl Into<String>) -> Self {
        self.request_config.stop_sequences.push(sequence.into());
        self
    }

    /// リクエスト設定をまとめて設定(ビルダーパターン)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let config = RequestConfig::new()
    ///     .with_max_tokens(4096)
    ///     .with_temperature(0.7);
    ///
    /// let worker = Worker::new(client)
    ///     .system_prompt("...")
    ///     .with_config(config);
    /// ```
    pub fn with_config(mut self, config: RequestConfig) -> Self {
        self.request_config = config;
        self
    }

    /// 現在の設定をプロバイダに対してバリデーションする
    ///
    /// 未サポートの設定があればエラーを返す。
    /// チェーンの最後で呼び出すことで、設定の問題を早期に検出できる。
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let worker = Worker::new(client)
    ///     .temperature(0.7)
    ///     .top_k(40)
    ///     .validate()?;  // OpenAIならtop_kがサポートされないためエラー
    /// ```
    ///
    /// # Returns
    /// * `Ok(Self)` - バリデーション成功
    /// * `Err(WorkerError::ConfigWarnings)` - 未サポートの設定がある
    pub fn validate(self) -> Result<Self, WorkerError> {
        let warnings = self.client.validate_config(&self.request_config);
        if warnings.is_empty() {
            Ok(self)
        } else {
            Err(WorkerError::ConfigWarnings(warnings))
        }
    }

    /// 履歴への可変参照を取得
    ///
    /// Mutable状態でのみ利用可能。履歴を自由に編集できる。
    pub fn history_mut(&mut self) -> &mut Vec<Message> {
        &mut self.history
    }

    /// 履歴を設定
    pub fn set_history(&mut self, messages: Vec<Message>) {
        self.history = messages;
    }

    /// 履歴にメッセージを追加(ビルダーパターン)
    pub fn with_message(mut self, message: Message) -> Self {
        self.history.push(message);
        self
    }

    /// 履歴にメッセージを追加
    pub fn push_message(&mut self, message: Message) {
        self.history.push(message);
    }

    /// 複数のメッセージを履歴に追加(ビルダーパターン)
    pub fn with_messages(mut self, messages: impl IntoIterator<Item = Message>) -> Self {
        self.history.extend(messages);
        self
    }

    /// 複数のメッセージを履歴に追加
    pub fn extend_history(&mut self, messages: impl IntoIterator<Item = Message>) {
        self.history.extend(messages);
    }

    /// 履歴をクリア
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    /// 設定を適用(将来の拡張用)
    #[allow(dead_code)]
    pub fn config(self, _config: WorkerConfig) -> Self {
        self
    }

    /// ロックしてCacheLocked状態へ遷移
    ///
    /// この操作により、現在のシステムプロンプトと履歴が「確定済みプレフィックス」として
    /// 固定される。以降は履歴への追記のみが可能となり、キャッシュヒットが保証される。
    pub fn lock(self) -> Worker<C, CacheLocked> {
        let locked_prefix_len = self.history.len();
        Worker {
            client: self.client,
            timeline: self.timeline,
            text_block_collector: self.text_block_collector,
            tool_call_collector: self.tool_call_collector,
            tools: self.tools,
            hooks: self.hooks,
            system_prompt: self.system_prompt,
            history: self.history,
            locked_prefix_len,
            turn_count: self.turn_count,
            turn_notifiers: self.turn_notifiers,
            request_config: self.request_config,
            last_run_interrupted: self.last_run_interrupted,
            cancel_tx: self.cancel_tx,
            cancel_rx: self.cancel_rx,
            _state: PhantomData,
        }
    }

}

// =============================================================================
// CacheLocked状態専用の実装
// =============================================================================

impl<C: LlmClient> Worker<C, CacheLocked> {
    /// ロック時点のプレフィックス長を取得
    pub fn locked_prefix_len(&self) -> usize {
        self.locked_prefix_len
    }

    /// ロックを解除してMutable状態へ戻す
    ///
    /// 注意: この操作を行うと、以降のリクエストでキャッシュがヒットしなくなる可能性がある。
    /// 履歴を編集する必要がある場合にのみ使用すること。
    pub fn unlock(self) -> Worker<C, Mutable> {
        Worker {
            client: self.client,
            timeline: self.timeline,
            text_block_collector: self.text_block_collector,
            tool_call_collector: self.tool_call_collector,
            tools: self.tools,
            hooks: self.hooks,
            system_prompt: self.system_prompt,
            history: self.history,
            locked_prefix_len: 0,
            turn_count: self.turn_count,
            turn_notifiers: self.turn_notifiers,
            request_config: self.request_config,
            last_run_interrupted: self.last_run_interrupted,
            cancel_tx: self.cancel_tx,
            cancel_rx: self.cancel_rx,
            _state: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    // 基本的なテストのみ。LlmClientを使ったテストは統合テストで行う。
}