SLOPSHOPPER

tts

Reads Claude's replies aloud as they stream, sentence by sentence, through VOICEVOX, Irodori-TTS or any command.

paneguardcommandtoaststatusprompt
v0.11.0MITupdated 2026-10-26kajidog/cc-mods-tts
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tts
│ ┃ tts-picker ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ Nothing to pick. │ tts │ │ ⏺ Read(src/auth.ts) │ tts: no audio player found (ffplay, │ │ ⎿ Read 6 lines │ paplay, aplay, afplay, powershell.exe) │ │ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · tts-picker
Nothing to pick.
README

cc-mods-tts

Latest Claude Code

Claude Code の mod(関数フックのプラグイン)。Claude の返答をストリーミング中に一文ずつ読み上げます。

  • 対応プラットフォーム: macOS / Linux / Windows(ネイティブ・WSL)
  • turn.step の text チャンクを文に分割し、合成と再生をパイプラインで流す(コードブロック・表・URL は読み上げから除外してます)
  • エンジン: VOICEVOX 互換 / Irodori-TTS / 任意コマンド

コードブロック・表・URL は読まず、パスや識別子は聞き取りやすい形に直して読みます。

書かれ方読み方
コードブロック・表飛ばして「コードは省略します。」「表は省略します。」と言う
引用最初の文に「引用、」を付けて読む。中のコードや表は飛ばす
URL・リンクURL は読まない。リンクは表示される文字だけ読む
箇条書きの印・括弧印は読まない。括弧は外して中身を読む
ファイルパスファイル名と行番号だけ読む
maxCharsPerTurn などの識別子単語に分けて読む(SQLite・iPhone などの名前は分けない)
12文字以上のハッシュ・UUID先頭7文字・8文字だけ読む
<kbd> <br> などの HTML タグ・コメントタグは読まず、中の文字だけ読む
負数・小数・C++・--help記号を残して読む
絵文字エンジンに任せる(VOICEVOX は読み飛ばす)

読み方をさらに変えたい場合は、engine=command でスクリプトを挟めます。

セットアップ

Claude Code 2.1.287 以降(Mods が既定で有効なバージョン)。どちらか一方で使えるようにできます。

A. GitHub からインストール(使うだけなら)

ターミナルの Claude Code のプロンプトで:

/plugin install tts --marketplace kajidog/cc-mods-tts

「Add marketplace?」に y、スコープは user(既定)のまま Enter。そのセッションからすぐ有効になり、以降のセッションでも読み込まれます。更新は claude plugin update tts のあと /reload-plugins。

デスクトップアプリの Code タブではこのコマンドは使えません。 設定→プラグインからマーケットプレイスの追加でkajidog/cc-mods-ttsのリポジトリを追加してこのプラグイン(tts)をインストールしてください

B. クローンして読み込む(手元で改造するなら)

git clone https://github.com/kajidog/cc-mods-tts.git ~/cc-mods-tts
claude --plugin-dir ~/cc-mods-tts

常に読み込むなら ~/.claude/settings.json の env に "CLAUDE_CODE_PLUGIN_DIRS": "~/cc-mods-tts"。この方法ではクローンしたフォルダのコードがそのまま動き、編集するとセッション中に読み込み直されます。

読み込んだら

  1. VOICEVOX を起動しておく(インストール時の既定エンジン)
  2. /tts engine で voicevox が ● になっているか確認
  3. 声を変えたい場合は /tts voice で選ぶ(既定は「ずんだもん・ノーマル」)
  4. /tts test で鳴るか確認

Irodori-TTS を使う場合

  1. Irodori-TTS-Server を起動する
  2. 参照音声(例: sample.wav)をサーバー側の voices/ に置く。拡張子を除いたファイル名(この例では sample)が声の ID になります
  3. /tts engine irodori で切り替え、/tts voice で追加した声を選ぶ(/tts voice sample で直接指定もできます)
  4. /tts test で鳴るか確認

voices/ は Irodori-TTS-Server 側のフォルダです。IRODORI_VOICES_DIR を設定している場合は、そのフォルダに置いてください。Irodori は声を選ぶまで読み上げができません。

対応する音声形式やアップロード API など、詳しくは公式の音声追加・管理手順(Voice Management)を参照してください。

OS 標準の音声を使う場合(engine=command)

VOICEVOX などを入れなくても、OS に入っている音声で読めます。エンジンは VOICEVOX のままにして、OS の音声を予備にもできます。TTS: Command を設定し、/config の TTS: Fallback engine を command にしておくと、VOICEVOX が起動していないときや落ちたときでも、その文を OS の音声で読みます。VOICEVOX が戻れば、次の文からまた VOICEVOX で読みます。VOICEVOX が使えない間は、ステータス行に ⚠ tts: voicevox down と出ます。エンジンは動いているのに読めなかったとき(プレイヤーが起動できないなど)は ⚠ tts: 失敗 と出ます。どちらも次に読めれば消え、トーストは出しません。

/config の TTS: Command に次のどれかを入れて、/tts engine command で切り替えます。コマンドは空白で区切って引数にするので、引数(パスを含む)に空白は入れられません。{out} は書き出す wav のパスに置き換わり、読む文は標準入力で渡ります。

macOS(say。日本語の声 Kyoko がない場合は、システム設定 → アクセシビリティ → 読み上げコンテンツ で追加)

say -v Kyoko -f - --file-format=WAVE --data-format=LEI16@22050 -o {out}

Windows(標準の音声合成。日本語の声 Haruka は日本語版 Windows に入っています)

次の内容を C:\tts\speak.ps1 などに保存します(空白を含まないパスに置いてください)。

param([string]$Out)
Add-Type -AssemblyName System.Speech
[Console]::InputEncoding = [Text.Encoding]::UTF8
$text = [Console]::In.ReadToEnd()
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$synth.SetOutputToWaveFile($Out)
$synth.Speak($text)
$synth.Dispose()
powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\tts\speak.ps1 {out}

WSL から使う場合は、{out} が Linux のパスのまま渡るので、このままでは使えません。

Linux(eSpeak NG。日本語はかなり機械的な読み方です)

espeak-ng -v ja --stdin -w {out}

どれも TTS: Speed は効きません。速さは各コマンドのオプション(say -r、espeak-ng -s など)で変えてください。

アンインストール

A で入れた場合:

claude plugin uninstall tts@cc-mods-tts
claude plugin marketplace remove cc-mods-tts   # マーケットプレイスも消すなら

起動中のセッションには /reload-plugins で反映されます。

B の場合は --plugin-dir を付けずに起動するか、CLAUDE_CODE_PLUGIN_DIRS を settings.json から消して、クローンしたフォルダを削除します。

どちらの場合も、/config で変えた設定は ~/.claude/settings.json の pluginConfigs に残ります(A は tts@cc-mods-tts、B は tts@inline のキー)。不要なら手で消してください。

使い方

コマンド内容
/tts状態表示(on/off・モード・エンジン・速度・音量)
/tts helpコマンド一覧
/tts config設定の一覧と今の値
/tts on / /tts off有効・無効(/config の TTS: Enabled と同じ)
/tts stop合成・再生中の処理とキューを止め、そのターンの残りの返答も読まない。次のターンから再開
/tts test [text]通常の返答と同じ整形を通してテスト読み上げ
/tts replay直前の最終回答を、文字数の上限なしで最初から読み直す
/tts replay select最近の発言ブロック(ツール呼び出しやユーザーの発言で区切ったもの)を新しい順に一覧し、冒頭の文で選んで最初から読み直す
`/tts mode [stream\final\notify]`読み上げモード切替。引数なしでモードを選ぶペインを開く
`/tts summary [on\off]`長い回答の要約だけ読むかどうか(下記)。引数なしで今の値を表示
/tts engine [name]エンジン切替。引数なしで各エンジンが応答するか(ok / down / unset)を表示
/tts voice [id]引数なしで声を選ぶペインを開く(↑↓で移動、Enter で決定、Esc で閉じる)。id 指定で直接設定
/tts speed [n] / /tts volume [n]速度・音量(1 が等倍)。引数なしで候補を選ぶペインを開く

声の候補が多い場合は64件ずつ表示します。p / n(Previous / Next)でページを切り替え、↑↓と Enter で選択できます。最初は現在の声があるページを開きます。

読み上げモード

モード読むもの
stream(既定)返答をストリーミング中に一文ずつ。最終回答が届いた時点でツール前の文をまだ読んでいたら、それを止めて最終回答を頭から読む
finalターン終了時に最終的な返答だけ(途中のツール前の文は読まない)
notify短い通知だけ:「完了しました」「エラーで止まりました」など

要約だけ読む

/tts summary on(/config の TTS: Read the summary only)にすると、Claude に「長い回答は1行目に 要約: … で要約を書く」よう頼みます(stream / final モードのときだけシステムプロンプトに足します)。既定はオフです。最終回答が要約の行で始まっていれば、その1行だけ読み、残りは読みません。要約がなければ、これまで通り回答を読みます。

  • 要約は画面にもそのまま出ます。読み上げ専用の隠しテキストではないので、表示が崩れたり余計なトークンを使ったりしません。
  • 判定するのは回答の1行目だけです。要約:・要約:・Summary:・TL;DR: を目印にします。
  • stream モードでは、ツール前の発言はこれまで通り読み、最終回答だけ要約の行で止めます。
  • /tts replay は要約ではなく回答全体を読み直します。
  • /tts summary off で、頼むのも要約だけ読むのもやめます。

どのモードでも、以下の操作待ちのダイアログが出たら読み上げを止めて通知します:

ダイアログ読む文(既定。/config の TTS notice で変えられる)
質問(AskUserQuestion)1件: 質問があります。+質問文 / 複数: 質問が3件あります。
プランの承認(ExitPlanMode)プランの確認をお願いします。
Bash の許可コマンドの確認をお願いします。+コマンドの説明(description)
その他のツールの許可ツールの許可をお願いします。

許可は classic.PermissionRequest(ダイアログを出すときに発火)で拾うので、ルールや auto モードで自動判定された呼び出しでは鳴らない。通知の音声は初回だけ合成し、以降は使い回す。

複数のセッション

同じマシンで複数のセッションが読み上げても、音声は重ならず順番に再生します。設定はいりません。/config の TTS: Take turns with other sessions をオフにすると、待たずにすぐ再生します。

  • 優先度は 通知・ダイアログ・/tts コマンド > 最終回答 > ツール前の発言 の順です。読んでいるセッションは、文の切れ目でより優先度の高い待ち手に譲ります(読みかけの文は最後まで読みます)。
  • 待ち時間の上限(maxWaitSeconds)を超えたら捨てるのは、ツール前の発言だけです。通知と最終回答は必ず読みます。
  • ダイアログや /tts stop で止まるのは、そのセッションの読み上げだけです。
  • WSL 内と Windows ネイティブのセッションは別々に順番を取ります(同時に動かすと重なることがあります)。

再生の補足

  • 停止: 合成のリクエストも中断します。ただし TTS サーバーが切断後も計算を続ける場合は、終わるまで次の合成が待たされることがあります。
  • 語尾の途切れ: ffplay / powershell では、無音を除いた WAV の後ろに0.2秒の無音を足します。ffmpeg が必要で、ない場合は元の音声をそのまま再生します。
  • ストリーミング再生: VOICEVOX 0.26 以降では、何も再生していないときの文を、合成しながら再生します(長い文ほど早く喋り始めます)。続く文はその間にファイルへ合成します。ffplay と ffmpeg がある Linux・macOS・WSL で使い、設定はいりません。ストリーミングに対応していないエンジン(0.25 以前など)では一度だけ試して、以降はファイルで合成します。ストリーミングでは文末の長い無音は削りません。
  • WSL のノイズ: ffplay は WSLg を経由するため、「ジリジリ」とノイズが混じることがあります。/config の TTS: Player を powershell にすると改善します(文と文の間は少し空きます)。

設定

設定はすべて /config の tts にまとめてます。項目名はどれも TTS: / TTS notice: で始まります。

項目(キー)内容既定
TTS: Enabled(enabled)読み上げる / 読み上げないtrue
TTS: Read mode(mode)stream / final / notify(上記)stream
TTS: Engine(engine)voicevox / irodori / commandvoicevox
TTS: Fallback engine(fallback)メインのエンジンが失敗した文(サーバー停止・未設定など)を読むエンジン。メインが使えない間は、ステータス行に ⚠ tts: voicevox down のように出るnone
TTS: Speed(speed)速度。エンジン側で合成時にかける(Irodori は 0.25〜4、VOICEVOX は speedScale)。command では無視1.1
TTS: Volume(volume)音量。再生時にかけるのでどのエンジンでも効く。ffplay / paplay / afplay は再生コマンドで、aplay / powershell は ffmpeg があれば再生前に変える1
TTS: Player(player)再生コマンド。auto は Windows ネイティブでは ffplay → powershell.exe、それ以外では ffplay → paplay → aplay → afplay → powershell.exe の順に最初に見つかったものauto
TTS: Max characters per response(maxCharsPerTurn)1回の応答で読む最大文字数。超えたら「途中を省略します。」と言って残りを飛ばし、応答の最後の1文だけ読む。0 で無制限600
TTS: Take turns with other sessions(sharePlayback)複数のセッションが読み上げるとき、1つずつ順番に再生する。オフにすると各セッションがすぐに再生する(音声が重なることがある)オン
TTS: Max wait for other sessions(maxWaitSeconds)ほかのセッションが読み上げている間、ツール前の発言を待たせる最大秒数。超えたら捨てる。通知と最終回答は常に待って読む。0 で無制限60
TTS: Stop on new prompt(interruptOnPrompt)プロンプト送信で読み上げを止めるtrue
TTS: Prompt for the model(modelPrompt)読み上げ中(stream / final モード)に Claude のシステムプロンプトへ足す文。説明・進捗報告は原則日本語にし、コード・引用・ユーザーの言語指定は保持する。空にすると何も足さない応答は音声で読み上げられています。説明やツール呼び出しの合間の進捗報告は原則として日本語で書いてください。ただし、コード・識別子・引用はそのまま保持し、ユーザーが指定した言語を優先してください。
TTS: Read the summary only(summary)長い回答の1行目に要約を書くよう Claude に頼み、要約があればそれだけ読む(stream / final モード)。/tts summary on / off と同じfalse
TTS: Irodori URL(irodoriUrl)Irodori-TTS の URLhttp://localhost:8088
TTS: Irodori voice(irodoriVoice)Irodori の声(/tts voice で選べる)(未設定)
TTS: VOICEVOX URL(voicevoxUrl)VOICEVOX 互換エンジンの URL(AivisSpeech は http://localhost:10101)http://localhost:50021
TTS: VOICEVOX speaker(voicevoxSpeaker)VOICEVOX のスタイル id(/tts voice で選べる)3
TTS: Command(command)engine=command のときのコマンド。空白区切り、{out} が書き出す wav のパスに置き換わり、本文は標準入力で渡る(未設定)
TTS notice: done / error / refusal(noticeDone / noticeError / noticeRefusal)notify モードでターン終了時に言う文完了しました。/ エラーで止まりました。/ 応答できませんでした。
TTS notice: question(noticeQuestion)質問が1件出たとき、質問文の前に言う文質問があります。
TTS notice: questions(noticeQuestions)質問が複数出たときに言う文。{n} が件数になる質問が{n}件あります。
TTS notice: plan(noticePlan)プランの承認待ちで言う文プランの確認をお願いします。
TTS notice: command(noticeCommand)Bash の許可ダイアログで、コマンドの説明の前に言う文コマンドの確認をお願いします。
TTS notice: tool(noticeTool)その他のツールの許可ダイアログで言う文ツールの許可をお願いします。
TTS notice: cut(noticeCut)文字数の上限で残りを飛ばすときに言う文。この後に応答の最後の1文を読む途中を省略します。
TTS notice: code(noticeCode)コードブロックを飛ばすところで言う文(stream / final モード)コードは省略します。
TTS notice: table(noticeTable)表を飛ばすところで言う文(stream / final モード)表は省略します。
TTS notice: quote(noticeQuote)引用の最初の文の前につなげて言う文(stream / final モード)引用、

通知の文はどれも空にするとその通知の読み上げをスキップできます(注:スキップしても既存の再生は止まります)。 質問やコマンドの通知を空にした場合は、質問文・コマンドの説明も読みません。

Irodori の速度の対応範囲は 0.25〜4 です。Mod ではこの下限による入力エラーは出しませんが、範囲外の値は Irodori サーバーが拒否する場合があります。文字数の上限に、省略やコードを知らせる通知文と、省略後に読む最後の1文は含みません。上限をまたぐ文は途中まで読まずに飛ばします。最後の1文が300文字を超える場合は読みません。

音声ファイルはセッション用の一時ディレクトリに保存し、再生後に削除します。macOS / Linux / WSL では所有者のみアクセスできる権限で作成し、Windows ネイティブではユーザーの一時フォルダ(%TEMP%)のアクセス権を引き継ぎます。通知キャッシュはセッション終了時・Mod の再読み込み時に削除します。プロセスの強制終了などで清掃が実行できなかった場合は、一時ディレクトリに残ることがあります。

前提

  • curl(Windows では curl.exe)
  • mktemp(macOS / Linux / WSL の一時ディレクトリ作成に使用)
  • Windows ネイティブ: Windows PowerShell(powershell.exe、一時ファイルの管理と再生に使用)
  • 再生: ffplay / paplay / aplay / afplay / powershell.exe(Windows・WSL)のいずれか(player: auto で自動選択)

開発

npm install
CLAUDE_CODE_PLUGIN_DIR_WATCH=1 claude --init-only --plugin-dir .  # .claude-plugin/types/ を生成(型チェックに必要)
npm run check  # lint・validate・型チェック・test をまとめて実行

個別には npm run lint / npm run validate / npm run typecheck / npm test で実行できます。Biome と TypeScript は devDependencies で固定し、claude は PATH にあるものを使います。

CI(.github/workflows/ci.yml)は main への push と PR で lint を実行し、Linux・Windows で validate・型チェック・test を実行します。型チェックの前に、上記の初期化コマンドで .claude-plugin/types/ を生成します。対話セッションや API キーは不要です。

API は early access のため、Claude Code の更新で変わることがある(CI で確認しているバージョン: 2.1.296)。

エンジンを追加する

エンジンは hooks/engines/ に1ファイルずつある(irodori.ts / voicevox.ts / command.ts)。追加するには:

  1. hooks/engines/<name>.ts に Engine(engine.ts の型)を書く。load(options, isWindows) で自分の設定を読み、synthesis(text, out) で wav を out に書くコマンド列を返す。声の一覧があれば voices も。合成しながら WAV を標準出力に書けるなら stream(text) も(WAV 以外を返すと、その文は synthesis で読み直す)
  2. hooks/engines/index.ts の ENGINES に足す
  3. .claude-plugin/plugin.json の userConfig.engine.options に名前を足し、そのエンジンの設定項目を追加する

状態を別の Mod で表示する

この Mod は画面に UI を出しません(エンジンが落ちたときのステータス行だけ出します)。読んでいる文やエンジンの状態は $.state に公開しているので、表示は別の Mod で作れます。型は types/index.d.ts の SpeechState / EngineState です。

キー中身
{ plugin: "tts", key: "speech" }state(idle / preparing / waiting / playing)と、待っている・読んでいる文の text
{ plugin: "tts", key: "engine" }使っているエンジンの name・voice と status(checking / ok / down / unset / off)

ui.render の中で $.state.get すると、値が変わるたびに描き直されます。書けるのはこの Mod だけです。

別の Mod から読み上げる

$.tts を公開しているので、別の Mod からこのセッションに読み上げさせられます。型は types/index.d.ts の Tts です。呼ぶ側の plugin.json の dependencies に "tts" を足すと、$.tts に型が付きます。

const result = await $.tts.speak({ text: "ビルドが終わりました。" })
// { isQueued: true }、または { isQueued: false, reason: "off" | "empty" | "ended" }
await $.tts.stop()
メソッド内容
speak({ text, interrupt? })text を /tts test と同じ整形で読む(コードブロック・表・URL は読まない)。キューに入った時点で返り、読み終わりは待たない(speech の状態で分かる)。interrupt: true で、読んでいるものとキューを止めてすぐ読む(stop() と同じく、ストリーミング中の返答の残りも読まない)
stop()読んでいるものとキューを止める。ストリーミング中の返答の残りも読まず、その返答がターンの回答なら、ターンの終わりにも読まない(final モードも同じ)。/tts stop と違い、次の応答からはまた読む

speak は読み上げモードに関係なく読み、1回の応答の文字数の上限もかかりません。複数のセッションの間では通知と同じく最優先です。/tts off の間は読まずに reason: "off"、セッションが終わった後は reason: "ended" を返します。セッションが始まる前に呼んだ分は、始まってから読みます。

実装例: gh-inbox-tts(GitHub の通知を $.tts.speak で読み上げる Mod)

変更履歴とリリース

変更履歴は CHANGELOG.md にまとめています。Changesets で変更メモを集め、GitHub Actions がリリース用 PR を作成・更新します。

開発時は Node.js 22.11 以降の 22 系、24 系、または 26 以降と、npm 10.9 以降を使います。

npm ci
npm run changeset

patch(修正)・minor(機能追加)・major(互換性のない変更)を選び、変更内容を日本語で入力します。生成された .changeset/*.md をコードと一緒にコミットしてください。ドキュメントや CI だけの変更ではメモは不要です。

  1. 変更メモを含む PR を main にマージする。
  2. Actions が chore: release tts という PR を作成・更新する。CHANGELOG への追記と、package.json・package-lock.json・.claude-plugin/plugin.json のバージョン更新がまとまります。
  3. 内容を確認してリリース用 PR をマージする。利用者は claude plugin update tts と /reload-plugins で更新できます。

最初に GitHub リポジトリの Settings → Actions → General → Workflow permissions で Allow GitHub Actions to create and approve pull requests を有効にしてください(Changesets の設定手順)。標準の GITHUB_TOKEN を使うため、追加のトークンは不要です。自動作成された PR の CI が承認待ちになった場合は、PR 画面の Approve workflows to run で実行を承認してください(GitHub の仕様)。

手元でリリース差分を生成する場合は npm run release:version、バージョンの整合性確認は npm run check:version を使います。履歴の生成時はプラグイン側も同期するため、changeset version 単体では実行しません。バージョン管理用の package.json は private: true で、npm 公開や GitHub Release の作成は行いません。

ライセンス

MIT License

Source 19 files
hooks/register.tsx 1251 lines
1import { atom, read, update } from "claude-code"
2import type { EngineInterface, Register } from "claude-code"
3
4import type { EngineState, Picker, Setting, SpeechState, Tts } from "../types"
5
6import { Channel } from "./channel"
7import { type Notices, type ReadMode, type TtsConfig, toConfig } from "./config"
8import { DIALOG_TOOLS, dialogSpeech } from "./dialog-text"
9import {
10  ANSWER_PRIORITY,
11  acquireCommand,
12  FLOOR_LOST,
13  FLOOR_TIMEOUT,
14  FLOOR_YIELDED,
15  floorOutcome,
16  guardedPlayCommand,
17  heartbeatCommand,
18  NOTICE_PRIORITY,
19  releaseCommand,
20  STREAM_PRIORITY,
21} from "./floor"
22import { type EngineName, ENGINES, type LoadedEngine, type Step } from "./engines"
23import { type Pin, PINS_KEY, type Pins, pinnedOptions, toPins } from "./pins"
24import { lastAnswer, replayBlocks, replayOptions } from "./replay"
25import { removeDirectoryCommand, removeFilesCommand, tempDirectoryCommand } from "./platform"
26import {
27  canStream,
28  findPlayerCommand,
29  isStreamFailed,
30  isStreamRefused,
31  isStreamSynthesized,
32  playCommand,
33  prepareAudioCommand,
34  streamPlayCommand,
35} from "./player"
36import { SpeechProcess } from "./process"
37import { type Change, MODE_LABELS, MODES, optionLine, planChange, SPEEDS, VOLUMES } from "./settings"
38import { SUMMARY_PROMPT, SummaryFilter, summaryOf } from "./summary"
39import { capLength, QUOTE_ENDED, QUOTED, SKIPPED_CODE, SKIPPED_TABLE, type Spoken, SpeechSplitter, toSentences } from "./speech-text"
40
41const HELP = [
42  "/tts                   state: on/off, mode, engine, speed, volume",
43  "/tts on | off          read replies aloud or not",
44  "/tts stop              stop speech and mute the rest of this turn",
45  "/tts test [text]       read a test sentence",
46  "/tts replay            read the last answer again, whole",
47  "/tts replay select     pick a recent block of the conversation and read it whole",
48  "/tts mode [name]       stream | final | notify; no name opens a picker",
49  "/tts summary [on|off]  read only the summary line a long answer opens with",
50  "/tts engine [name]     switch engines; no name checks whether each one answers",
51  "/tts voice [id]        pick a voice; no id opens a picker",
52  "/tts speed [n]         speech speed (1: as is, Irodori: 0.25–4); no value opens a picker",
53  "/tts volume [n]        playback volume (1: as is); no value opens a picker",
54  "/tts pin | unpin       keep this directory's engine and voice apart from the rest, or stop",
55  "/tts config            every setting and its value; change them in /config → tts",
56  "/tts help              this list",
57].join("\n")
58/** Which notice notify mode says as a turn ends; an interrupted turn stays silent. */
59const TURN_NOTICES: Partial<Record<string, keyof Notices>> = { answer: "done", error: "error", refusal: "refusal" }
60const PICKER_PANE = "tts-picker"
61// Claude Code refuses a Select with more than 64 options.
62const PICKER_PAGE_SIZE = 64
63const picker = atom({ plugin: "tts", key: "picker" } as const, null as Picker | null)
64// Survives a reload so the next module can remove the old module's audio files.
65const audioDirectory = atom({ plugin: "tts", key: "audioDirectory" } as const, null as string | null)
66// Survives a reload so the next module holds the floor the last one held.
67const floorId = atom({ plugin: "tts", key: "floorId" } as const, null as string | null)
68// Published for other mods to show; this mod only writes them.
69const speechState = atom({ plugin: "tts", key: "speech" } as const, { state: "idle", text: null } as SpeechState)
70const engineState = atom({ plugin: "tts", key: "engine" } as const, { name: "", voice: "", status: "checking" } as EngineState)
71
72/** Irodori runs diffusion with a concurrency of 1, so one request can take minutes. */
73const SYNTH_TIMEOUT_MS = 300_000
74/** Refusals in a row, each followed by a file the engine read, after which an engine is not asked to stream again. */
75const STREAM_REFUSALS = 2
76/** How often a session holding the floor while it synthesizes says it is still there. */
77const FLOOR_HEARTBEAT_MS = 10_000
78/** How often a session holding the floor between clips looks for a session waiting with something more urgent. */
79const FLOOR_YIELD_CHECK_MS = 2_000
80/** A last sentence longer than this is not said after the cut: a long line without a stop is no question. */
81const MAX_TAIL = 300
82
83/**
84 * How much of one model response has been queued; past the limit the rest is dropped,
85 * save its last sentence (`tail`), which `finishResponse` says: it often asks what to do next.
86 */
87type Budget = Origin & {
88  spoken: number
89  isCut: boolean
90  /** The last sentence past the limit, and the quote notice said before it. */
91  tail?: { text: string; quote: string }
92  /** The quote notice still to be said before what comes next in the quote. */
93  lead?: string
94}
95
96/** Where speech comes from: the streamed response (`step`), and its priority on the floor shared with other sessions. */
97type Origin = { step?: number; priority: number }
98const NOTICE: Origin = { priority: NOTICE_PRIORITY }
99
100/** `cacheAs` keeps the synthesized clip at that path for the next time; `seq` numbers speech in the order queued. */
101type Sentence = Origin & { text: string; generation: number; seq: number; cacheAs?: string }
102/**
103 * `source` writes the clip's speech to stdout, played as it comes; should the engine refuse to
104 * stream, the clip is synthesized to `file` instead.
105 */
106type Clip = Origin & { text: string; file: string; generation: number; seq: number; isCached?: boolean; source?: Source }
107/**
108 * `engine` is the one asked: a refusal is its, whatever is in use by then. `finish` frees the engine
109 * for the next sentence once the stream is synthesized, or the clip is done with.
110 */
111type Source = { argv: string[]; stdin?: string; engine: LoadedEngine; finish: () => void }
112
113export const register: Register = (on, options) => {
114  let isWindows = false
115  let config = toConfig(options)
116  let engine = ENGINES[config.engine].load(options)
117  let fallback = config.fallback === undefined ? undefined : ENGINES[config.fallback].load(options)
118  // The working directory's pin, if any, lays its engine and voice over the options.
119  let cwd = ""
120  let pins: Pins = {}
121
122  // `generation` moves on at every stop: queued work of an older one is dropped.
123  let generation = 0
124  let isTurnMuted = false
125  // The main loop's responses, counted in every mode; `$.tts` stopping drops the one streaming then,
126  // so a turn whose answer is that response does not read it at its end.
127  let responseCount = 0
128  let stoppedResponse = -1
129  // Streamed responses are numbered from 1; `unplayed` counts each one's speech not yet played or
130  // dropped, under 0 for speech of no response.
131  let stepCount = 0
132  // The responses turns' answers came in: their clips are said with the answer's priority.
133  const answerSteps = new Set<number>()
134  // Responses that ended calling a tool: their text is known to come before a tool call as soon as they end.
135  const toolSteps = new Set<number>()
136  // The first response of this turn: an earlier turn's speech is never cut off as text before the answer.
137  let turnFirstStep = 1
138  const unplayed = new Map<number, number>()
139  let seq = 0
140  // Stream clips queued up to this `seq` are dropped: one of them waited past the limit for the floor.
141  let quietThrough = 0
142  // Called once nothing is left to play: a session holding the floor gives it up.
143  let onAllPlayed = () => {}
144  // Set by session.start: publishes that nothing is left to say.
145  let onIdle = () => {}
146  // Set by session.start: writes the published state again after /clear, resume or /branch reset it.
147  let republishState = () => {}
148  const track = (origin: Origin) => {
149    const key = origin.step ?? 0
150    unplayed.set(key, (unplayed.get(key) ?? 0) + 1)
151    return ++seq
152  }
153  const settle = (origin: Origin) => {
154    const key = origin.step ?? 0
155    const count = (unplayed.get(key) ?? 1) - 1
156    if (count > 0) unplayed.set(key, count)
157    else unplayed.delete(key)
158    if (unplayed.size === 0) {
159      onAllPlayed()
160      onIdle()
161    }
162  }
163  const priorityOf = (clip: Origin) => (clip.step !== undefined && answerSteps.has(clip.step) ? ANSWER_PRIORITY : clip.priority)
164  // Stream text is known to come before a tool call once a later response starts: only then does it wait within the limit.
165  // The response still streaming may turn out to be the answer, which is never dropped.
166  const isBeforeTool = (clip: Clip) =>
167    priorityOf(clip) === STREAM_PRIORITY &&
168    clip.step !== undefined &&
169    // Only within this turn: an earlier turn's last response (one that ended in an error, say) is no text before a tool call.
170    ((clip.step >= turnFirstStep && clip.step < stepCount) || toolSteps.has(clip.step))
171  const waitLimitOf = (clip: Clip) => (isBeforeTool(clip) ? config.maxWaitSeconds : 0)
172  // Names this session on the floor; kept across a reload in `floorId`.
173  let floorName = Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
174  let releaseFloor = async () => {}
175  // Restarts a wait for the floor whose clip now has another priority or limit (it became the answer,
176  // or a later response showed it comes before a tool call).
177  let refreshWait = () => {}
178  const { isEnabled } = config
179  let player: string | undefined
180  const synthesisProcess = new SpeechProcess()
181  const playbackProcess = new SpeechProcess()
182  const floorProcess = new SpeechProcess()
183  const sentences = new Channel<Sentence>()
184  // The sentence being synthesized: the next clip to play, whose priority a holder between clips yields by.
185  let synthesizing: Sentence | undefined
186  const clips = new Channel<Clip>()
187  // Clips queued and not yet played or dropped: a sentence streams only when none of them is live.
188  const ahead = new Set<Clip>()
189  const queueClip = (clip: Clip) => {
190    ahead.add(clip)
191    clips.push(clip)
192  }
193  // Notices are few and fixed: each is synthesized once per load, then replayed at once.
194  const cachedNotices = new Map<string, string>()
195  let directory = ""
196  // Set as session.end begins, before its teardown is awaited; cleared once /clear, resume or /branch brings a directory back.
197  let isEnded = false
198  let noticeCount = 0
199  // Set while the engine in use fails ("voicevox down"); shown beside playback until it reads again.
200  let engineIssue: string | undefined
201  // Set by a sentence that could not be read; shown as "失敗" beneath an engine issue, cleared once a clip plays.
202  let isFailed = false
203  // The blocks `/tts replay select` last offered; a pick names one by its index.
204  let replayChoices: string[] = []
205  // Set by session.start: probes the engine in use and shows the result.
206  let recheckEngine = () => {}
207  // The engine that answered streams with no WAV and files with one: it is not asked to stream again.
208  // Loaded anew by a switch or a pin, an engine is asked again.
209  let refusedStream: LoadedEngine | undefined
210  // Refusals since the engine last streamed: one alone may be an error of the moment.
211  let streamRefusals = { engine: undefined as LoadedEngine | undefined, count: 0 }
212
213  /** Rebuilds the engines from the options with this directory's pin laid over them. */
214  const applyPins = (stored: Pins) => {
215    pins = stored
216    const effective = pinnedOptions(options, pins[cwd])
217    config = toConfig(effective)
218    engine = ENGINES[config.engine].load(effective, isWindows)
219    fallback = config.fallback === undefined ? undefined : ENGINES[config.fallback].load(effective, isWindows)
220    // Cached notices were spoken in the voice before.
221    cachedNotices.clear()
222    recheckEngine()
223  }
224
225  /** What saving `value` for `setting` changes, against the settings in effect here. */
226  const changeOf = (setting: Setting, value: string) => planChange(setting, value, { options, config, engine, cwd, pin: pins[cwd] })
227
228  /** Invalidates queued speech and closes the active synthesis and playback streams. */
229  const stop = async () => {
230    generation += 1
231    // Shown at once: what was queued is cleaned up after, which can take seconds.
232    onIdle()
233    await Promise.all([synthesisProcess.stop(), playbackProcess.stop(), floorProcess.stop()])
234  }
235
236  /** Stops as `stop` does, and drops the response streaming now: unlike `/tts stop`, the turn's later responses are read. */
237  const stopResponse = () => {
238    stoppedResponse = responseCount
239    return stop()
240  }
241
242  /** Queues `text` to be said next; called right after a stop, it plays first. */
243  const queueNotice = (text: string) => {
244    if (text === "") return
245    const cached = cachedNotices.get(text)
246    if (cached !== undefined) return queueClip({ ...NOTICE, text, file: cached, generation, seq: track(NOTICE), isCached: true })
247    sentences.push({ ...NOTICE, text, generation, seq: track(NOTICE), cacheAs: `${directory}/notice-${noticeCount++}.wav` })
248  }
249
250  /** Queues `text` for synthesis, in pieces an engine takes. */
251  const say = (text: string, origin: Origin) => {
252    if (text === "") return
253    const { step, priority } = origin
254    for (const piece of capLength(text)) sentences.push({ text: piece, generation, step, priority, seq: track(origin) })
255  }
256
257  /**
258   * Queues sentences; with a budget, stops before the sentence that would pass the limit
259   * (never reading half of one) and says once that the rest is skipped.
260   */
261  const enqueue = (spoken: readonly Spoken[], budget?: Budget) => {
262    const origin = budget ?? NOTICE
263    // The quote notice, joined to what is said next in the quote: "引用、" and its first sentence.
264    // It waits across calls, as a streamed quote may come in pieces, until said or the quote ends.
265    const quoting: { lead?: string } = budget ?? {}
266    for (const text of spoken) {
267      if (text === QUOTED || text === QUOTE_ENDED) {
268        quoting.lead = text === QUOTED ? config.notices.quote : undefined
269        continue
270      }
271      // The code and table notices are the mod's, not the response's: they use no budget and are never the last sentence.
272      if (text === SKIPPED_CODE || text === SKIPPED_TABLE) {
273        const notice = text === SKIPPED_CODE ? config.notices.code : config.notices.table
274        if (budget?.isCut !== true && notice !== "") {
275          say((quoting.lead ?? "") + notice, origin)
276          quoting.lead = undefined
277        }
278        continue
279      }
280      const quote = quoting.lead ?? ""
281      if (budget !== undefined && config.maxCharsPerTurn > 0) {
282        const length = Array.from(text).length
283        if (!budget.isCut && budget.spoken + length > config.maxCharsPerTurn) {
284          budget.isCut = true
285          say(config.notices.cut, origin)
286        }
287        // Each skipped sentence may be the last, so the one that passes the limit counts too.
288        // The quote notice stays for the quote's later sentences, any of which may be the last.
289        if (budget.isCut) {
290          budget.tail = { text, quote }
291          continue
292        }
293        budget.spoken += length
294      }
295      say(quote + text, origin)
296      quoting.lead = undefined
297    }
298  }
299
300  /** Whether `enqueue` says something for `text`: quote marks say nothing alone, and a skip only its notice when set. */
301  const isSpoken = (text: Spoken) => {
302    if (text === QUOTED || text === QUOTE_ENDED) return false
303    if (text === SKIPPED_CODE) return config.notices.code !== ""
304    if (text === SKIPPED_TABLE) return config.notices.table !== ""
305    return true
306  }
307
308  /** Whether sentences of a streamed response before `step` are still to be played. */
309  // Responses whose speech is dropped, the rest playing on: the current turn's, giving way to its answer read whole.
310  const skippedSteps = new Set<number>()
311  /** Whether queued speech is still to be said: no stop since, and not of a response given way. */
312  const isLive = (item: Origin & { generation: number }) =>
313    item.generation === generation && !(item.step !== undefined && skippedSteps.has(item.step))
314  // The clip playing or waiting for the floor.
315  let playing: Clip | undefined
316
317  /** Drops the current turn's streamed speech, an earlier turn's answer still playing on, and cuts off what of it is under way. */
318  const skipTurnSpeech = async () => {
319    for (let step = turnFirstStep; step <= stepCount; step++) skippedSteps.add(step)
320    const cuts: Promise<void>[] = []
321    if (synthesizing !== undefined && !isLive(synthesizing)) cuts.push(synthesisProcess.stop())
322    if (playing !== undefined && !isLive(playing)) cuts.push(playbackProcess.stop(), floorProcess.stop())
323    await Promise.all(cuts)
324  }
325
326  const hasUnplayedBefore = (step: number) => [...unplayed.keys()].some(earlier => earlier >= turnFirstStep && earlier < step)
327
328  /** What of a turn's answer is read: its summary line when it opens with one and the setting is on. */
329  const answerText = (answer: string) => (config.summary ? summaryOf(answer) : undefined) ?? answer
330
331  /** Reads `text` again from the start, whole: whatever is being read stops. */
332  const replay = async (text: string) => {
333    await stop()
334    enqueue(toSentences(text))
335  }
336
337  /** Ends a response: past the limit, says its last sentence after the cut notice. */
338  const finishResponse = (budget: Budget) => {
339    // The tail keeps its quote notice, which, like every notice, its length does not count.
340    if (budget.tail !== undefined && Array.from(budget.tail.text).length <= MAX_TAIL) say(budget.tail.quote + budget.tail.text, budget)
341    budget.tail = undefined
342  }
343
344  // Another mod has this session speak through `$.tts`, as a `/tts` command would: first among sessions, in any mode.
345  on("engine.create", async ($, e, next) => {
346    const built = await next(e)
347    const tts: Tts = {
348      speak: async ({ text, interrupt }) => {
349        if (!isEnabled) return { isQueued: false, reason: "off" }
350        // Speech asked for before the session starts waits for it; once it is ending, its directory is being removed.
351        if (isEnded) return { isQueued: false, reason: "ended" }
352        const texts = toSentences(text)
353        if (!texts.some(isSpoken)) return { isQueued: false, reason: "empty" }
354        // Queued before the stop is awaited: a later call made meanwhile is said after this one, not before.
355        const stopped = interrupt === true ? stopResponse() : undefined
356        enqueue(texts)
357        await stopped
358        return { isQueued: true }
359      },
360      stop: () => stopResponse(),
361    }
362    return { ...built, tts }
363  })
364
365  on("session.start", async ($, e, next) => {
366    const started = await next(e)
367    isWindows = (await $.env.get("OS")) === "Windows_NT"
368    cwd = await $.session.cwd()
369    applyPins(toPins(await $.store.get(PINS_KEY)))
370    player = config.player === "auto" ? (await $.process.run(findPlayerCommand(isWindows))).stdout.trim() || undefined : config.player
371    if (player === undefined) $.ui.toast("tts: no audio player found (ffplay, paplay, aplay, afplay, powershell.exe)")
372
373    directory = await prepareDirectory($, isWindows)
374    const inheritedFloorName = await read($, floorId)
375    floorName = inheritedFloorName ?? floorName
376    await update($, floorId, () => floorName)
377    // A reloaded module knows nothing of a floor the last one held, and would neither heartbeat nor release it:
378    // give it back now rather than make other sessions wait for it to go stale.
379    if (inheritedFloorName !== null) await $.process.run(releaseCommand(isWindows, floorName)).catch(() => undefined)
380    let clipCount = 0
381
382    // Counts what was learned of the engine: a check whose answer comes after a later synthesis is stale.
383    let engineNews = 0
384    const noteEngine = (error?: unknown) => {
385      engineNews += 1
386      const issue = error === undefined ? undefined : `${config.engine} ${/is not set/.test(String(error)) ? "unset" : "down"}`
387      showEngineIssue(issue)
388      if (issue === undefined) publishEngine("ok")
389    }
390    // The status line shows only a failure; Claude Code draws it as "⚠ tts: voicevox down", or "⚠ tts: 失敗" with the engine up.
391    let shownStatus: string | undefined
392    const showStatus = () => {
393      const status = engineIssue ?? (isFailed ? "失敗" : undefined)
394      if (status === shownStatus) return
395      shownStatus = status
396      $.ui.status(status)
397    }
398    const showEngineIssue = (issue: string | undefined) => {
399      if (issue === engineIssue) return showStatus()
400      engineIssue = issue
401      showStatus()
402      if (issue !== undefined) publishEngine(/unset$/.test(issue) ? "unset" : "down")
403    }
404    // Published one write after another: a slow write never lands after the one that followed it.
405    let stateWrites = Promise.resolve()
406    const publish = (write: () => Promise<unknown>) => {
407      stateWrites = stateWrites.then(write).then(() => undefined, () => undefined)
408    }
409    // Published as it changes, like the speech below.
410    let shownEngine = ""
411    const publishEngine = (status: EngineState["status"]) => {
412      const published: EngineState = { name: config.engine, voice: engine.voice, status }
413      const key = JSON.stringify(published)
414      if (key === shownEngine) return
415      shownEngine = key
416      publish(() => update($, engineState, () => published))
417    }
418    // Published as it changes; the same state twice is written once.
419    let shownSpeech = ""
420    let lastSpeech: SpeechState = { state: "idle", text: null }
421    const publishSpeech = (speech: SpeechState) => {
422      lastSpeech = speech
423      const key = JSON.stringify(speech)
424      if (key === shownSpeech) return
425      shownSpeech = key
426      publish(() => update($, speechState, () => speech))
427    }
428    onIdle = () => publishSpeech({ state: "idle", text: null })
429    publishSpeech({ state: "idle", text: null })
430    // The last module's line stays after a reload.
431    $.ui.status(undefined)
432
433    // The fallback reads on quietly: the status line says the engine is failing.
434    const reportFallback = (error: unknown) => {
435      $.ui.log(`tts: ${config.engine} failed, read with ${config.fallback}: ${String(error)}`, { to: "debug" })
436    }
437
438    // No toast: an engine stopped on purpose fails every sentence. The status line says so; the debug log says why.
439    const reportError = (error: unknown) => {
440      const message = error instanceof Error ? error.message : String(error)
441      $.ui.log(`tts: ${message}`, { to: "debug" })
442      isFailed = true
443      showStatus()
444    }
445
446    /**
447     * Synthesizes `speech` to `file`, with the fallback should the engine in use fail; true when the fallback read it.
448     * `failed` is the engine's failure already met for this speech: the fallback reads at once, not after another.
449     */
450    const render = async (speech: Origin & { text: string; generation: number }, file: string, process: SpeechProcess, failed?: { error: unknown }) => {
451      const isCurrent = () => isLive(speech)
452      // A result of the engine before a switch says nothing of the one in use now.
453      const used = engine
454      try {
455        if (failed !== undefined) throw failed.error
456        await synthesize($, process, engine, speech.text, file, isCurrent)
457        if (isCurrent() && used === engine) noteEngine()
458        return false
459      } catch (error) {
460        if (isCurrent() && used === engine) noteEngine(error)
461        if (!isCurrent() || fallback === undefined || config.fallback === undefined) throw error
462        await synthesize($, process, fallback, speech.text, file, isCurrent)
463        reportFallback(error)
464        return true
465      }
466    }
467
468    /**
469     * What plays `sentence` as the engine synthesizes it, once what comes before (VOICEVOX's audio query)
470     * has run; undefined where the engine or the player cannot stream: a file is tried then. Throws what the
471     * engine in use failed with, which a file would fail with too.
472     */
473    const prepareStream = async (sentence: Sentence): Promise<Omit<Source, "finish"> | undefined> => {
474      const used = engine
475      if (used.stream === undefined || used === refusedStream || player === undefined || !canStream(player, isWindows)) return undefined
476      try {
477        const steps = used.stream(sentence.text)
478        const last = steps.at(-1)
479        if (last === undefined) return undefined
480        const stdout = await runSteps($, synthesisProcess, steps.slice(0, -1), () => isLive(sentence))
481        return { argv: last.argv, stdin: typeof last.stdin === "function" ? last.stdin(stdout) : last.stdin, engine: used }
482      } catch (error) {
483        // An engine switched from meanwhile is not the one a file is asked of.
484        if (used !== engine) return undefined
485        throw error
486      }
487    }
488
489    // Synthesis runs ahead of playback, one request at a time: a stream handed to playback is one until synthesized.
490    let streamed = Promise.resolve()
491    void (async () => {
492      for (;;) {
493        const sentence = await sentences.take()
494        await streamed
495        if (!isLive(sentence)) {
496          settle(sentence)
497          continue
498        }
499        synthesizing = sentence
500        // Nothing live waiting or playing: the next sentence is being synthesized, which can take minutes.
501        // Queued clips are not counted: ones given way to stay queued, and a live one is taken at once.
502        if (playing === undefined || !isLive(playing)) publishSpeech({ state: "preparing", text: null })
503        const file = sentence.cacheAs ?? `${directory}/${String(clipCount++).padStart(6, "0")}.wav`
504        const isCurrent = () => isLive(sentence)
505        const { generation: clipGeneration, step, priority, seq } = sentence
506        let isHandedOff = false
507        try {
508          // With nothing before it to play, a sentence plays as it is synthesized; after others, it is synthesized
509          // while they play. A notice is kept as a file to say again.
510          const isFirst = ![...ahead].some(isLive)
511          let source: Omit<Source, "finish"> | undefined
512          let failed: { error: unknown } | undefined
513          if (isFirst && sentence.cacheAs === undefined) source = await prepareStream(sentence).catch((error: unknown) => {
514            failed = { error }
515            return undefined
516          })
517          if (!isCurrent()) continue
518          if (source !== undefined) {
519            let finish = () => {}
520            streamed = new Promise(resolve => {
521              finish = resolve
522            })
523            queueClip({ text: sentence.text, file, generation: clipGeneration, step, priority, seq, source: { ...source, finish } })
524            isHandedOff = true
525            continue
526          }
527          const isFallback = await render(sentence, file, synthesisProcess, failed)
528          if (!isCurrent()) {
529            await $.process.run(removeFilesCommand([file], isWindows))
530            continue
531          }
532          // Done while the clip before plays; an untrimmed clip still plays.
533          await runProcess($, synthesisProcess, prepareAudioCommand(file, player, isWindows), undefined, 30_000).catch(() => undefined)
534          if (!isCurrent()) {
535            await $.process.run(removeFilesCommand([file, `${file}.t.wav`], isWindows))
536            continue
537          }
538          // A notice the fallback read is kept for this time only: the engine may be back next time.
539          const isCached = sentence.cacheAs !== undefined && !isFallback
540          if (isCached) cachedNotices.set(sentence.text, file)
541          queueClip({ text: sentence.text, file, generation: clipGeneration, step, priority, seq, isCached })
542          isHandedOff = true
543        } catch (error) {
544          await $.process.run(removeFilesCommand([file], isWindows))
545          if (isCurrent()) reportError(error)
546        } finally {
547          synthesizing = undefined
548          if (!isHandedOff) settle(sentence)
549        }
550      }
551    })()
552
553    // One session plays at a time: the floor is a lock all sessions on this machine share.
554    let isHoldingFloor = false
555    // Set when the floor cannot be used (no sh, an unwritable temporary folder): play alone, as before.
556    let isFloorBroken = false
557    // The clip waiting for the floor with the priority it waits with and whether within a limit, and whether that wait is restarted.
558    let waiting: { clip: Clip; priority: number; isLimited: boolean } | undefined
559    let isRewaiting = false
560    refreshWait = () => {
561      if (waiting === undefined || isRewaiting) return
562      const { clip, priority, isLimited } = waiting
563      if (priorityOf(clip) === priority && waitLimitOf(clip) > 0 === isLimited) return
564      isRewaiting = true
565      void floorProcess.stop()
566    }
567
568    // Releases and heartbeats run one at a time: a heartbeat never writes the floor back after a release.
569    let floorOps = Promise.resolve()
570    const floorOp = (op: () => Promise<void>) => {
571      const run = floorOps.then(op)
572      floorOps = run.catch(() => undefined)
573      return run
574    }
575    releaseFloor = () => floorOp(async () => {
576      if (!isHoldingFloor) return
577      isHoldingFloor = false
578      await $.process.run(releaseCommand(isWindows, floorName)).catch(() => undefined)
579    })
580    // Removes a floor a wait killed mid-way may have taken; one this session does not hold is left alone.
581    const giveBackFloor = () => floorOp(async () => {
582      await $.process.run(releaseCommand(isWindows, floorName)).catch(() => undefined)
583    })
584    // The priority of the clip played last; between clips, the floor goes to a session waiting with one above
585    // the next clip's, the sentence being synthesized.
586    let heldPriority = STREAM_PRIORITY
587    const heartbeat = (canYield = false) => floorOp(async () => {
588      if (!isHoldingFloor) return
589      const beat = await $.process.run(heartbeatCommand(isWindows, floorName, canYield ? (synthesizing === undefined ? heldPriority : priorityOf(synthesizing)) : undefined)).catch(() => undefined)
590      if (beat?.exitCode === FLOOR_LOST || beat?.exitCode === FLOOR_YIELDED) isHoldingFloor = false
591    })
592
593    /** Keeps the floor while more of this session's speech is coming, so no other session cuts in; gives it up once none is. */
594    const holdFloor = async () => {
595      while (isHoldingFloor && clips.size === 0) {
596        if (unplayed.size === 0) return releaseFloor()
597        let timer: { cancel: () => void } | undefined
598        const isBeat = await Promise.race([
599          clips.ready().then(() => false),
600          new Promise<boolean>(resolve => {
601            onAllPlayed = () => resolve(false)
602            timer = $.clock.after(FLOOR_YIELD_CHECK_MS, () => resolve(true))
603          }),
604        ])
605        onAllPlayed = () => {}
606        timer?.cancel()
607        // While the next clip is synthesized, which can take minutes, a more urgent session goes first.
608        if (isBeat && clips.size === 0 && unplayed.size > 0) await heartbeat(true)
609      }
610    }
611
612    /** Heartbeats while `playing` runs: a clip longer than the stale limit does not lose the floor. */
613    const keepFloor = async <T,>(playing: Promise<T>): Promise<T> => {
614      let isPlaying = true
615      let timer: { cancel: () => void } | undefined
616      const schedule = () => {
617        timer = $.clock.after(FLOOR_HEARTBEAT_MS, () => {
618          void heartbeat().then(() => {
619            if (isPlaying) schedule()
620          })
621        })
622      }
623      schedule()
624      try {
625        return await playing
626      } finally {
627        isPlaying = false
628        timer?.cancel()
629      }
630    }
631
632    /**
633     * Synthesizes to its file a clip queued to stream, holding the floor meanwhile; true when the fallback read it.
634     * Undefined when a stop left it unread.
635     */
636    const readFile = async (clip: Clip, source: Source, player: string) => {
637      const isFallback = await keepFloor(render(clip, clip.file, playbackProcess))
638      // The engine is done with the clip: the next sentence is synthesized while it plays.
639      source.finish()
640      if (!isLive(clip)) return undefined
641      await runProcess($, playbackProcess, prepareAudioCommand(clip.file, player, isWindows), undefined, 30_000).catch(() => undefined)
642      return isFallback
643    }
644
645    /** Reads from its file a clip whose engine refused to stream. An engine that refuses again and reads that too is not asked to stream again. */
646    const readInstead = async (clip: Clip, source: Source, player: string) => {
647      // A stop leaves the file unread: that says nothing of the engine.
648      const isFallback = await readFile(clip, source, player)
649      if (isFallback !== false || source.engine !== engine) return
650      const count = streamRefusals.engine === engine ? streamRefusals.count + 1 : 1
651      streamRefusals = { engine, count }
652      if (count >= STREAM_REFUSALS) refusedStream = engine
653    }
654
655    /** Notes what a stream that played says of its engine: a source that failed partway is an error, as a failed synthesis is. */
656    const noteStream = (clip: Clip, source: Source, played: { code: number | null; stderr: string }) => {
657      if (!isLive(clip)) return
658      const isEngineInUse = source.engine === engine
659      if (played.code === 0) {
660        if (!isEngineInUse) return
661        streamRefusals = { engine, count: 0 }
662        return noteEngine()
663      }
664      if (!isStreamFailed(played.code, played.stderr)) return
665      const error = new Error(`${config.engine} stream failed partway (exit ${played.code})`)
666      if (isEngineInUse) noteEngine(error)
667      reportError(error)
668    }
669
670    /** Plays `clip` on the floor; drops it instead when it is stream text that waited past the limit. */
671    const playClip = async (clip: Clip, player: string) => {
672      // Cleared once the engine refuses to stream: the clip is read from its file then.
673      let source = clip.source
674      // When a limited wait gives up: kept across waits again after a handover, so the limit is one in all.
675      let deadline: number | undefined
676      for (;;) {
677        if (!isLive(clip)) return
678        // The player was changed since the clip was queued to stream, to one that cannot.
679        if (source !== undefined && !canStream(player, isWindows)) {
680          await readFile(clip, source, player)
681          source = undefined
682          continue
683        }
684        const play = source === undefined
685          ? playCommand(player, clip.file, config.volume, isWindows)
686          : streamPlayCommand(clip.file, config.volume, source.argv, SYNTH_TIMEOUT_MS / 1000)
687        const input = source?.stdin
688        const finish = source?.finish
689        const onStderr = finish === undefined ? undefined : (stderr: string) => isStreamSynthesized(stderr) && finish()
690        const priority = priorityOf(clip)
691        if (isBeforeTool(clip) && clip.seq <= quietThrough) return
692        // Played alone where the floor is not used: no wait, no guard.
693        const isAlone = isFloorBroken || !config.sharePlayback
694        if (!isAlone && !isHoldingFloor) {
695          // Only text before a tool call waits within a limit: a notice or an answer is never dropped.
696          const now = await $.clock.now()
697          if (waitLimitOf(clip) === 0) deadline = undefined
698          else deadline ??= now + waitLimitOf(clip) * 1000
699          const limit = deadline === undefined ? 0 : (deadline - now) / 1000
700          if (deadline !== undefined && limit <= 0) {
701            quietThrough = seq
702            return
703          }
704          waiting = { clip, priority, isLimited: deadline !== undefined }
705          publishSpeech({ state: "waiting", text: clip.text })
706          const waited = await floorProcess.read($.process.spawn({ argv: acquireCommand(isWindows, floorName, priority, limit) }))
707          waiting = undefined
708          // Cleared on every way out, a stop's included: a flag left set would keep later waits from restarting.
709          const isRestarted = isRewaiting
710          isRewaiting = false
711          // A wait cancelled just as it took the floor still holds it: it is given up once nothing is left to say.
712          if (waited.code === 0) isHoldingFloor = true
713          // A stop cancels the wait along with the clip; one killed mid-way may have taken the floor, so give it back.
714          if (!isLive(clip)) {
715            if (waited.code !== 0) await giveBackFloor()
716            return
717          }
718          // The clip's priority or limit changed: wait again with the new ones.
719          if (isRestarted) continue
720          if (waited.code === FLOOR_TIMEOUT) {
721            quietThrough = seq
722            return
723          }
724          if (waited.code !== 0) {
725            isFloorBroken = true
726            $.ui.log(`tts: playback is not shared with other sessions: ${(waited.stderr || `exit ${waited.code}`).trim().slice(0, 200)}`, { to: "debug" })
727            await giveBackFloor()
728            continue
729          }
730        }
731        if (!isAlone) heldPriority = priority
732        publishSpeech({ state: "playing", text: clip.text })
733        const argv = isAlone ? play : guardedPlayCommand(isWindows, floorName, priority, play)
734        const played = await keepFloor(playbackProcess.read($.process.spawn({ argv, input }), onStderr))
735        // Handed to a session with something more urgent, or lost as stale: wait for the floor again.
736        if (!isAlone && floorOutcome(played.code, played.stderr) !== undefined) {
737          isHoldingFloor = false
738          continue
739        }
740        // Cleared by a clip heard, not by one synthesized: synthesis runs ahead of playback.
741        if (played.code === 0 && isFailed) {
742          isFailed = false
743          showStatus()
744        }
745        if (source === undefined) return
746        if (!isStreamRefused(played.code, played.stderr)) return noteStream(clip, source, played)
747        await readInstead(clip, source, player)
748        source = undefined
749      }
750    }
751
752    void (async () => {
753      for (;;) {
754        await holdFloor()
755        const clip = await clips.take()
756        if (isLive(clip) && player !== undefined) {
757          playing = clip
758          try {
759            await playClip(clip, player)
760          } catch (error) {
761            if (isLive(clip)) reportError(error)
762          } finally {
763            playing = undefined
764          }
765        }
766        ahead.delete(clip)
767        clip.source?.finish()
768        // Published before the files are removed, which can take seconds (PowerShell on Windows).
769        // Counted by speech, not by response: one response's sentences share a key.
770        // A clip given way to (not one a stop dropped) leaves the answer that replaces it being synthesized.
771        if (clip.generation === generation) {
772          const isMore = [...unplayed.values()].reduce((sum, count) => sum + count, 0) > 1
773          publishSpeech(isMore ? { state: "preparing", text: null } : { state: "idle", text: null })
774        }
775        // A clip read from its file after all may have been stopped while trimmed.
776        const files = [`${clip.file}.v.wav`, ...(clip.source === undefined ? [] : [`${clip.file}.t.wav`])]
777        if (clip.isCached !== true) files.push(clip.file)
778        await $.process.run(removeFilesCommand(files, isWindows))
779        settle(clip)
780      }
781    })()
782
783    // Checked at once, so a start or an engine switch shows a dead engine before anything is read.
784    recheckEngine = () => {
785      isFailed = false
786      showEngineIssue(undefined)
787      if (!isEnabled) return publishEngine("off")
788      publishEngine("checking")
789      const checked = engine
790      const news = ++engineNews
791      void checkEngine($, checked).then(state => {
792        if (checked !== engine || news !== engineNews) return
793        if (state === "ok") publishEngine("ok")
794        else showEngineIssue(`${config.engine} ${state}`)
795      })
796    }
797    republishState = () => {
798      shownSpeech = ""
799      shownEngine = ""
800      publishSpeech(lastSpeech)
801      recheckEngine()
802    }
803    recheckEngine()
804
805    await $.command.register({
806      name: "tts",
807      description: "Read replies aloud: on, off, stop, test, replay, mode, summary, engine, voice, speed, volume, pin, unpin, config, help",
808      argumentHint: "[on|off|stop|test [text]|replay [select]|mode|summary [on|off]|engine|voice|speed|volume [value]|pin|unpin|config|help]",
809      // `/tts stop` has to land while a reply is still being read.
810      immediate: true,
811    })
812    return started
813  })
814
815  on("session.end", async ($, e, next) => {
816    isEnded = true
817    await stop()
818    await releaseFloor()
819    cachedNotices.clear()
820    if (directory !== "") await $.process.run(removeDirectoryCommand(directory, isWindows))
821    directory = ""
822    await update($, audioDirectory, () => null)
823    return next(e)
824  }).catch(($, e, next) => next(e))
825
826  // /clear, resume and /branch keep this module alive without another session.start, and reset
827  // $.state, which holds the directory for the next reload to remove.
828  on("classic.SessionStart", { source: ["clear", "resume", "fork"] }, async ($, e, next) => {
829    if (directory === "") directory = await prepareDirectory($, isWindows)
830    else await update($, audioDirectory, () => directory)
831    isEnded = false
832    await update($, floorId, () => floorName)
833    republishState()
834    return next(e)
835  }).catch(($, e, next) => next(e))
836
837  on("command.run", { command: "tts" }, async ($, e) => {
838    const [action = "", ...rest] = e.args.trim().split(/\s+/)
839    switch (action) {
840      case "on":
841      case "off": {
842        if (action === "off") await stop()
843        const set = await $.config.set({ key: "tts.enabled", value: action === "on" })
844        return { text: "deny" in set && set.deny ? set.deny : action }
845      }
846      case "stop": {
847        isTurnMuted = true
848        await stop()
849        return { text: "stopped" }
850      }
851      case "test": {
852        const text = e.args.trim().replace(/^test(?:\s+|$)/, "") || "読み上げのテストです。"
853        const texts = toSentences(text)
854        if (texts.length === 0) return { text: "no text to read after formatting" }
855        try {
856          engine.synthesis(text, "probe.wav")
857        } catch (error) {
858          if (fallback === undefined) return { text: error instanceof Error ? error.message : String(error) }
859        }
860        enqueue(texts)
861        return { text: `testing ${config.engine} (the first Irodori request loads the model and can take a while)` }
862      }
863      case "replay": {
864        const messages = await $.session.messages()
865        if (rest[0] !== "select") {
866          const answer = lastAnswer(messages)
867          if (answer === undefined) return { text: "no answer to replay yet" }
868          await replay(answer)
869          return { text: "replaying the last answer" }
870        }
871        replayChoices = replayBlocks(messages)
872        const picked = rest[1] === undefined ? undefined : replayChoices[Number(rest[1])]
873        if (picked !== undefined) {
874          await replay(picked)
875          return { text: `replaying block ${rest[1]}` }
876        }
877        const options = replayOptions(replayChoices)
878        if (options.length === 0) return { text: "nothing to replay yet" }
879        if (await openPicker($, { action: "replay", title: "replay (newest first)", options, value: options[0]!.value })) {
880          return { text: "pick a block in the pane (Esc closes it)" }
881        }
882        return { text: ["recent blocks, newest first (/tts replay select <n>):", ...options.map(optionLine)].join("\n") }
883      }
884      case "voice": {
885        const { voices } = engine
886        if (voices === undefined) return { text: `engine=${config.engine} has no voices; set it up in /config` }
887        const voice = rest.join(" ")
888        if (voice === "") {
889          const listed = await $.http.fetch(voices.url)
890          if (!listed.ok) return { text: `GET ${voices.url} failed with ${listed.status}` }
891          const options = voices.parse(listed.text)
892          const title = `${config.engine} voice`
893          if (await openPicker($, { action: "voice", title, options, value: voices.current })) {
894            return { text: "pick a voice in the pane (Esc closes it)" }
895          }
896          return { text: [`${config.engine} voices (/tts voice <id>):`, ...options.map(optionLine)].join("\n") }
897        }
898        return { text: await commit($, changeOf("voice", voice), applyPins) }
899      }
900      case "mode": {
901        const name = rest[0] as ReadMode | undefined
902        if (name === undefined) {
903          const options = MODES.map(mode => ({ value: mode, label: MODE_LABELS[mode] }))
904          if (await openPicker($, { action: "mode", title: "read mode", options, value: config.mode })) {
905            return { text: "pick a mode in the pane (Esc closes it)" }
906          }
907          return { text: `mode: ${config.mode} (${MODES.join(" | ")})` }
908        }
909        return { text: await commit($, changeOf("mode", name), applyPins) }
910      }
911      case "summary": {
912        const value = rest[0]
913        if (value === undefined) return { text: `summary: ${config.summary ? "on" : "off"} (/tts summary on | off)` }
914        if (value !== "on" && value !== "off") return { text: "summary is on or off" }
915        const set = await $.config.set({ key: "tts.summary", value: value === "on" })
916        return { text: "deny" in set && set.deny ? set.deny : `summary: ${config.summary ? "on" : "off"} → ${value}` }
917      }
918      case "speed":
919      case "volume": {
920        const value = rest[0]
921        if (value === undefined) {
922          const current = String(action === "speed" ? options.speed : config.volume)
923          const choices = (action === "speed" ? SPEEDS : VOLUMES).map(each => ({ value: each, label: `× ${each}` }))
924          if (await openPicker($, { action: action, title: action, options: choices, value: current })) {
925            return { text: `pick a ${action} in the pane (Esc closes it)` }
926          }
927          return { text: `${action}: ${current}` }
928        }
929        return { text: await commit($, changeOf(action, value), applyPins) }
930      }
931      case "pin": {
932        const pin: Pin = { engine: config.engine, voices: engine.voices ? { [config.engine]: engine.voices.current } : {} }
933        const stored = { ...toPins(await $.store.get(PINS_KEY)), [cwd]: pin }
934        await $.store.set(PINS_KEY, stored)
935        applyPins(stored)
936        return {
937          text: `pinned ${cwd}: ${config.engine} (${engine.voice})\nengine and voice changes here stay in this directory; /tts unpin undoes it`,
938        }
939      }
940      case "unpin": {
941        if (pins[cwd] === undefined) return { text: "this directory is not pinned" }
942        const before = `${config.engine} (${engine.voice})`
943        const { [cwd]: _unpinned, ...stored } = toPins(await $.store.get(PINS_KEY))
944        await $.store.set(PINS_KEY, stored)
945        applyPins(stored)
946        return { text: `unpinned ${cwd}: ${before} → ${config.engine} (${engine.voice})` }
947      }
948      case "engine": {
949        const name = rest[0]
950        if (name === undefined) {
951          const names = Object.keys(ENGINES) as EngineName[]
952          const rows = await Promise.all(names.map(each => engineRow($, each, ENGINES[each].load(options, isWindows), config)))
953          return { text: ["engines (● answers, ○ down or unset; /tts engine <name> switches):", ...rows].join("\n") }
954        }
955        return { text: await commit($, changeOf("engine", name), applyPins) }
956      }
957      case "help":
958        return { text: HELP }
959      case "config": {
960        const width = Math.max(...Object.keys(options).map(key => key.length))
961        const rows = Object.entries(options).map(([key, value]) => `  ${key.padEnd(width)}  ${JSON.stringify(value)}`)
962        const pinned = pins[cwd] === undefined ? [] : [`engine and voice are pinned here: ${config.engine} (${engine.voice})`]
963        return { text: ["settings (change them in /config → tts):", ...rows, ...pinned].join("\n") }
964      }
965      case "": {
966        const marks = await Promise.all([answerMark($, engine), fallback && answerMark($, fallback)])
967        return {
968          text: [
969            `${isEnabled ? "on" : "off"} (mode: ${config.mode}, summary: ${config.summary ? "on" : "off"})`,
970            `engine: ${marks[0]} ${config.engine} (${engine.voice})${config.fallback ? `, fallback: ${marks[1]} ${config.fallback}` : ""}`,
971            `speed: ${options.speed}, volume: ${config.volume}`,
972            ...(pins[cwd] === undefined ? [] : [`engine and voice pinned to ${cwd} (/tts unpin)`]),
973            `player: ${player ?? "none"}`,
974            "/tts help lists the commands",
975          ].join("\n"),
976        }
977      }
978      default:
979        return { text: `unknown: ${action}\n\n${HELP}` }
980    }
981  })
982
983  // The picker a `/tts` command without a value opens: a pick saves the setting and closes the pane.
984  on("ui.render", { component: "Pane", requestId: PICKER_PANE }, async ($, e) => {
985    const shown = await read($, picker)
986    if (e.surface === "mobile" || shown === null || shown.options.length === 0) {
987      const { Text } = $.ui.resolve(e)
988      return <Text dimColor>{shown === null || shown.options.length === 0 ? "Nothing to pick." : shown.options.map(optionLine).join("\n")}</Text>
989    }
990    const { Box, Text, Select, Button } = $.ui.resolve(e)
991    const page = shown.page ?? Math.floor(Math.max(0, shown.options.findIndex(option => option.value === shown.value)) / PICKER_PAGE_SIZE)
992    const pages = Math.ceil(shown.options.length / PICKER_PAGE_SIZE)
993    const choices = shown.options.slice(page * PICKER_PAGE_SIZE, (page + 1) * PICKER_PAGE_SIZE)
994    const turnPage = (page: number) => update($, picker, () => ({ ...shown, page }))
995    return (
996      <Box flexDirection="column">
997        <Text dimColor>{`${shown.title}: ↑↓ move, Enter picks, Esc closes`}</Text>
998        {pages > 1 && (
999          <Box>
1000            {page > 0 && <Button key="previous-page" hotkey="p" onPress={() => turnPage(page - 1)}>Previous</Button>}
1001            <Text dimColor>{` Page ${page + 1}/${pages} `}</Text>
1002            {page + 1 < pages && <Button key="next-page" hotkey="n" onPress={() => turnPage(page + 1)}>Next</Button>}
1003          </Box>
1004        )}
1005        <Select
1006          key={`${shown.action}-${page}`}
1007          options={choices.map(option => ({ value: option.value, label: option.label ?? option.value }))}
1008          value={choices.some(option => option.value === shown.value) ? shown.value : undefined}
1009          autoFocus
1010          onSelect={async value => {
1011            await $.ui.close({ id: PICKER_PANE })
1012            if (shown.action === "replay") {
1013              const text = replayChoices[Number(value)]
1014              if (text === undefined) $.ui.toast("tts: that block is gone; run /tts replay select again")
1015              else await replay(text)
1016              return
1017            }
1018            $.ui.toast(`tts: ${await commit($, changeOf(shown.action, value), applyPins)}`)
1019          }}
1020        />
1021      </Box>
1022    )
1023  })
1024
1025  on("prompt.submit", async ($, e, next) => {
1026    if (config.interruptOnPrompt) await stop()
1027    return next(e)
1028  }).catch(($, e, next) => next(e))
1029
1030  // Asks the model to write what reads well aloud, and a summary to read in its place; notify mode reads none of its text.
1031  on("prompt.compose", async ($, e, next) => {
1032    const composed = await next(e)
1033    if (!isEnabled || config.mode === "notify") return composed
1034    const added = [
1035      ...(config.modelPrompt === "" ? [] : [{ id: "tts:spoken", text: config.modelPrompt, scope: "session" as const }]),
1036      ...(config.summary ? [{ id: "tts:summary", text: SUMMARY_PROMPT, scope: "session" as const }] : []),
1037    ]
1038    return added.length === 0 ? composed : { sections: [...composed.sections, ...added] }
1039  }).catch(($, e, next) => next(e))
1040
1041  on("turn.start", async ($, e, next) => {
1042    // A subagent's turn, should one start here, is no new turn of the main loop: its steps are not counted.
1043    if (!("agentId" in e) || e.agentId === undefined) {
1044      isTurnMuted = false
1045      turnFirstStep = stepCount + 1
1046    }
1047    return next(e)
1048  })
1049
1050  on("turn.complete", async ($, e, next) => {
1051    if (e.reason === "aborted" && e.agentId === undefined) await stop()
1052    if (isEnabled && !isTurnMuted && e.agentId === undefined) {
1053      // An answer streaming when `$.tts` stopped is not read at the turn's end either; a notice still is.
1054      const isDropped = stoppedResponse === responseCount
1055      // Stream: text from before the answer still waiting gives way to the answer, read from its start.
1056      // Once the answer is being read, nothing earlier waits and it reads on: it is never said twice.
1057      if (config.mode === "stream" && e.reason === "answer") {
1058        answerSteps.add(stepCount)
1059        refreshWait()
1060      }
1061      if (config.mode === "stream" && e.reason === "answer" && e.answer !== "" && !isDropped && hasUnplayedBefore(stepCount)) {
1062        // Only this turn's speech gives way: an earlier turn's answer still playing reads on before this one.
1063        await skipTurnSpeech()
1064        const budget: Budget = { spoken: 0, isCut: false, priority: ANSWER_PRIORITY }
1065        enqueue(toSentences(answerText(e.answer)), budget)
1066        finishResponse(budget)
1067      }
1068      if (config.mode === "final" && e.reason === "answer" && !isDropped) {
1069        const budget: Budget = { spoken: 0, isCut: false, priority: ANSWER_PRIORITY }
1070        enqueue(toSentences(answerText(e.answer)), budget)
1071        finishResponse(budget)
1072      }
1073      const notice = TURN_NOTICES[e.reason]
1074      if (config.mode === "notify" && notice !== undefined && config.notices[notice] !== "") enqueue([config.notices[notice]])
1075    }
1076    return next(e)
1077  })
1078
1079  // Whatever the mode, a dialog waiting for the person cuts off the reading and is announced.
1080  on("tool.call", async ($, e, next) => {
1081    if (isEnabled && DIALOG_TOOLS.has(e.tool)) {
1082      await stop()
1083      const { notice, detail } = dialogSpeech(e.tool, e, config.notices)
1084      queueNotice(notice)
1085      enqueue(detail)
1086    }
1087    return next(e)
1088  }).catch(($, e, next) => next(e))
1089
1090  // Raised as a permission dialog is about to be shown, not for a call a rule or the mode settles.
1091  on("classic.PermissionRequest", async ($, e, next) => {
1092    if (isEnabled && !DIALOG_TOOLS.has(e.tool_name)) {
1093      await stop()
1094      const { notice, detail } = dialogSpeech(e.tool_name, e.tool_input, config.notices)
1095      queueNotice(notice)
1096      enqueue(detail)
1097    }
1098    return next(e)
1099  }).catch(($, e, next) => next(e))
1100
1101  // Speaks the main loop's text as it streams; thinking, tool calls and subagents stay silent.
1102  on("turn.step", async function* ($, e, next) {
1103    const stream = next(e)
1104    if (e.agentId === undefined) responseCount += 1
1105    if (!isEnabled || config.mode !== "stream" || e.agentId !== undefined) return yield* stream
1106
1107    // Each response has its own budget: text before a tool call does not use up the answer's.
1108    const budget: Budget = { spoken: 0, isCut: false, step: ++stepCount, priority: STREAM_PRIORITY }
1109    // Text of the response before waits as text before a tool call from now on.
1110    refreshWait()
1111    const splitter = new SpeechSplitter()
1112    // A response opening with a summary line is heard as that line alone.
1113    const summary = config.summary ? new SummaryFilter() : undefined
1114    const responseGeneration = generation
1115    const queueResponse = (texts: readonly Spoken[]) => {
1116      if (!isTurnMuted && responseGeneration === generation) enqueue(texts, budget)
1117    }
1118    let block: number | undefined
1119    try {
1120      for await (const chunk of stream) {
1121        if (chunk.kind === "text") {
1122          if (block !== undefined && block !== chunk.index) queueResponse([...splitter.push(summary?.flush() ?? ""), ...splitter.flush()])
1123          block = chunk.index
1124          queueResponse(splitter.push(summary === undefined ? chunk.text : summary.push(chunk.text)))
1125        }
1126        // The response's last chunk says it ends calling a tool: its text comes before one from now on.
1127        if (chunk.kind === "stop" && chunk.stopReason === "tool_use" && budget.step !== undefined) {
1128          toolSteps.add(budget.step)
1129          refreshWait()
1130        }
1131        yield chunk
1132      }
1133    } finally {
1134      // Runs even when the engine stops pulling after the last chunk: the line without a newline is said too.
1135      queueResponse(splitter.push(summary?.flush() ?? ""))
1136      // Text before a tool call is no answer: what followed its summary line is read too.
1137      if (summary !== undefined && budget.step !== undefined && toolSteps.has(budget.step)) queueResponse(splitter.push(summary.release()))
1138      queueResponse(splitter.flush())
1139      if (!isTurnMuted && responseGeneration === generation) finishResponse(budget)
1140    }
1141    return stream.result
1142  })
1143}
1144
1145/** Creates a temporary directory, removing the previous module's files after a reload. */
1146async function prepareDirectory($: EngineInterface, isWindows: boolean): Promise<string> {
1147  const previous = await read($, audioDirectory)
1148  if (previous !== null) await $.process.run(removeDirectoryCommand(previous, isWindows))
1149  const created = await $.process.run(tempDirectoryCommand(isWindows))
1150  if (created.exitCode !== 0 || created.stdout.trim() === "") throw new Error("tts: could not create a private audio directory")
1151  const directory = created.stdout.trim()
1152  await update($, audioDirectory, () => directory)
1153  return directory
1154}
1155
1156
1157// Everything handed $ stays in this file: the validator follows $ into this file's functions only.
1158
1159/** Runs an engine's commands for one sentence; throws on the first that fails. */
1160async function synthesize(
1161  $: EngineInterface,
1162  process: SpeechProcess,
1163  engine: LoadedEngine,
1164  text: string,
1165  file: string,
1166  isCurrent: () => boolean,
1167) {
1168  await runSteps($, process, engine.synthesis(text, file), isCurrent)
1169}
1170
1171/** Runs commands in turn, each fed the one before's stdout as it asks; gives the last stdout, and throws on the first that fails. */
1172async function runSteps($: EngineInterface, process: SpeechProcess, steps: Step[], isCurrent: () => boolean): Promise<string> {
1173  let stdout = ""
1174  for (const step of steps) {
1175    if (!isCurrent()) return stdout
1176    const stdin = typeof step.stdin === "function" ? step.stdin(stdout) : step.stdin
1177    const ran = await runProcess($, process, step.argv, stdin, SYNTH_TIMEOUT_MS)
1178    if (ran.code !== 0) {
1179      throw new Error(`${step.argv[0]} exited ${ran.code}: ${(ran.stderr || ran.stdout).trim().slice(0, 200)}`)
1180    }
1181    stdout = ran.stdout
1182  }
1183  return stdout
1184}
1185
1186/** A cancellable command with the same time limit synthesis had under process.run. */
1187async function runProcess($: EngineInterface, process: SpeechProcess, argv: string[], input: string | undefined, timeoutMs: number) {
1188  const running = process.read($.process.spawn({ argv, input }))
1189  let timedOut = false
1190  const timer = $.clock.after(timeoutMs, () => {
1191    timedOut = true
1192    void process.stop()
1193  })
1194  try {
1195    const result = await running
1196    if (timedOut) throw new Error(`${argv[0]} timed out`)
1197    return result
1198  } finally {
1199    timer.cancel()
1200  }
hooks/channel.ts 26 lines
1/** An unbounded queue whose `take` waits for the next item. */
2export class Channel<T> {
3  private items: T[] = []
4  private waiter: (() => void) | undefined
5
6  get size(): number {
7    return this.items.length
8  }
9
10  push(item: T) {
11    this.items.push(item)
12    this.waiter?.()
13    this.waiter = undefined
14  }
15
16  /** Waits until an item is queued, taking none. */
17  async ready(): Promise<void> {
18    while (this.items.length === 0) await new Promise<void>(resolve => (this.waiter = resolve))
19  }
20
21  async take(): Promise<T> {
22    while (this.items.length === 0) await new Promise<void>(resolve => (this.waiter = resolve))
23    return this.items.shift() as T
24  }
25}
26
hooks/config.ts 84 lines
1import type { PluginOptions } from "claude-code"
2
3import { type EngineName, ENGINES } from "./engines"
4
5/** stream: every sentence as it streams. final: the turn's answer once it ends. notify: short notices alone. */
6export type ReadMode = "stream" | "final" | "notify"
7
8/** The lines said as notices, each a `/config` row; an empty one stays silent. */
9export type Notices = {
10  done: string
11  error: string
12  refusal: string
13  question: string
14  /** `{n}` is the number of questions. */
15  questions: string
16  plan: string
17  command: string
18  tool: string
19  cut: string
20  code: string
21  table: string
22  /** Joined to the first sentence of a block quote. */
23  quote: string
24}
25
26const NOTICE_OPTIONS: Record<keyof Notices, string> = {
27  done: "noticeDone",
28  error: "noticeError",
29  refusal: "noticeRefusal",
30  question: "noticeQuestion",
31  questions: "noticeQuestions",
32  plan: "noticePlan",
33  command: "noticeCommand",
34  tool: "noticeTool",
35  cut: "noticeCut",
36  code: "noticeCode",
37  table: "noticeTable",
38  quote: "noticeQuote",
39}
40
41/** The settings every engine shares; each engine reads its own in `load`. */
42export type TtsConfig = {
43  isEnabled: boolean
44  mode: ReadMode
45  engine: EngineName
46  /** The engine tried when `engine` fails a sentence; undefined for none. */
47  fallback: EngineName | undefined
48  player: string
49  volume: number
50  maxCharsPerTurn: number
51  /** Take turns with other sessions on the floor; false plays at once, over them. */
52  sharePlayback: boolean
53  /** Seconds text before a tool call waits for another session to finish; 0: no limit. */
54  maxWaitSeconds: number
55  interruptOnPrompt: boolean
56  /** Added to the system prompt while replies are read; empty: nothing. */
57  modelPrompt: string
58  /** Ask for a summary line on long answers, and read only it where an answer has one. */
59  summary: boolean
60  notices: Notices
61}
62
63export function toConfig(options: PluginOptions): TtsConfig {
64  const engine = String(options.engine)
65  const fallback = String(options.fallback)
66  return {
67    isEnabled: options.enabled !== false,
68    mode: options.mode as ReadMode,
69    engine: engine in ENGINES ? (engine as EngineName) : "voicevox",
70    fallback: fallback in ENGINES && fallback !== engine ? (fallback as EngineName) : undefined,
71    player: String(options.player),
72    volume: Number(options.volume),
73    maxCharsPerTurn: Number(options.maxCharsPerTurn),
74    sharePlayback: options.sharePlayback !== false,
75    maxWaitSeconds: Math.max(0, Number(options.maxWaitSeconds ?? 60) || 0),
76    interruptOnPrompt: options.interruptOnPrompt === true,
77    modelPrompt: String(options.modelPrompt ?? "").trim(),
78    summary: options.summary === true,
79    notices: Object.fromEntries(
80      Object.entries(NOTICE_OPTIONS).map(([notice, option]) => [notice, String(options[option] ?? "").trim()]),
81    ) as Notices,
82  }
83}
84
hooks/dialog-text.ts 34 lines
1import type { Notices } from "./config"
2import { type Spoken, toSentences } from "./speech-text"
3
4/** Tools whose call itself opens a dialog for the person; the rest open one only to ask permission. */
5export const DIALOG_TOOLS: ReadonlySet<string> = new Set(["AskUserQuestion", "ExitPlanMode"])
6
7/**
8 * What is said as a dialog opens: `notice`, a short line from the settings
9 * that is cached and plays at once (empty: none), then `detail`, synthesized
10 * each time.
11 */
12export type DialogSpeech = { notice: string; detail: Spoken[] }
13
14export function dialogSpeech(tool: string, input: unknown, notices: Notices): DialogSpeech {
15  const fields = (typeof input === "object" && input !== null ? input : {}) as Record<string, unknown>
16  switch (tool) {
17    case "AskUserQuestion": {
18      const questions = Array.isArray(fields.questions) ? (fields.questions as { question?: unknown }[]) : []
19      // Several questions are counted, not read: the dialog shows them one at a time.
20      if (questions.length > 1) return { notice: notices.questions.replaceAll("{n}", String(questions.length)), detail: [] }
21      const question = questions[0]?.question
22      return { notice: notices.question, detail: notices.question !== "" && typeof question === "string" ? toSentences(question) : [] }
23    }
24    case "ExitPlanMode":
25      return { notice: notices.plan, detail: [] }
26    case "Bash": {
27      const { description } = fields
28      return { notice: notices.command, detail: notices.command !== "" && typeof description === "string" ? toSentences(description) : [] }
29    }
30    default:
31      return { notice: notices.tool, detail: [] }
32  }
33}
34
hooks/floor.ts 174 lines
1import { powershellCommand, quotePowerShell } from "./platform"
2
3/**
4 * The floor: one lock file every session on this machine shares, so only one plays at a time.
5 * A session waiting for it leaves a file under `wait/` saying its priority; a holder hands the
6 * floor over at the next clip to a session waiting with a higher one, and none ever stops
7 * another's clip.
8 */
9
10/** Text before a tool call, which a wait past the limit drops. */
11export const STREAM_PRIORITY = 0
12/** A turn's answer: never dropped, said before text before a tool call. */
13export const ANSWER_PRIORITY = 1
14/** Notices, dialogs and what a `/tts` command reads: said first. */
15export const NOTICE_PRIORITY = 2
16
17/** acquireCommand gave up: the wait passed its limit. */
18export const FLOOR_TIMEOUT = 3
19/** guardedPlayCommand handed the floor to a session waiting with a higher priority, and played nothing. */
20export const FLOOR_YIELDED = 75
21/** guardedPlayCommand found the floor taken: this session lost it as stale. Nothing played. */
22export const FLOOR_LOST = 76
23/**
24 * What guardedPlayCommand writes to stderr beside FLOOR_YIELDED or FLOOR_LOST: a player that
25 * exits with the same status is not taken for the floor.
26 */
27export const FLOOR_MARK = "tts-floor:"
28
29/** Whether a guarded play handed the floor over or found it lost, rather than played. */
30export function floorOutcome(code: number | null, stderr: string): "yielded" | "lost" | undefined {
31  if (!stderr.includes(FLOOR_MARK)) return undefined
32  return code === FLOOR_YIELDED ? "yielded" : code === FLOOR_LOST ? "lost" : undefined
33}
34
35/** Seconds without a heartbeat after which a holder counts as gone (a crash, a killed session). */
36const STALE_HOLDER = 60
37/** Seconds after which a waiter that stopped refreshing its file counts as gone. */
38const STALE_WAITER = 5
39/**
40 * Seconds after which a gone waiter's file is removed. Until then it is only passed over: a waiter
41 * that was merely paused may be writing a fresh one, which a removal could take with it.
42 */
43const ABANDONED_WAITER = 3600
44
45// Unix: the shared directory is the user's own; `set -C` makes creating the lock file atomic.
46const SH_PRELUDE = [
47  `dir="\${TMPDIR:-/tmp}/claude-tts-floor-$(id -u)"`,
48  // Never through a link another user planted: the directory must be a real one of this user's.
49  `mkdir "$dir" 2>/dev/null; [ -d "$dir" ] && [ ! -L "$dir" ] && [ -O "$dir" ] && chmod 700 "$dir" && mkdir -p "$dir/wait" || exit 1`,
50  `valid() { case $1 in ''|*[!0-9]*) return 1;; esac; }`,
51  // Whether a session other than `$id` waits, freshly, with a priority above `$prio`; removes long-abandoned waiters.
52  `higher() { for f in "$dir"/wait/*; do [ -f "$f" ] && [ "$f" != "$dir/wait/$id" ] || continue; read -r p t < "$f" 2>/dev/null; valid "$p" && valid "$t" || continue; if [ $(($1 - t)) -gt ${ABANDONED_WAITER} ]; then rm -f "$f"; elif [ $(($1 - t)) -le ${STALE_WAITER} ] && [ "$p" -gt "$prio" ]; then return 0; fi; done; return 1; }`,
53  `owner() { o=; b=; [ -f "$dir/floor" ] && read -r o b < "$dir/floor" 2>/dev/null; }`,
54  `beat() { echo "$id $1" > "$dir/floor.$id" && mv -f "$dir/floor.$id" "$dir/floor"; }`,
55  // Whether the floor file at $2 is a holder's that is gone: no heartbeat for a while, or one it never finished writing that is old.
56  `staleat() { o=; b=; [ -f "$2" ] || return 1; read -r o b < "$2" 2>/dev/null; if valid "$b"; then [ $(($1 - b)) -gt ${STALE_HOLDER} ]; else [ -n "$(find "$2" -mmin +${Math.ceil(STALE_HOLDER / 60)} 2>/dev/null)" ]; fi; }`,
57  // Moves the floor aside and judges the file moved, not what was seen before: a floor another waiter
58  // took meanwhile is fresh, and goes back, never over one created since.
59  `takeover() { t="$dir/floor.stale.$id"; mv "$dir/floor" "$t" 2>/dev/null || return 0; staleat "$1" "$t" || ln "$t" "$dir/floor" 2>/dev/null; rm -f "$t"; }`,
60  // Gives up this session's floor: moves it aside and removes it only if the file moved is this session's;
61  // another's, taken meanwhile (this one stale after a sleep), goes back, never over one created since.
62  `drop() { d="$dir/floor.drop.$id"; mv "$dir/floor" "$d" 2>/dev/null || return 0; o=; read -r o b < "$d" 2>/dev/null; [ "$o" = "$id" ] || ln "$d" "$dir/floor" 2>/dev/null; rm -f "$d"; }`,
63  // A waiter's file is replaced whole: a holder never reads it half written.
64  `put() { echo "$2" > "$dir/wait.$id" && mv -f "$dir/wait.$id" "$1"; }`,
65  `fail() { echo "${FLOOR_MARK} $2" >&2; exit $1; }`,
66].join("\n")
67
68const PS_PRELUDE = [
69  `$dir = Join-Path ([IO.Path]::GetTempPath()) 'claude-tts-floor'`,
70  `$null = New-Item -ItemType Directory -Force -Path (Join-Path $dir 'wait')`,
71  `$floor = Join-Path $dir 'floor'`,
72  "function Now { [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() }",
73  "function Pair($path) { try { $s = @([IO.File]::ReadAllText($path).Trim() -split ' '); if ($s.Count -eq 2 -and $s[1] -match '^[0-9]+$') { return ,$s } } catch {}; return $null }",
74  `function Higher($now) { foreach ($f in @(Get-ChildItem -LiteralPath (Join-Path $dir 'wait') -File -ErrorAction SilentlyContinue)) { if ($f.Name -eq $id) { continue }; $s = Pair $f.FullName; if ($null -eq $s -or $s[0] -notmatch '^[0-9]+$') { continue }; $age = $now - [long]$s[1]; if ($age -gt ${ABANDONED_WAITER}) { Remove-Item -LiteralPath $f.FullName -Force -ErrorAction SilentlyContinue } elseif ($age -le ${STALE_WAITER} -and [int]$s[0] -gt $prio) { return $true } }; return $false }`,
75  // Files are written aside and swapped in whole; the floor is only ever replaced, never created again by a heartbeat.
76  "function Put($path, $text, $mayCreate) { $tmp = Join-Path $dir \"put.$id.tmp\"; try { [IO.File]::WriteAllText($tmp, $text); if (Test-Path -LiteralPath $path) { [IO.File]::Replace($tmp, $path, $null) } elseif ($mayCreate) { [IO.File]::Move($tmp, $path) } } catch {} finally { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue } }",
77  "function Beat($now) { Put $floor \"$id $now\" $false }",
78  `function StaleAt($path, $now) { $o = Pair $path; if ($null -ne $o) { return ($now - [long]$o[1] -gt ${STALE_HOLDER}) }; $f = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue; return ($null -ne $f -and ([DateTime]::UtcNow - $f.LastWriteTimeUtc).TotalSeconds -gt ${STALE_HOLDER}) }`,
79  "function Stale($now) { StaleAt $floor $now }",
80  // Gives up this session's floor, removing only a file that is this session's (see drop above).
81  "function Drop { $d = Join-Path $dir \"floor.drop.$id\"; Remove-Item -LiteralPath $d -Force -ErrorAction SilentlyContinue; try { [IO.File]::Move($floor, $d) } catch { return }; $o = Pair $d; if ($null -eq $o -or $o[0] -ne $id) { try { [IO.File]::Move($d, $floor) } catch {} }; Remove-Item -LiteralPath $d -Force -ErrorAction SilentlyContinue }",
82  "function Create($path, $text) { try { $file = [IO.File]::Open($path, 'CreateNew', 'Write'); $bytes = [Text.Encoding]::ASCII.GetBytes($text); $file.Write($bytes, 0, $bytes.Length); $file.Dispose(); return $true } catch [IO.IOException] { return $false } }",
83  // Moves the floor aside and judges the file moved: a fresh one goes back, never over one created since.
84  "function Takeover($now) { $t = Join-Path $dir \"floor.stale.$id\"; Remove-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue; try { [IO.File]::Move($floor, $t) } catch { return }; if (-not (StaleAt $t $now)) { try { [IO.File]::Move($t, $floor) } catch {} }; Remove-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue }",
85  `function Fail($code, $what) { [Console]::Error.WriteLine("${FLOOR_MARK} $what"); exit $code }`,
86].join("; ")
87
88const sh = (script: string, args: (string | number)[]) => ["sh", "-c", `${SH_PRELUDE}\n${script}`, "tts-floor", ...args.map(String)]
89const ps = (id: string, priority: number, script: string) =>
90  powershellCommand(`$id = ${quotePowerShell(id)}; $prio = ${priority}; ${PS_PRELUDE}; ${script}`)
91
92/**
93 * Waits for the floor; exits 0 once held, FLOOR_TIMEOUT after `limitSeconds` (0: no limit).
94 * Steps aside while a session waits with a higher priority, and takes the floor from a holder gone stale.
95 */
96export function acquireCommand(isWindows: boolean, id: string, priority: number, limitSeconds: number): string[] {
97  // A fraction of a second is still a limit: 0 alone waits without one.
98  const limit = Math.max(0, Math.ceil(limitSeconds))
99  if (isWindows) return ps(id, priority, [
100    `$limit = ${limit}; $start = Now; $w = Join-Path (Join-Path $dir 'wait') $id`,
101    "function Leave($code) { Remove-Item -LiteralPath $w -Force -ErrorAction SilentlyContinue; exit $code }",
102    "while ($true) {",
103    "$now = Now; Put $w \"$prio $now\" $true",
104    "$o = Pair $floor; if ($null -ne $o -and $o[0] -eq $id) { Leave 0 }",
105    "if (Stale $now) { Takeover $now }",
106    "if (-not (Higher $now) -and (Create $floor \"$id $now\")) { Leave 0 }",
107    `if ($limit -gt 0 -and $now - $start -ge $limit) { Leave ${FLOOR_TIMEOUT} }`,
108    "Start-Sleep -Milliseconds 200 }",
109  ].join("; "))
110  return sh([
111    `id=$1 prio=$2 limit=$3 w="$dir/wait/$1" start=$(date +%s)`,
112    `trap 'rm -f "$w" "$dir/wait.$id"; exit 143' HUP INT TERM`,
113    "while :; do",
114    `  now=$(date +%s); put "$w" "$prio $now"`,
115    `  owner; if [ "$o" = "$id" ]; then rm -f "$w"; exit 0; fi`,
116    `  staleat "$now" "$dir/floor" && takeover "$now"`,
117    `  if ! higher "$now" && (set -C; echo "$id $now" > "$dir/floor") 2>/dev/null; then rm -f "$w"; exit 0; fi`,
118    `  if [ "$limit" -gt 0 ] && [ $((now - start)) -ge "$limit" ]; then rm -f "$w"; exit ${FLOOR_TIMEOUT}; fi`,
119    "  sleep 0.2",
120    "done",
121  ].join("\n"), [id, priority, limit])
122}
123
124/** Gives the floor up, if this session holds it, and withdraws a wait for it a cancelled acquire left behind. */
125export function releaseCommand(isWindows: boolean, id: string): string[] {
126  if (isWindows) return ps(id, 0, "Remove-Item -LiteralPath (Join-Path (Join-Path $dir 'wait') $id) -Force -ErrorAction SilentlyContinue; Drop; exit 0")
127  return sh(`id=$1; rm -f "$dir/wait/$id"; drop; exit 0`, [id])
128}
129
130/**
131 * Says the holder is still here; exits FLOOR_LOST when it no longer holds the floor. Given a
132 * priority (between clips, nothing playing), hands the floor to a session waiting with a higher
133 * one instead and exits FLOOR_YIELDED.
134 */
135export function heartbeatCommand(isWindows: boolean, id: string, yieldBelow?: number): string[] {
136  const canYield = yieldBelow !== undefined
137  if (isWindows) return ps(id, yieldBelow ?? 0, [
138    `$o = Pair $floor; if ($null -eq $o -or $o[0] -ne $id) { exit ${FLOOR_LOST} }`,
139    `$now = Now; if (${canYield ? "$true" : "$false"} -and (Higher $now)) { Drop; exit ${FLOOR_YIELDED} }`,
140    "Beat $now; exit 0",
141  ].join("; "))
142  return sh([
143    `id=$1 prio=$2 yield=$3`,
144    `owner; [ "$o" = "$id" ] || exit ${FLOOR_LOST}`,
145    `now=$(date +%s); if [ "$yield" = 1 ] && higher "$now"; then drop; exit ${FLOOR_YIELDED}; fi`,
146    `beat "$now"`,
147  ].join("\n"), [id, yieldBelow ?? 0, canYield ? 1 : 0])
148}
149
150/**
151 * Plays `play` while holding the floor, in the same process: first hands the floor over to a
152 * session waiting with a higher priority (FLOOR_YIELDED) and checks it is still held (FLOOR_LOST).
153 */
154export function guardedPlayCommand(isWindows: boolean, id: string, priority: number, play: string[]): string[] {
155  if (isWindows) {
156    const guard = [
157      `$o = Pair $floor; if ($null -eq $o -or $o[0] -ne $id) { Fail ${FLOOR_LOST} 'lost' }`,
158      `$now = Now; if (Higher $now) { Drop; Fail ${FLOOR_YIELDED} 'yielded' }`,
159      "Beat $now",
160    ].join("; ")
161    // A PowerShell player already runs a script: play in the same process rather than start another.
162    const isPowerShell = play[0] === "powershell.exe" && play[3] === "-Command" && play.length === 5
163    const body = isPowerShell ? play[4] : `& ${play.map(quotePowerShell).join(" ")}; exit $LASTEXITCODE`
164    return ps(id, priority, `${guard}; ${body}`)
165  }
166  return sh([
167    `id=$1 prio=$2; shift 2`,
168    `owner; [ "$o" = "$id" ] || fail ${FLOOR_LOST} lost`,
169    `now=$(date +%s); if higher "$now"; then drop; fail ${FLOOR_YIELDED} yielded; fi`,
170    `beat "$now"`,
171    `exec "$@"`,
172  ].join("\n"), [id, priority, ...play])
173}
174
hooks/engines/index.ts 12 lines
1import { command } from "./command"
2import type { Engine } from "./engine"
3import { irodori } from "./irodori"
4import { voicevox } from "./voicevox"
5
6export type { Engine, LoadedEngine, Step } from "./engine"
7
8/** Every engine by the name `/tts engine` and the `engine` setting take. */
9export const ENGINES = { voicevox, irodori, command } satisfies Record<string, Engine>
10
11export type EngineName = keyof typeof ENGINES
12
hooks/pins.ts 31 lines
1import type { PluginOptions } from "claude-code"
2
3import { type EngineName, ENGINES } from "./engines"
4
5/** What a working directory pins: its engine, and the voice it chose for each engine. */
6export type Pin = { engine: EngineName; voices: Partial<Record<EngineName, string>> }
7
8/** Pins by working directory, as `$.store` keeps them. */
9export type Pins = Record<string, Pin>
10
11export const PINS_KEY = "pins"
12
13/** The options with a directory's pin laid over them; the options alone without one. */
14export function pinnedOptions(options: PluginOptions, pin: Pin | undefined): PluginOptions {
15  if (pin === undefined) return options
16  const pinned: Record<string, PluginOptions[string]> = { ...options, engine: pin.engine }
17  for (const [name, voice] of Object.entries(pin.voices) as [EngineName, string][]) {
18    const selected = ENGINES[name].load(options).voices?.select(voice)
19    if (selected !== undefined) pinned[selected.key.replace(/^tts\./, "")] = selected.value
20  }
21  return pinned
22}
23
24/** Reads `$.store`'s value as pins, dropping what is not one. */
25export function toPins(stored: unknown): Pins {
26  if (typeof stored !== "object" || stored === null) return {}
27  return Object.fromEntries(
28    Object.entries(stored).filter(([, pin]) => typeof pin === "object" && pin !== null && (pin as Pin).engine in ENGINES),
29  ) as Pins
30}
31
hooks/replay.ts 65 lines
1import type { SessionMessage } from "claude-code"
2
3import type { PickerOption } from "../types"
4
5import { toSentences } from "./speech-text"
6
7/** How many blocks `/tts replay select` offers, newest first. */
8const MAX_BLOCKS = 100
9const MAX_LABEL = 60
10
11/**
12 * What the model wrote in one go: consecutive assistant text, ended by a tool
13 * call (whose message's text belongs to the block) or by a user message.
14 */
15export function replayBlocks(messages: readonly SessionMessage[]): string[] {
16  const blocks: string[] = []
17  let parts: string[] = []
18  const end = () => {
19    if (parts.length > 0) blocks.push(parts.join("\n"))
20    parts = []
21  }
22  for (const message of messages) {
23    if (message.role === "user") {
24      end()
25      continue
26    }
27    if (message.text.trim() !== "") parts.push(message.text)
28    if (message.toolUses.length > 0) end()
29  }
30  end()
31  return blocks
32}
33
34/**
35 * The turn's final answer: the assistant text after the last tool call. A
36 * prompt or command typed since is passed over, so it is the answer before it.
37 */
38export function lastAnswer(messages: readonly SessionMessage[]): string | undefined {
39  const parts: string[] = []
40  let index = messages.length - 1
41  while (index >= 0 && messages[index]!.role === "user" && messages[index]!.toolResults === undefined) index--
42  for (; index >= 0; index--) {
43    const message = messages[index]!
44    if (message.role === "user" || message.toolUses.length > 0) break
45    if (message.text.trim() !== "") parts.unshift(message.text)
46  }
47  return parts.length === 0 ? undefined : parts.join("\n")
48}
49
50/** The picker's choices for `blocks`, newest first: `value` is the block's index. */
51export function replayOptions(blocks: readonly string[]): PickerOption[] {
52  const options: PickerOption[] = []
53  for (let index = blocks.length - 1; index >= 0 && options.length < MAX_BLOCKS; index--) {
54    options.push({ value: String(index), label: replayLabel(blocks[index]!) })
55  }
56  return options
57}
58
59/** A block's first sentence as it would be heard, cut to one short line. */
60function replayLabel(block: string): string {
61  const first = toSentences(block).find(sentence => typeof sentence === "string") ?? "(コードや表のみ)"
62  const characters = Array.from(first)
63  return characters.length > MAX_LABEL ? `${characters.slice(0, MAX_LABEL - 1).join("")}…` : first
64}
65
hooks/platform.ts 36 lines
1/** Quotes a literal for PowerShell, including the smart quotes it treats as delimiters. */
2export function quotePowerShell(value: string): string {
3  return `'${value.replace(/['‘’‚‛]/g, quote => quote + quote)}'`
4}
5
6/** Keep paths containing Japanese readable when Windows PowerShell writes to a pipe. */
7export function powershellCommand(script: string): string[] {
8  return [
9    "powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
10    `$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [Text.UTF8Encoding]::new(); ${script}`,
11  ]
12}
13
14/** Unix uses mode 0700; Windows inherits the user's temporary folder permissions. */
15export function tempDirectoryCommand(isWindows: boolean): string[] {
16  return isWindows
17    ? powershellCommand("$path = Join-Path ([IO.Path]::GetTempPath()) ('claude-tts-' + [Guid]::NewGuid().ToString('N')); [IO.Directory]::CreateDirectory($path).FullName")
18    : ["mktemp", "-d", "/tmp/claude-tts-XXXXXXXXXX"]
19}
20
21export function removeFilesCommand(files: string[], isWindows: boolean): string[] {
22  return isWindows
23    ? powershellCommand(`Remove-Item -LiteralPath ${files.map(quotePowerShell).join(", ")} -Force -ErrorAction SilentlyContinue; exit 0`)
24    : ["rm", "-f", ...files]
25}
26
27export function removeDirectoryCommand(directory: string, isWindows: boolean): string[] {
28  return isWindows
29    ? powershellCommand(`Remove-Item -LiteralPath ${quotePowerShell(directory)} -Recurse -Force -ErrorAction SilentlyContinue; exit 0`)
30    : ["rm", "-rf", "--", directory]
31}
32
33export function findProgramCommand(program: string, isWindows: boolean): string[] {
34  return isWindows ? ["where.exe", program] : ["sh", "-c", 'command -v "$1" >/dev/null', "probe", program]
35}
36
hooks/player.ts 154 lines
1import { powershellCommand, quotePowerShell } from "./platform"
2
3const TAIL_PADDING_SECONDS = 0.2
4
5/** Prints the first audio player found on this machine. */
6export function findPlayerCommand(isWindows: boolean): string[] {
7  if (isWindows) return powershellCommand("if (Get-Command ffplay -CommandType Application -ErrorAction SilentlyContinue) { 'ffplay' } else { 'powershell' }")
8  return [
9    "sh",
10    "-c",
11    // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion
12    "for p in ffplay paplay aplay afplay powershell.exe; do command -v $p >/dev/null && { echo ${p%.exe}; exit; }; done",
13  ]
14}
15
16/**
17 * Cuts long engine pauses, then gives ffplay and SoundPlayer time to finish speech.
18 * Padding must be in the WAV: ffplay does not flush an apad filter at EOF.
19 * Leaves the file as it was where ffmpeg is missing.
20 */
21export function prepareAudioCommand(file: string, player: string | undefined, isWindows = false): string[] {
22  const edge = (keep: number) => `silenceremove=start_periods=1:start_threshold=-45dB:start_silence=${keep}`
23  const padding = player === "ffplay" || player === "powershell" ? `,apad=pad_dur=${TAIL_PADDING_SECONDS}` : ""
24  const filter = `${edge(0.05)},areverse,${edge(0.2)},areverse${padding}`
25  if (isWindows) return powershellCommand([
26    "if (-not (Get-Command ffmpeg -CommandType Application -ErrorAction SilentlyContinue)) { exit 0 }",
27    `$file = ${quotePowerShell(file)}`,
28    `ffmpeg -loglevel error -y -i $file -af '${filter}' ($file + '.t.wav')`,
29    "if ($LASTEXITCODE -eq 0) { Move-Item -LiteralPath ($file + '.t.wav') -Destination $file -Force }",
30  ].join("; "))
31  return [
32    "sh",
33    "-c",
34    `command -v ffmpeg >/dev/null || exit 0; ffmpeg -loglevel error -y -i "$1" -af "${filter}" "$1.t.wav" && mv -f "$1.t.wav" "$1"`,
35    "tts-trim",
36    file,
37  ]
38}
39
40/** streamPlayCommand played nothing: the source wrote no WAV (an engine without streaming, one that is down), or ffmpeg is missing. */
41export const STREAM_REFUSED = 74
42/** What streamPlayCommand writes to stderr beside STREAM_REFUSED: a player that exits 74 itself is not taken for a refusal. */
43const STREAM_MARK = "tts-stream:"
44
45/** Whether streamPlayCommand works with this player: ffplay reads a pipe, and only a Unix shell runs the script. */
46export function canStream(player: string, isWindows: boolean): boolean {
47  return player === "ffplay" && !isWindows
48}
49
50/** Whether a stream exited having played nothing, so the clip is to be synthesized to a file instead. */
51export function isStreamRefused(code: number | null, stderr: string): boolean {
52  return code === STREAM_REFUSED && stderr.includes(`${STREAM_MARK} refused`)
53}
54
55/** Whether the source of a stream that had begun to play failed (or stalled past the limit), cutting the speech short. */
56export function isStreamFailed(code: number | null, stderr: string): boolean {
57  return code !== 0 && stderr.includes(`${STREAM_MARK} failed`)
58}
59
60/** Whether the source of a stream that began to play has ended, the engine done with it, though the speech may still be playing. */
61export function isStreamSynthesized(stderr: string): boolean {
62  return stderr.includes(`${STREAM_MARK} synthesized`)
63}
64
65/**
66 * Plays the WAV that `source` writes to stdout as it comes, through ffmpeg (the leading pause cut,
67 * the volume, the padding prepareAudioCommand gives a file) into ffplay. Its stdin goes to `source`.
68 * The processes talk through FIFOs beside `file` rather than a pipeline, so a stop can kill each one.
69 * Exits STREAM_REFUSED when `source` writes anything but a WAV, before anything is played, or ffmpeg fails
70 * while it runs; a source
71 * still running after `limitSeconds` is stopped, as synthesis to a file is.
72 */
73export function streamPlayCommand(file: string, volume: number, source: string[], limitSeconds: number): string[] {
74  const filter = `silenceremove=start_periods=1:start_threshold=-45dB:start_silence=0.05,volume=${volume},apad=pad_dur=${TAIL_PADDING_SECONDS}`
75  const fifos = '"$f.in" "$f.mid" "$f.out"'
76  const refuse = `echo "${STREAM_MARK} refused" >&2; exit ${STREAM_REFUSED}`
77  const noBuffer = "-probesize 32 -analyzeduration 0"
78  return ["sh", "-c", [
79    "f=$1; shift",
80    `command -v ffmpeg >/dev/null && rm -f ${fifos} "$f.no" && mkfifo ${fifos} || { ${refuse}; }`,
81    "s= g= t= p= w=",
82    // ffmpeg stopped gently writes its trailer to a FIFO no one reads, and never exits.
83    `trap 'kill -9 $t 2>/dev/null; kill $s $g $p $w 2>/dev/null; rm -f ${fifos} "$f.no"; exit 143' TERM INT HUP`,
84    // An asynchronous command reads /dev/null unless its stdin is redirected.
85    "exec 3<&0",
86    `"$@" <&3 >"$f.in" & s=$!`,
87    // Its sleep is killed with it, rather than left to run out.
88    `{ sleep ${limitSeconds} & z=$!; trap 'kill $z; exit' TERM; wait $z && kill $s; } 2>/dev/null & w=$!`,
89    // Passes the source on once it opens as a WAV; anything else (an error body, nothing) is a refusal.
90    `{ [ "$(dd bs=1 count=4 2>/dev/null)" = RIFF ] || { : >"$f.no"; exit; }; printf RIFF; cat && echo "${STREAM_MARK} synthesized" >&2; } <"$f.in" >"$f.mid" & g=$!`,
91    `ffmpeg -loglevel error -y ${noBuffer} -f wav -i "$f.mid" -af "${filter}" -f wav "$f.out" & t=$!`,
92    `ffplay -nodisp -autoexit -loglevel error ${noBuffer} -fflags nobuffer -f wav "$f.out" & p=$!`,
93    // ffmpeg that failed may never have opened its input or output, leaving the rest waiting on a FIFO.
94    "wait $t; tc=$?",
95    "[ $tc -ne 0 ] && kill $s $g $p 2>/dev/null",
96    "wait $s; sc=$?",
97    "kill $w 2>/dev/null",
98    // Failed with the source still running, ffmpeg cannot play this (an option its version lacks): a refusal.
99    `[ $tc -ne 0 ] && [ $sc -eq 143 ] && : >"$f.no"`,
100    "wait $p; pc=$?",
101    "wait $g",
102    `[ -e "$f.no" ] && { rm -f ${fifos} "$f.no"; ${refuse}; }`,
103    `rm -f ${fifos}`,
104    `[ $sc -ne 0 ] && { echo "${STREAM_MARK} failed $sc" >&2; exit $sc; }`,
105    "exit $pc",
106  ].join("\n"), "tts-stream", file, ...source]
107}
108
109/**
110 * PowerShell that plays the wav at `path` (a PowerShell expression) to its end. The file goes in
111 * as a stream: SoundPlayer given a \\wsl.localhost path with capitals plays nothing, without error.
112 */
113function soundPlayerScript(path: string, variable = "$"): string {
114  const stream = `${variable}stream`
115  return `${stream} = [IO.File]::OpenRead(${path}); try { (New-Object Media.SoundPlayer ${stream}).PlaySync() } finally { ${stream}.Dispose() }`
116}
117
118/**
119 * Plays `file` at `volume` (1 as synthesized), preserving the cached original.
120 */
121export function playCommand(player: string, file: string, volume: number, isWindows = false): string[] {
122  const shell = (script: string) => ["sh", "-c", script, "tts-play", file]
123  const isScaled = volume !== 1
124  // aplay and SoundPlayer have no volume: play a scaled copy when ffmpeg is present.
125  const scaleFile = isScaled
126    ? `command -v ffmpeg >/dev/null && ffmpeg -loglevel error -y -i "$1" -af volume=${volume} "$1.v.wav" && set -- "$1.v.wav"; `
127    : ""
128  switch (player) {
129    case "ffplay":
130      return ["ffplay", "-nodisp", "-autoexit", "-loglevel", "error", ...(isScaled ? ["-af", `volume=${volume}`] : []), file]
131    case "paplay":
132      return ["paplay", `--volume=${Math.round(65536 * volume)}`, file]
133    case "afplay":
134      return ["afplay", "-v", String(volume), file]
135    case "aplay":
136      return shell(`${scaleFile}exec aplay -q "$1"`)
137    case "powershell":
138      if (isWindows) return powershellCommand([
139        `$file = ${quotePowerShell(file)}`,
140        ...(isScaled ? [
141          `if (Get-Command ffmpeg -CommandType Application -ErrorAction SilentlyContinue) { ffmpeg -loglevel error -y -i $file -af volume=${volume} ($file + '.v.wav'); if ($LASTEXITCODE -eq 0) { $file += '.v.wav' } }`,
142        ] : []),
143        soundPlayerScript("$file"),
144      ].join("; "))
145      // WSL: Windows reads the file through its \\wsl.localhost path.
146      return shell(
147        // `\$` keeps sh from expanding PowerShell's variable.
148        `${scaleFile}exec powershell.exe -NoProfile -NonInteractive -Command "${soundPlayerScript(`'$(wslpath -w "$1")'`, "\\$")}"`,
149      )
150    default:
151      return [player, file]
152  }
153}
154
hooks/process.ts 37 lines
1import type { HookStream, ProcessSpawnChunk, ProcessSpawnResult } from "claude-code"
2
3/** One synthesis or playback process; closing its stream also kills the child. */
4export class SpeechProcess {
5  private stream: HookStream<ProcessSpawnChunk, ProcessSpawnResult> | undefined
6
7  get isRunning(): boolean {
8    return this.stream !== undefined
9  }
10
11  async stop(): Promise<void> {
12    await this.stream?.return({ code: null, signal: "SIGTERM" }).catch(() => undefined)
13  }
14
15  /** `onStderr` is given the stderr read so far each time more comes. */
16  async read(stream: HookStream<ProcessSpawnChunk, ProcessSpawnResult>, onStderr?: (stderr: string) => void) {
17    this.stream = stream
18    // Closing a stream rejects its result; observe that rejection even during cancellation.
19    const result = stream.result.catch(() => ({ code: null, signal: "SIGTERM" }))
20    let stdout = ""
21    let stderr = ""
22    try {
23      for await (const piece of stream) {
24        // Bound output so a noisy command cannot fill memory.
25        if (piece.stream === "stdout") stdout = (stdout + piece.text).slice(0, 4_194_304)
26        else {
27          stderr = (stderr + piece.text).slice(0, 4_194_304)
28          onStderr?.(stderr)
29        }
30      }
31      return { ...(await result), stdout, stderr }
32    } finally {
33      if (this.stream === stream) this.stream = undefined
34    }
35  }
36}
37
hooks/settings.ts 69 lines
1import type { PluginOptions } from "claude-code"
2
3import type { PickerOption, Setting } from "../types"
4
5import type { ReadMode, TtsConfig } from "./config"
6import { type EngineName, ENGINES, type LoadedEngine } from "./engines"
7import type { Pin, Pins } from "./pins"
8
9export const MODES: readonly ReadMode[] = ["stream", "final", "notify"]
10export const MODE_LABELS: Record<ReadMode, string> = {
11  stream: "stream  返答を一文ずつ、流れてくるそばから",
12  final: "final   ターンが終わってから最終的な返答だけ",
13  notify: "notify  完了・エラーなどの短い通知だけ",
14}
15export const SPEEDS = ["0.8", "1", "1.1", "1.2", "1.5", "2"]
16export const VOLUMES = ["0.5", "0.75", "1", "1.25", "1.5"]
17
18/** A setting change ready to save: where it goes, and how it reads before and after. */
19export type Change =
20  | { label: string; previous: string; next: string; config: { key: string; value: string | number } }
21  | { label: string; previous: string; next: string; pins: (stored: Pins) => Pins }
22  | { error: string }
23
24/** The settings in effect, which a change is measured against. */
25export type Current = { options: PluginOptions; config: TtsConfig; engine: LoadedEngine; cwd: string; pin: Pin | undefined }
26
27/** What saving `value` for `setting` changes; while pinned, engine and voice go to the pin. */
28export function planChange(setting: Setting, value: string, { options, config, engine, cwd, pin }: Current): Change {
29  const pinned = (update: (base: Pin) => Pin) => (stored: Pins) => {
30    const base = stored[cwd] ?? pin
31    return base === undefined ? stored : { ...stored, [cwd]: update(base) }
32  }
33  switch (setting) {
34    case "mode":
35      if (!MODES.includes(value as ReadMode)) return { error: `mode is one of ${MODES.join(", ")}` }
36      return { label: "mode", previous: config.mode, next: value, config: { key: "tts.mode", value } }
37    case "speed":
38    case "volume": {
39      const scale = Number(value)
40      if (!(scale > 0 && scale <= 4)) return { error: `${setting} is a number above 0, up to 4` }
41      const previous = String(setting === "speed" ? options.speed : config.volume)
42      return { label: setting, previous, next: String(scale), config: { key: `tts.${setting}`, value: scale } }
43    }
44    case "engine": {
45      if (!(value in ENGINES)) return { error: `engine is one of ${Object.keys(ENGINES).join(", ")}` }
46      const name = value as EngineName
47      if (pin === undefined) return { label: "engine", previous: config.engine, next: name, config: { key: "tts.engine", value: name } }
48      return { label: "engine (this directory)", previous: config.engine, next: name, pins: pinned(base => ({ ...base, engine: name })) }
49    }
50    case "voice": {
51      const { voices } = engine
52      if (voices === undefined) return { error: `engine=${config.engine} has no voices; set it up in /config` }
53      if (pin === undefined) return { label: "voice", previous: voices.current, next: value, config: voices.select(value) }
54      const name = config.engine
55      return {
56        label: "voice (this directory)",
57        previous: voices.current,
58        next: value,
59        pins: pinned(base => ({ ...base, voices: { ...base.voices, [name]: value } })),
60      }
61    }
62  }
63}
64
65/** A choice as a text listing shows it: its id, then its name where it has one. */
66export function optionLine(option: PickerOption): string {
67  return option.label === undefined ? `  ${option.value}` : `  ${option.value}: ${option.label}`
68}
69