SLOPSHOPPER

tako

tako terminal integration: reports this pane's Claude Code state (context, rate limits, turn) to tako and shows tako's status in a band above the prompt (with…

panebandspinnerrowsguardcommand
★ 1v0.0.0GPL-3.0updated 2026-10-26takushio2525/tako/crates/tako-core/claude-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tako
│ ┃ tako ✕ › fix the failing auth test and add an audit log call │ ┃ No reply from tako (outside a tako pane, or │ ┃ tako has stopped) ⏺ Read(src/auth.ts) │ ┃ [ Hide band ] ⎿ Read 6 lines │ ⏺ 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 · tako
No reply from tako (outside a tako pane, or tako has stopped) [ Hide band ]
README

tako

AI エージェント時代の、集約監視に特化した高速 GUI ターミナル A fast GUI terminal built for the AI-agent era — monitor your whole agent fleet in one tab.

開発中です。macOS で動作し、Windows は移植を進めています(対応状況)。 In development. Runs on macOS; the Windows port is in progress.

ドキュメント / Documentation — tako.takushio2525.com セットアップ ・ クイックスタート ・ CLI リファレンス ・ MCP ツール一覧 ・ オーケストレーション

なぜ tako? / Why tako?

Claude Code のような AI エージェントを使う開発では、1 つの作業が「エージェント本体 + 子エージェント + dev サーバー + ログ」に分裂し、既存ターミナルではタブやウィンドウに散らばってしまいます。tako は 「1 グループ = 1 タブ」 で、エージェントが起動した子プロセスのペインを同じタブ内に自動で生やし、全体をひと目で監視できるようにします。

Working with AI agents like Claude Code, a single task naturally splits into the agent itself, sub-agents, dev servers, and logs — scattered across tabs and windows in existing terminals. tako keeps one group in one tab: panes for agent-spawned processes appear automatically right next to their parent, so you can watch the whole fleet at a glance.

特徴 / Features

  • エージェント集約監視 / Agent fleet monitoring — 3 層の検知・制御(汎用 CLI、設定ゼロで使える内蔵 MCP サーバー、opt-in のパッシブ検知)/ Three integration layers: a generic CLI, a built-in zero-config MCP server, and opt-in passive detection
  • Zed 級の速度 / Zed-class speed — Rust + GPUI + alacritty_terminal によるネイティブ GPU 描画 / Native GPU rendering, no Electron
  • 軽量ワークスペース / Lightweight workspace — cwd 連動ファイルツリー、自動更新されるコード / Markdown / 画像 / PDF プレビュー、git graph / cwd-aware file tree, live code / Markdown / image / PDF previews, git graph
  • セッション永続化 / Persistent sessions — tmux(Windows は psmux)があれば、tako を再起動しても実行中プロセスと画面がそのまま復元される(無い場合はタブ・ペイン構成と cwd の復元まで)/ With tmux — psmux on Windows — running processes and screen contents survive a restart; without it, the tab/pane layout and cwds are restored
  • クロスプラットフォーム / Cross-platform — macOS 先行、Windows 対応必須 / macOS first, Windows is a hard requirement

インストール / Install

配布しているビルド済みバイナリは macOS(Apple Silicon / macOS 11.0 以降) と Windows(x64 / Windows 10 バージョン 1809 以降) 向けで、どちらも同じリリースに載ります。 The prebuilt binaries target macOS (Apple Silicon, macOS 11.0+) and Windows (x64, Windows 10 version 1809+) — both ship in the same release.

macOS: Homebrew(推奨) / macOS: Homebrew (recommended)

brew install --cask takushio2525/tako/tako

更新は brew upgrade --cask takushio2525/tako/tako、またはアプリ内の更新通知から行えます。 tako CLI も同時に PATH へ入るため、tako コマンドがそのまま使えます。

Update with brew upgrade --cask takushio2525/tako/tako, or from the in-app update notification. The cask also links the tako CLI into your PATH.

macOS: zip を手動で / macOS: manual zip

GitHub Releases から tako-vX.X.X-macos-arm64.zip を取得します。 Grab tako-vX.X.X-macos-arm64.zip from the Releases page.

  1. zip をダブルクリックで展開し、tako.app を /Applications へドラッグ / Extract and drag tako.app into /Applications
  2. 未署名のため初回起動時に Gatekeeper の警告が出ます / macOS Gatekeeper warns on first launch (not notarized yet):
  3. tako.app をダブルクリックして警告が出たら一旦キャンセル / Double-click, then cancel the warning
  4. システム設定 → プライバシーとセキュリティ を開く / Open System Settings → Privacy & Security
  5. 下部の「"tako"は開発元を確認できないため〜」の隣の 「このまま開く」 をクリック / Click "Open Anyway" next to the tako warning
  6. もう一度 tako.app を起動すると「開く」ボタンが表示される / Launch again and click "Open"

Windows: インストーラー / ポータブル zip / Windows: installer or portable zip

GitHub Releases から次のどちらかを取得します(Windows 版は macOS 版と同じリリースに載ります)。動作要件は Windows 10 バージョン 1809(ビルド 10.0.17763)以降 / x64 です。 Grab either of these from the Releases page (Windows builds ship in the same release as the macOS ones). Requires Windows 10 version 1809 (build 10.0.17763) or later, x64.

  • tako-vX.X.X-windows-x86_64.exe — 標準のインストーラー。管理者権限は要りません(%LOCALAPPDATA%\Programs\tako に入り、スタートメニュー登録と tako コマンドの PATH 追加まで行います)/ Recommended installer. No administrator rights required (it installs into %LOCALAPPDATA%\Programs\tako, adds the Start menu entry, and puts tako on your PATH)
  • tako-vX.X.X-windows-x86_64.zip — 展開して置くだけのポータブル版。tako-app.exe(本体)と tako.exe(CLI)は同じフォルダに置いたまま使ってください / Portable build. Keep tako-app.exe (the app) and tako.exe (the CLI) in the same folder
  • 未署名のため SmartScreen の警告が出たら 詳細情報 → 実行 で進めてください / Unsigned, so if SmartScreen warns you, click More info → Run anyway

セッション永続化には psmux を入れてください(Windows で tmux と同じ役割を担います)。 Install psmux for persistent sessions; it plays the same role as tmux on Windows.

winget install marlocarlo.psmux

移植は途中です。手順の詳細は セットアップ、どの機能が使えるかは Windows 対応状況 にまとめてあります。 The port is still in progress: see Setup for the full walkthrough and Windows support status for what works today.

使い始める / Getting started

素のターミナルとして使うなら、起動すればそのまま使えます。AI 連携を使う場合は tako 内のターミナルで次の 2 つを実行します。 As a plain terminal, just launch it. To use the AI integration, run these two commands inside tako:

tako setup     # 初回のみ。claude / codex / agy を検出して設定を整える
tako master    # 司令塔の AI(マスター)を今いるペインで起動する

あとは日本語で頼むだけです。マスターが作業役の AI(worker)を隣のペインに立ち上げ、指示を渡し、完了を見届けて報告します。

「~/Documents/webapp にあるリポジトリを管理対象に追加して」
「webapp の README の誤字を直しておいて」

オーケストレーションを使わず 1 対 1 で相談したいときは tako solo。専用タブで動かしたいときは tako master --tab です。 初回起動時はタブバー下のバナー(および Cmd+K のコマンドパレット)から同じ操作ができます。 詳しい流れはクイックスタート、設定項目はセットアップガイドにあります。

tako setup detects your installed and authenticated agent CLIs (claude / codex / agy) and fills in the rest with previous or safe default values — with a single authenticated CLI it asks nothing. tako master then starts the orchestrator in the current pane, and you talk to it in plain language; it spawns workers next to itself and reports back. Use tako solo for one-on-one work without orchestration, and tako master --tab for a dedicated tab.

Claude Code 連携 / Claude Code integration

tako 内の Claude Code からペイン操作(分割・送信・読み取り等)を使うには、初回 1 回だけ MCP サーバーの接続設定が必要です(以後はどのプロジェクトでも設定ゼロ)。

tako setup-mcp

Claude Code のユーザー設定に tako MCP サーバーを自動登録します(内部で claude mcp add --scope user を呼び出します)。 プロジェクト単位にしたい場合は tako setup-mcp --project(カレントディレクトリの .mcp.json に追加)。 tako アプリが起動中なら、Claude Code に「tako の MCP を設定して」と頼んでも設定できます(MCP ツール tako_setup_mcp)。 旧バージョンが ~/.claude/settings.json に書いた無効な設定は自動で掃除されます。

This registers the tako MCP server in Claude Code's user config (internally claude mcp add --scope user); --project writes to the current directory's .mcp.json instead. If tako is running you can also ask Claude Code to "set up tako MCP" (the tako_setup_mcp tool). Outside tako the bridge exposes 0 tools and stays out of the way.

claude CLI から登録する場合:

claude mcp add --scope user --transport stdio tako -- /Applications/tako.app/Contents/MacOS/tako mcp serve

command のパスは tako CLI のインストール場所に合わせてください(which tako で確認できます)。

設定ファイルを直接書く場合は ~/.claude.json の mcpServers に以下を追加します(既存のキーを壊さないよう注意)。プロジェクト単位ならプロジェクトルートの .mcp.json に同じ構造を書きます。

{
  "mcpServers": {
    "tako": {
      "type": "stdio",
      "command": "/Applications/tako.app/Contents/MacOS/tako",
      "args": ["mcp", "serve"],
      "env": {}
    }
  }
}

リモートアクセス / Remote access

tako remote start は、外出先のスマホのブラウザから tako のペインを見て操作するための API サーバーを起動します。既定で無効で、明示的に起動したときだけ動きます。セットアップは tako remote setup の対話ウィザードが案内します。

通信は Tailscale の serve が HTTPS → ループバック TCP(127.0.0.1 のエフェメラルポート)をプロキシする構成です。daemon の待ち受けはループバックだけにバインドされるので、LAN や外部ネットワークからは到達できません。URL は tailnet 内にのみ存在し、WireGuard でエンドツーエンド暗号化されます。認証は二層で、層①が tailscale whois による tailnet ノードの検証、層②が機器ペアリング(初回接続時に Mac 画面の承認ダイアログを通すまで画面データを受け取れない)です。仕組みの詳細はリモートアクセスのドキュメントにあります。

使う前に必ず読んでください / Read before use:

  • これは正規の遠隔操作ツールです。 接続すると、リモートのブラウザからあなたのターミナルへ任意のキー入力・コマンドを送信できます(=実質的にシェルへのフルアクセス)。自分の端末を自分で操作する目的でのみ使ってください。他人の端末に無断で導入・接続する用途のものではありません。
  • 接続 URL を共有しないでください。 URL 自体にトークンは含まれませんが、tailnet 内の端末からはアクセス可能です。SNS やスクリーンショットで公開しないでください。
  • 到達できるのは同じ tailnet の端末だけです。 それでも tailnet 内の全端末を信頼できない場合(共有 tailnet 等)は、この機能を使わないでください。Tailscale アカウント自体の保護(2 要素認証・tailnet lock)も重要です。

tako remote start launches an API server that lets you drive tako's panes from a phone browser. It is disabled by default. Tailscale serve proxies HTTPS to a loopback TCP listener (127.0.0.1, ephemeral port), so the daemon is not reachable from your LAN or the internet; see the remote access docs for how it works. Treat it as a legitimate remote-control tool: once connected, the remote browser can send arbitrary keystrokes and commands to your terminal — effectively full shell access. Use it only to control your own machine, never share the connection URL, and do not enable it if you cannot trust every device on your tailnet.

ソースからビルド / Build from source

開発中は cargo run -p tako-app がそのまま使えます(バンドル不要)。 For development, plain cargo run -p tako-app works without bundling.

tako.app を生成して /Applications へ配置する場合:

# dist/tako.app を生成(--verify でバンドル版のセルフテストも実行)
scripts/build-app.sh --verify

# /Applications へ配置(配置後、ビルド出力の dist/tako.app は片付けられる)
scripts/build-app.sh --install

同じ .app が 2 つディスク上にあると macOS の Launch Services が両方を登録し、Finder の「このアプリケーションで開く」に tako が 2 つ並びます。--install は配置後にビルド出力を消して登録も外すので、候補は /Applications の 1 つだけになります。

アイコンの再描画には rsvg-convert(brew install librsvg)を使います。無い場合は同梱の PNG から自動でフォールバックします。

scripts/build-app.sh --verify creates dist/tako.app and runs the bundled self-test; --install copies it into /Applications, then removes the build copy and unregisters it from Launch Services so Finder's "Open With" lists tako only once. Icon rendering uses rsvg-convert (brew install librsvg) with a PNG fallback.

開発コマンド / Development commands

cargo build --workspace
cargo test --workspace
cargo fmt --all --check && cargo clippy --workspace --all-targets -- -D warnings

AI エージェント向けの規約は AGENTS.md、詳細仕様は .agent/ にあります。 Conventions for AI agents live in AGENTS.md; detailed specs are in .agent/.

トラブルシューティング / Troubleshooting

Homebrew の Swift toolchain(copy-xattrs.swift)が CommandLineTools/SDK のバージョン不整合でビルド失敗し、brew upgrade --cask tako が中断されると、cask 台帳から tako が消えているのに /Applications/tako.app の実体は残る「詰み状態」が発生することがあります。この状態では brew install --cask tako も「It seems there is already an App at '/Applications/tako.app'」で失敗します。

復旧方法(いずれか):

# 方法 1: tako CLI で修復(推奨。tako が起動している場合)
tako update repair

# 方法 2: brew で台帳を再締結
brew install --cask takushio2525/tako/tako --force

# 方法 3: brew を諦めて zip で手動更新
tako update apply-zip

tako update status で現在の配布系統を確認できます。install_method が broken-brew と表示される場合、上記の復旧が必要です。

根本原因の解消: Homebrew の Swift toolchain エラーが根本原因の場合、以下で Xcode CommandLineTools を再インストールすると brew 側の問題も解消します。

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

macOS 26 (Tahoe) 以降では、tako 内で動く AI エージェント(Claude Code 等)のサンドボックス化されたコマンドが iCloud Drive・Google Drive・他アプリのデータ領域に触れるたびに、macOS が対象ごとに個別の許可ダイアログを tako.app 名義で表示します(tako 自身がこれらの領域を読むわけではありません)。対象の数だけダイアログが出るため、頻発する場合は以下で恒久解消できます。

システム設定 → プライバシーとセキュリティ → フルディスクアクセス → tako を ON

フルディスクアクセスは個別許可の上位互換のため、以後このダイアログは表示されません。

v0.2.6 以降は署名の designated requirement が identifier 固定になり、付与した許可(フルディスクアクセス・個別許可とも)が再ビルド・アプリ内更新をまたいで保持されます。v0.2.5 以前からの更新直後は署名要件の移行のため 1 回だけ再許可が必要です。

タブやターミナルペインが突然大量に消えても、実体のプロセスはバックエンド tmux セッションの中で生き続けていることがほとんどです(AI エージェントは会話の文脈ごと生存しています)。以下の順で復旧してください。

  1. レイアウトのバックアップから戻す(推奨): ペイン数が大きく減る保存の直前には、レイアウトが自動で世代バックアップされています。
   tako recover                 # バックアップ世代の一覧(タブ数 / ペイン数 / 更新時刻)
   # tako を終了(Cmd-Q)してから:
   tako recover --apply 1       # 直前の世代を復元
   # tako を再起動 → 実行中プロセスごと画面に戻ります
  1. 個別にセッションを取り込む: バックアップが無い・一部だけ戻したい場合は、生きているセッションを直接タブへ取り込めます。
   tako tmux list               # バックエンドセッションと cwd の一覧
   tako tab new                 # 受け皿のタブを作る(出力の pane ID を控える)
   tako tmux open --socket tako --pane <ペインID> <セッション名>

セキュリティ / Security

脆弱性は公開の Issue に書かず、SECURITY.md の非公開の窓口から知らせてください。 / Please report vulnerabilities privately as described in SECURITY.md, not in public issues.

ライセンス / License

GPL-3.0-or-later — 依存クレート(zlog / ztracing、Zed リポ由来)が GPL-3.0 のため。

同梱している第三者成果物(zsh-autosuggestions・ファイルアイコン・スマホ用画面の JavaScript とフォントほか)の告知は THIRD-PARTY-NOTICES.md、配布バイナリに静的リンクしている Rust クレートのライセンス本文と著作権表示は THIRD-PARTY-LICENSES.md にあります。 Notices for bundled third-party works are in THIRD-PARTY-NOTICES.md; the license texts and copyright notices of the Rust crates linked into the binaries are in THIRD-PARTY-LICENSES.md.

配布しているバイナリに対応するソースコードは、GitHub Releases の各リリースのタグにあります。tako は無保証です(GPL-3.0 第 15 条・第 16 条。詳細は LICENSE)。 The source code for each released binary is the tag of that release on GitHub Releases. tako comes with ABSOLUTELY NO WARRANTY (sections 15 and 16 of the GPL-3.0; see LICENSE).

Source 2 files
hooks/register.ts 1831 lines
1// tako mod(#1877 / S1 #1879 / S3 #1881 / S7-3 #1962): このペインの Claude Code の状態を集めて tako へ
2// 報告し、tako の応答(帯・バー・サイドバーの材料)で Claude Code の画面に tako の状況を出す。
3// 設計の正本は .agent/plans/2026-10-tako-mod.md §5(規約)・§7 S3(帯・サイドバー)・§9.3 / §9.5 / §9.6(S7)。
4//
5// 画面に出すもの:
6// - 帯(プロンプトの上): **他の mod の行を包み**(next(e) の答えを上に並べる = 利用者の他の mod の帯を
7//   消さない。#1962)、その下に tako の行を**ボタン込みで 1 行**。tako の行はこのペインの名前・タブ・worker 数と
8//   要注意の数・カスタムボタン(ui.json の buttons。既定は /compact)。並びと出すものは ui.json の
9//   band.segments。幅(bodyColumns)に収まらなければ優先度の低いものから落とし、それでも溢れたら末尾を切る。
10//   権限ダイアログ・質問の表示中は Claude Code が帯ごと隠すので「承認待ち」は出さない
11// - 使用制限・ctx のバー(#1962): 入力欄の下の行(PromptHint)の末尾に `5h ▁ 4% 7d ▂ 22% ctx ▁ 6%`。
12//   描くかは tako が決める(view.usage_bar。利用者の statusLine が既に出していれば描かない)。描いたら
13//   報告の renders.usage_bar で返し、tako は画面下のステータスバーの claude の区画を引っ込める
14// - コマンドカード(#1963): AI の `tako_show_command` の行(会話の中で「Called tako」に畳まれる ToolGroup を
15//   展開した ToolUse)をカード(ラベル・コマンドを Code で・実行記録)に描き替える。押す口は 2 つ:
16//   会話の行のコマンドごとの `[ 実行 ]` / `[ コピー ]`(**クリック 1 回**。#2159。tako がクリックを TUI へ
17//   渡し(#1961 = view.cards.click)、全画面のときだけ置く = 押せないボタンを見せない)と、帯の tako の行の
18//   `カード N` と `y: コピー` / `r: 実行`(ホットキー。クリックが届かない main screen・`tako mouse off` でも
19//   押せる)。正本は tako の store(応答の view.cards)。帯に押せる形で描いたカードの
20//   id を報告の renders.cards で返し、tako はそのカードを GPUI のカード帯から外す。Copy は $.ui.copy
21//   (他の mod に拒まれたら tako の CLI の show-command --copy へ落とす)、Run / 閉じるは tako が組んだ引数。
22//   Run は同じコマンドを 2 回走らせない: 押した CLI が返るまでと返ってから RUN_REPEAT_MS の間の押下は捨て
23//   (ダブルクリックの 2 打目)、その後は tako の dispatch が実行中の再実行を断る(GPUI のカードと同じ判断)
24// - チャット風の描画(#1964): 利用者の発話(composer / bridge)を右寄せの吹き出しに・AI の返答のコードブロックの
25//   下に Copy のボタン(論理文字列 = 画面の折り返しは混ざらない。クリックで押す)と帯の「最新のコードをコピー」
26//   (キーで押す)・ツールの呼び出しを 1 行の要約に(ToolGroup は展開して 1 呼び出し 1 行。「詳細」で
27//   エンジンの行に戻す)。どれを描くかは tako が決める(view.chat。ターミナル表示の既定はコードのコピーだけ)。
28//   どれも next(e) の答えを包む(エンジンの行なら置き換え、他の mod が描いていればその描画を中に / 上に残す)。
29//   今あてている組は報告の renders.chat で返し、GUI モードで tako が mod にチャットを任せたペインは
30//   GPUI のチャットビューの代わりにこの画面がそのまま出る。会話の行が足された数(chat_seq)も報告に載せ、
31//   GPUI のチャットが表に出ているペイン(view.chat.notify)ではすぐ報告する = transcript を通知で読み直す
32// - `/tako`: サイドバーのペイン($.ui.open)に詳細。頼まれずには開かない(開くのはコマンドだけ)
33// - 帯を隠すトグル: 正本は tako の ui.json の band.hidden(#1960)。$.store の `band`({ hidden, at })は
34//   この読み込み元の写しで、`/tako band on|off`・ペインのボタンで変えたら報告の band.toggled_at で tako へ
35//   渡り、tako が ui.json へ取り込む。tako からは応答の view.band_request で届く。時刻の新しいものが勝つ
36// 何を出すかの判断は tako 側(tako_core::claude_mod::band_view)。ここは幅に合わせて詰めて描くだけ。
37// ボタンの tako の操作・shell も、叩く CLI の引数は tako が組んで view.button_args で渡す
38// A/B の TAKO_1877_S7_LEGACY では view.band_style が 's3' で届き、S3 の描き方(next を包まない・
39// ボタンとバーなし・renders を報告しない)へ戻る
40//
41// 守っていること(§5 の規約。番犬 crates/tako-control/tests/issue1879_claude_mod_watchdog.rs が走査する):
42// - 観測だけで判断を奪わない: すべての on(...) は next(e) へ流し、.catch(($, e, next) => next(e)) を付ける
43//   (mod が壊れても tool call と権限ダイアログを止めない。権限を勝手に許可しない)
44// - フックの中で CLI を待たない: フックは状態を書き換えて dirty を立てるだけ。CLI は 1 秒の flush が叩く
45//   (例外は session.end の最後の 1 回だけ。待たないとプロセスが先に終わって届かない)
46// - tako の外では休眠: TAKO_PANE_ID か TAKO_CLI が無ければ何も呼ばない
47//   (CLI は接続できないと control.json へ落ちるので、tako の外から叩くと別のインスタンスへ繋がりうる)
48// - 失敗で騒がない: CLI の失敗は $.ui.log(…, { to: 'debug' }) だけ
49// - $ を渡す補助関数はファイル最上位の関数宣言(validate の規則)
50// - 会話の本文・プロンプト・ツールの引数は報告に載せない(ツール名だけ)
51//
52// 例外(#2050 の送信時の確認 = 鍵らしき文字の 2 段目): prompt.submit だけは、人の入力(composer = その
53// 端末での Enter・bridge = Remote Control)を送る前に tako へ判定させ、答えが confirm なら Claude Code の
54// 選択ダイアログで「やめる / 送る」を確かめ、やめたら送信を落として({ drop })文を入力欄へ戻す。判定は tako の 1 実装
55// (`tako paste-guard check --pane N`。**本文は標準入力で渡す** = argv にもログにも残さない)で、ここは
56// 答えに従うだけ。tako が流した値・人が確かめた値は tako が外して答える(worker の初回プロンプトで
57// 止めない)。CLI が失敗・時間切れ・mod が投げたら**送信を通す**(.catch で next(e)。壊れた mod が
58// 送信を止めない)。デバッグログへは終了コードだけ(本文・伏せ字を書かない)
59import type {
60  EngineInterface,
61  Register,
62  RenderElement,
63  RenderInput,
64  SessionRateLimit,
65  Timer,
66  UiPressArgument,
67} from 'claude-code'
68
69import type {
70  TakoBandSegment,
71  TakoButton,
72  TakoCard,
73  TakoCardCommand,
74  TakoChat,
75  TakoChatRenders,
76  TakoLimitsSeen,
77  TakoModReport,
78  TakoPress,
79  TakoRateLimit,
80  TakoRenders,
81  TakoThemeColor,
82  TakoTurn,
83  TakoView,
84  TakoWorker,
85} from '../types'
86
87// 展開時(tako_core::claude_mod::install)に tako の版へ置き換わる
88const MOD_VERSION = '__TAKO_MOD_VERSION__'
89/** 変化があるときの報告の最短間隔 */
90const FLUSH_MS = 1_000
91/** 変化が無くても送る間隔(tako は 45 秒で失効させる = 2 回の取りこぼしまで許す) */
92const HEARTBEAT_MS = 15_000
93/** CLI 1 回の上限。tako が落ちていれば 10 ms 未満で exit 1 になる */
94const REPORT_TIMEOUT_MS = 5_000
95/** session.end の最後の報告だけは待つので、上限は短く */
96const FINAL_TIMEOUT_MS = 2_000
97/**
98 * 送信時の確認(#2050)で叩く CLI 1 回の上限。tako が詰まっていたら待たずに送信を通す
99 * (実測の所要は数十 ms。利用者の Enter を数秒より長く止めない)
100 */
101const GUARD_TIMEOUT_MS = 3_000
102/** 送信時の確認で見る出どころ(人の入力だけ。AI・仕組みの送信 = peer / plugin / 通知 等は止めない) */
103const GUARD_ORIGINS: readonly string[] = ['composer', 'bridge']
104/** 送信時の確認の伏せ字を並べる上限 */
105const GUARD_SHOW_MAX = 3
106/** tako の応答(帯の材料)がこれより古くなったら帯を消す(tako の鮮度 FRESH_FOR と同じ 45 秒) */
107const VIEW_FRESH_MS = 45_000
108/** 帯の区切りの区切り文字(幅 1 の ASCII だけ。曖昧幅の文字は端末の設定で 2 桁になりうる) */
109const SEP = ' | '
110/** 帯のペイン名・タブ名を切り詰める上限(桁) */
111const NAME_MAX = 24
112/** サイドバーのペインの id($.ui.open)。描画の requestId もこれ */
113const PANE_ID = 'tako'
114/** $.store のキー(帯のトグル) */
115const BAND_KEY = 'band'
116/** 利用者が Claude Code の /plugin で止める id(tako setup が skills/tako に置いた写し = #1959) */
117const SKILLS_ID = 'tako@skills-dir'
118/**
119 * バーの棒の 8 段(#1962。tako_core::claude_mod::BAR_GLYPHS と同じ = tako が画面を読むときに
120 * mod 自身のバーを除く形。単体テストが突き合わせる)
121 */
122const BAR_GLYPHS = '▁▂▃▄▅▆▇█'
123/** 端末のボタンの枠(`[ ` と ` ]`)の桁 */
124const BUTTON_CHROME = 4
125/** 帯の区切りとボタンの間・ボタンどうしの間の桁 */
126const BUTTON_GAP = 1
127/** ボタンで叩く CLI 1 回の上限(session-restart は引き継ぎの書き出しを待つので長め) */
128const PRESS_TIMEOUT_MS = 30_000
129/**
130 * カードの Run を押した CLI が返ってから、同じコマンドの Run の押下を捨てる間(#2159)。ダブルクリックの
131 * 2 打目(macOS の既定の間隔は 0.5 秒)が、すぐ終わるコマンドの終了の後に届いて 2 本目を走らせないため。
132 * 実行中の押し直しはこの後も tako の dispatch が断る(スマホ・GPUI のカードと同じ判断)
133 */
134const RUN_REPEAT_MS = 1_000
135/** 実行を断られた理由をトーストに出す上限(桁) */
136const RUN_REASON_MAX = 80
137/** ui.json が届く前(古い tako)の帯の並び(tako_core::claude_mod_ui::BandUi の既定と同じ) */
138const DEFAULT_SEGMENTS: readonly TakoBandSegment[] = ['pane', 'tab', 'workers', 'attention', 'card', 'buttons']
139/** tako の MCP の `tako_show_command`(`mcp__<登録名>__tako_show_command`。登録名は利用者の環境次第) */
140const SHOW_TOOL = /^mcp__.+__tako_show_command$/
141/** 帯のカードのコマンドの頭を切り詰める桁 */
142const CARD_HEAD_MAX = 32
143/** 帯のカードのボタン(plain = `y: コピー`)のホットキーと `: ` の桁 */
144const PLAIN_CHROME = 3
145/** ui.json が届く前の色(tako_core::claude_mod_ui::ColorsUi の既定と同じ) */
146const DEFAULT_COLORS: { accent: TakoThemeColor; warn: TakoThemeColor; dim: TakoThemeColor } = {
147  accent: 'suggestion',
148  warn: 'warning',
149  dim: 'subtle',
150}
151
152// $.state(セッションの値。描画が購読するので、書けば読み手が描き直される)
153const VIEW = { plugin: 'tako', key: 'view' } as const
154const HIDDEN = { plugin: 'tako', key: 'bandHidden' } as const
155// 使用制限の窓ごとの観測時刻(#1903)。$.state に置くのはホットリロード(tako の更新で mod が
156// 書き換わる)をまたいで残すため。モジュール変数だと読み込み直しのたびに全窓を「今」の観測にしてしまう
157const LIMITS_SEEN = { plugin: 'tako', key: 'limitsSeen' } as const
158// 帯で選んでいるカードのコマンド(#1963。n で次へ。描画が購読する)
159const CARD_CURSOR = { plugin: 'tako', key: 'cardCursor' } as const
160// 最新の AI の返答のコードブロック(#1964。帯の「最新のコードをコピー」が写す。報告には載せない)
161const CHAT_CODES = { plugin: 'tako', key: 'chatCodes' } as const
162// ツールの要約から「詳細」で開いた呼び出し(#1964。開いた行はエンジンの描画に戻す)
163const TOOL_OPEN = { plugin: 'tako', key: 'toolOpen' } as const
164/** 開いた呼び出しを覚える上限(古いものから忘れる) */
165const TOOL_OPEN_MAX = 64
166/** 吹き出しにする発話の出どころ(人の入力 = その端末の composer と Remote Control の bridge) */
167const BUBBLE_ORIGINS: readonly string[] = ['composer', 'bridge']
168/** 吹き出しを右へ寄せるとき左に空ける桁の下限(幅の 1/5 と比べて大きい方) */
169const BUBBLE_INDENT_MIN = 4
170
171// モジュール変数。ホットリロードで消えるが、そのとき session.start が再発火して張り直す
172let cli: string | undefined
173// このペインの tako の ID(TAKO_PANE_ID。送信時の確認 = #2050 で tako に渡す)
174let paneId: string | undefined
175let timer: Timer | undefined
176let dirty = false
177let sending = false
178let lastSentAt = 0
179let turn: TakoTurn = 'idle'
180let pendingTool: string | undefined
181let effort: string | undefined
182let lastTurn: { duration_ms: number; reason: string } | undefined
183// 帯(S3): 最後に受け取った tako の材料の時刻・JSON(同じなら $.state を書かない = 無駄に描き直さない)
184let viewAt = 0
185let lastViewJson: string | undefined
186// 最後に受け取った材料の描き方(#1962。's3' = A/B。renders を報告するかを決める)
187let lastStyle: 's3' | undefined
188let lang = 'en'
189// `/tako` の説明文を登録した言語(tako の表示言語が応答で分かったら登録し直す)
190let commandLang: string | undefined
191// 帯のトグル($.store の写し)と、それを変えた時刻(中継・他のセッションとの突き合わせ)
192let bandHidden = false
193let bandToggledAt: number | undefined
194// 直近の描画(報告で tako へ返す。何を描いたかは区切りの種類だけ)
195let bandShown = false
196let bandColumns: number | undefined
197let bandSegments: string[] = []
198let lastBandKey: string | undefined
199// classic 系のイベント(classic.PreToolUse 等)がこのセッションの mod へ届いているか。
200// 組織アカウントでは 1 つも届かないことがある(2.1.294 で実測。FR-2.42.7)。
201// 届かないときの権限待ちは tool.check の判定から確かなものだけを拾う
202let classicEvents = false
203// 利用者が /plugin で止めたかを最後に見た時刻(#1959。heartbeat と同じ間隔で見直す)
204let lastDisabledCheck = 0
205// 利用者の statusLine の有無(#1962。設定と同じ間隔で見直す。読めなければ undefined = tako は画面だけで見ない)
206let statusLine: boolean | undefined
207// Claude Code に今あるスラッシュコマンドの名前(#1962。無い名前の slash ボタンは描かない。
208// 読めなければ undefined = 絞らない)
209let commandNames: Set<string> | undefined
210// 描いたもの(#1962。報告の renders): 帯のボタンの数・帯 / 入力欄の下の行にバーを描いたか・
211// 起きてからフックが呼ばれたか(帯だけ呼ばれない = 外側の他の mod が next を呼ばずに帯を描いている)
212let bandButtons = 0
213let bandBar = false
214let hintBar = false
215let bandHookSeen = false
216let hintHookSeen = false
217// 最後に押されたボタン(語彙の種類と成否だけ)
218let lastPress: TakoPress | undefined
219// コマンドカード(#1963): 最後の応答に view.cards があったか(無い = tako が描かせない = renders.cards を
220// 送らない)・直近の帯で押せる形で描いたカードの id・最後に見たいちばん新しいカード(新しいカードが
221// 来たら帯の選択をそれへ移す)
222let cardsOffered = false
223let bandCards: number[] = []
224let newestCard: number | undefined
225// カードの Run の二重押しの番(#2159): `カード id:コマンドの番号` → この時刻(epoch ms)まで押下を捨てる
226// (CLI が返るまでは無限 = 押した後の CLI の往復中の 2 打目も捨てる)。帯と会話の行のボタンで共有する
227const runBusy = new Map<string, number>()
228// チャット風の描画(#1964): 最後に受け取った view.chat(今あてている組 = renders.chat)と、起きてから
229// 足された本筋の会話の行の数(chat_seq。数だけ = 本文は持たない)
230let chatView: TakoChat | undefined
231let chatSeq = 0
232
233// effort の値を読む。turn.step は文字列(2.1.294 の実測: "medium")、classic 系は { level } で運ぶ
234function effortLevel(value: unknown): string | undefined {
235  if (typeof value === 'string') return value
236  if (typeof value === 'object' && value !== null && 'level' in value) {
237    const level = (value as { level: unknown }).level
238    if (typeof level === 'string') return level
239  }
240  return undefined
241}
242
243// 使用制限に観測時刻を付ける(#1903)。窓ごとに % か resetsAt が変わったときだけ今の時刻を打ち、
244// 変わらなければ前に打った時刻のまま送る。heartbeat で打ち直すと、1 時間放置したペインの古い % も
245// 「今」の観測に見え、tako が同じアカウントの値を最新の観測で束ねられない(設計書 §6)。
246// $.state を読めない・書けないときは今の時刻を打つ(報告そのものは止めない = §5 の「失敗で騒がない」)
247async function stampLimits($: EngineInterface, limits: readonly SessionRateLimit[], at: number): Promise<TakoRateLimit[]> {
248  let seen: TakoLimitsSeen = {}
249  try {
250    seen = (await $.state.get(LIMITS_SEEN)).value ?? {}
251  } catch (err) {
252    $.ui.log(`tako mod: limitsSeen unreadable: ${String(err).slice(0, 200)}`, { to: 'debug' })
253  }
254  const next: TakoLimitsSeen = {}
255  let changed = Object.keys(seen).length !== limits.length
256  const out = limits.map(limit => {
257    const prev = seen[limit.kind]
258    const same = prev !== undefined && prev.percent_used === limit.percentUsed && prev.resets_at === limit.resetsAt
259    if (!same) changed = true
260    const observed = same ? prev.observed_at : at
261    next[limit.kind] =
262      limit.resetsAt === undefined
263        ? { percent_used: limit.percentUsed, observed_at: observed }
264        : { percent_used: limit.percentUsed, resets_at: limit.resetsAt, observed_at: observed }
265    return { kind: limit.kind, percent_used: limit.percentUsed, resets_at: limit.resetsAt, observed_at: observed }
266  })
267  if (changed) {
268    try {
269      await $.state.set(LIMITS_SEEN, next)
270    } catch (err) {
271      $.ui.log(`tako mod: limitsSeen unwritable: ${String(err).slice(0, 200)}`, { to: 'debug' })
272    }
273  }
274  return out
275}
276
277// 利用者が Claude Code 側で tako mod を止めたか(/plugin の disable = settings の enabledPlugins に
278// false。#1959)。env の注入(inline)で読まれていても従う = 注入が利用者の選択を上書きしない。
279// 読めなければ止めていない扱い(報告は止めない = §5 の「失敗で騒がない」)。
280// 同じ 1 回の読みで statusLine の有無も控える(#1962。中身は読まない・報告に載せるのは有無だけ)
281async function userDisabled($: EngineInterface): Promise<boolean> {
282  try {
283    const settings = await $.settings.read()
284    const line = settings.statusLine
285    const next = typeof line === 'object' && line !== null
286    if (next !== statusLine) {
287      statusLine = next
288      dirty = true
289    }
290    const enabled = settings.enabledPlugins
291    return typeof enabled === 'object' && enabled !== null && (enabled as Record<string, unknown>)[SKILLS_ID] === false
292  } catch (err) {
293    $.ui.log(`tako mod: settings unreadable: ${String(err).slice(0, 200)}`, { to: 'debug' })
294    return false
295  }
296}
297
298// Claude Code に今あるスラッシュコマンドの名前を控える(#1962。slash のボタンは無い名前を描かない)。
299// 読めなければ前の値のまま(初回なら絞らない)
300async function syncCommands($: EngineInterface): Promise<void> {
301  try {
302    commandNames = new Set((await $.command.list()).map(c => c.name))
303  } catch (err) {
304    $.ui.log(`tako mod: command list unreadable: ${String(err).slice(0, 200)}`, { to: 'debug' })
305  }
306}
307
308// 休眠に入る(#1959): 理由を 1 回だけ報告して timer を止め、帯の材料を消す
309// (tako は画面の読み取りへ落ちる。次に起きるのは session.start = claude の起動し直しかホットリロード)
310async function goDormant($: EngineInterface, reason: 'user_disabled'): Promise<void> {
311  timer?.cancel()
312  timer = undefined
313  await send($, false, FINAL_TIMEOUT_MS, reason)
314  cli = undefined
315  await setView($, null)
316}
317
318// 報告を組む。欠けた値(最初の API 応答の前の ctx% など)は undefined のまま = JSON から落ちる
319async function buildReport($: EngineInterface, ended: boolean, dormant?: 'user_disabled'): Promise<TakoModReport> {
320  const at = await $.clock.now()
321  const usage = await $.session.usage()
322  const version = await $.session.version()
323  return {
324    schema: 1,
325    mod_version: MOD_VERSION,
326    claude_version: version.version,
327    session_id: await $.session.id(),
328    at,
329    model: await $.session.model(),
330    effort,
331    context: { tokens: usage.context.tokens, window: usage.context.window, percent: usage.context.percent },
332    rate_limits: await stampLimits($, usage.rateLimits, at),
333    cost_usd: usage.cost?.usd,
334    turn,
335    pending_tool: pendingTool,
336    last_turn: lastTurn,
337    classic_events: classicEvents,
338    config_dir: await $.env.get('CLAUDE_CONFIG_DIR'),
339    band: { hidden: bandHidden, shown: bandShown, columns: bandColumns, segments: bandSegments, toggled_at: bandToggledAt },
340    dormant,
341    status_line: statusLine,
342    renders: currentRenders(),
343    last_press: lastPress,
344    chat_seq: chatSeq,
345    ended,
346  }
347}
348
349// 描いたもの(#1962)。S3 の描き方(A/B)では載せない = tako は今の表示のまま(S3 の mod と同じ)
350function currentRenders(): TakoRenders | undefined {
351  if (lastStyle === 's3') return undefined
352  return {
353    band: bandShown,
354    usage_bar: hintBar ? 'prompt_hint' : bandBar ? 'band' : undefined,
355    buttons: bandButtons,
356    band_hook: bandHookSeen,
357    hint_hook: hintHookSeen,
358    // #1963: tako が描かせたときだけ(描けなかったら空 = tako は猶予の後に GPUI の帯へ出す)
359    cards: cardsOffered ? bandCards : undefined,
360    // #1964: tako が描かせた組(応答に view.chat が無ければ欠ける = tako は GPUI のチャットのまま)
361    chat: chatRenders(),
362  }
363}
364
365// 今あてているチャット風の描画の組(#1964。view.chat をそのまま返す = 描いたと言うのは tako が頼んだものだけ)
366function chatRenders(): TakoChatRenders | undefined {
367  if (chatView === undefined) return undefined
368  return { bubble: chatView.bubble, code_copy: chatView.code_copy, tool_summary: chatView.tool_summary, notify: chatView.notify }
369}
370
371// 1 回送る。応答(tako 側のスナップショット = 帯・サイドバーの材料)を $.state へ写す
372async function send($: EngineInterface, ended: boolean, timeoutMs: number, dormant?: 'user_disabled'): Promise<void> {
373  const path = cli
374  if (path === undefined) return
375  dirty = false
376  try {
377    await syncStore($)
378    const report = await buildReport($, ended, dormant)
379    lastSentAt = report.at
380    const done = await $.process.run([path, 'mod', 'report'], { stdin: JSON.stringify(report), timeoutMs })
381    if (done.exitCode !== 0) {
382      $.ui.log(`tako mod: report exit ${done.exitCode}: ${done.stderr.trim().slice(0, 200)}`, { to: 'debug' })
383    } else if (!ended && dormant === undefined) {
384      await absorb($, done.stdout)
385    }
386  } catch (err) {
387    $.ui.log(`tako mod: report failed: ${String(err).slice(0, 200)}`, { to: 'debug' })
388  }
389}
390
391// 1 秒ごとの flush。変化があれば送り、無くても 15 秒に 1 回は送る(heartbeat)
392async function tick($: EngineInterface): Promise<void> {
393  if (cli === undefined || sending) return
394  const now = await $.clock.now()
395  // tako が応答しなくなったら(落ちた・別の tako へ繋がらない)古い材料で描き続けない
396  if (lastViewJson !== undefined && lastViewJson !== 'null' && now - viewAt > VIEW_FRESH_MS) {
397    await setView($, null)
398  }
399  // 走っている間に /plugin で止められたら従う(#1959。見直しは heartbeat と同じ間隔)
400  const recheck = now - lastDisabledCheck >= HEARTBEAT_MS
401  if (!recheck && !dirty && now - lastSentAt < HEARTBEAT_MS) return
402  sending = true
403  try {
404    if (recheck) {
405      lastDisabledCheck = now
406      if (await userDisabled($)) {
407        await goDormant($, 'user_disabled')
408        return
409      }
410      await syncCommands($)
411    }
412    if (dirty || now - lastSentAt >= HEARTBEAT_MS) await send($, false, REPORT_TIMEOUT_MS)
413  } finally {
414    sending = false
415  }
416}
417
418// session.start(ホットリロードでも来る)で入口を決める。tako の外なら休眠のまま
419async function wake($: EngineInterface): Promise<void> {
420  timer?.cancel()
421  timer = undefined
422  const pane = await $.env.get('TAKO_PANE_ID')
423  const path = await $.env.get('TAKO_CLI')
424  if (pane === undefined || pane === '' || path === undefined || path === '') {
425    cli = undefined
426    paneId = undefined
427    return
428  }
429  cli = path
430  paneId = pane
431  // 利用者が /plugin で止めていれば、理由を 1 回だけ伝えて休眠する(#1959)
432  lastDisabledCheck = await $.clock.now()
433  if (await userDisabled($)) {
434    await goDormant($, 'user_disabled')
435    return
436  }
437  dirty = true
438  // ホットリロードでは $.state の材料が残っている。次の応答まで(最大 45 秒)はそれで描く
439  viewAt = await $.clock.now()
440  timer = $.clock.every(FLUSH_MS, () => {
441    void tick($)
442  })
443  // 帯の準備は報告の後ろに置き、失敗しても報告(S1 / S2)を止めない
444  try {
445    await syncStore($)
446    await registerCommand($)
447    await syncCommands($)
448  } catch (err) {
449    $.ui.log(`tako mod: band setup failed: ${String(err).slice(0, 200)}`, { to: 'debug' })
450  }
451}
452
453// `/tako` を登録する(同じ名前の登録は置き換わる = 言語が変わったら登録し直す)。
454// 説明文の頭に tako を付けない(Claude Code が一覧にプラグイン名を添える)
455async function registerCommand($: EngineInterface): Promise<void> {
456  commandLang = lang
457  await $.command.register({
458    name: 'tako',
459    description: words(lang).command,
460    argumentHint: '[band on|off]',
461    immediate: true,
462  })
463}
464
465// 最後の報告(ended: true)。tako はそのペインの報告を即座に捨てる
466async function finish($: EngineInterface): Promise<void> {
467  timer?.cancel()
468  timer = undefined
469  await send($, true, FINAL_TIMEOUT_MS)
470  cli = undefined
471}
472
473// --- 帯とサイドバー(S3 #1881)------------------------------------------------------
474
475type Words = {
476  tab: string
477  workers: (n: number) => string
478  attention: (n: number) => string
479  noWorkers: string
480  more: (n: number) => string
481  ctxPending: string
482  resetsIn: (d: string) => string
483  state: (w: TakoWorker) => string
484  thresholds: (ctx: number, limit: number) => string
485  hide: string
486  show: string
487  noView: string
488  hidden: string
489  shown: string
490  usage: string
491  notPlaced: (reason: string) => string
492  command: string
493  // コマンドカード(#1963)
494  card: (id: number) => string
495  copy: string
496  run: string
497  next: string
498  close: string
499  cardClosed: string
500  cardHint: (copy: string, run: string) => string
501  // 会話の行にボタンを置いたときの案内(#2159。キーの口は帯)
502  cardKeyHint: (copy: string, run: string) => string
503  runRefused: (reason: string) => string
504  runState: (run: NonNullable<TakoCardCommand['run']>) => string
505  // 送信時の確認(#2050)
506  guardHeader: string
507  guardQuestion: (found: string) => string
508  guardSend: string
509  guardCancel: string
510  guardDropped: string
511  guardWarned: (found: string) => string
512  // チャット風の描画(#1964)
513  copyCode: (index: number, of: number, lang: string) => string
514  latestCode: (of: number) => string
515  copied: string
516  copyRefused: string
517  toolDone: string
518  toolRunning: string
519  toolError: string
520  toolInterrupted: string
521  toolDetails: string
522  toolHide: string
523}
524
525const WORDS: Record<'ja' | 'en', Words> = {
526  ja: {
527    tab: 'タブ',
528    workers: n => `worker ${n}`,
529    attention: n => `要注意 ${n}`,
530    noWorkers: 'worker なし',
531    more: n => `ほか ${n} 本`,
532    ctxPending: '最初の応答の前',
533    resetsIn: d => `リセットまで ${d}`,
534    state: w => {
535      if (w.attention === 'permission') return '承認待ち'
536      if (w.attention === 'question') return '質問待ち'
537      if (w.attention === 'dialog') return '選択待ち'
538      if (w.state === 'limited') return '使用制限'
539      if (w.state === 'failed') return '異常終了'
540      if (w.state === 'busy') return '作業中'
541      if (w.state === 'idle') return '待機'
542      return '不明'
543    },
544    thresholds: (c, l) => `帯に ctx / 使用制限を出すのは ${c}% / ${l}% 以上`,
545    hide: '帯を隠す',
546    show: '帯を出す',
547    noView: 'tako から応答が無い(tako のペインの外か、tako が止まっている)',
548    hidden: '帯を隠した(/tako band on で戻す)',
549    shown: '帯を出した',
550    usage: '使い方: /tako(サイドバー)・/tako band on|off(帯)',
551    notPlaced: r => `サイドバーを置けない: ${r}`,
552    command: 'このペインの tako の状況をサイドバーに出す(band on|off で帯を出す / 隠す)',
553    card: id => `カード ${id}`,
554    copy: 'コピー',
555    run: '実行',
556    next: '次',
557    close: '閉じる',
558    cardClosed: 'このカードは閉じた',
559    cardHint: (copy, run) => `帯(ctrl+x → Tab)の ${copy}: コピー / ${run}: 実行`,
560    cardKeyHint: (copy, run) => `キーでは帯(ctrl+x → Tab)の ${copy}: コピー / ${run}: 実行`,
561    runRefused: reason => (reason === '' ? 'tako: 実行できませんでした' : `tako: 実行できませんでした(${reason})`),
562    runState: run =>
563      `→ ペイン ${run.pane} ${run.state === 'running' ? '実行中' : run.state === 'exited' ? `終了 ${run.exit_code ?? '?'}` : 'が閉じた'}`,
564    guardHeader: 'tako',
565    guardQuestion: found => `鍵らしき文字が入っています(${found})。このまま送りますか?`,
566    guardSend: '送る',
567    guardCancel: 'やめる',
568    guardDropped: 'tako: 鍵らしき文字が入っているので送りませんでした',
569    guardWarned: found => `tako: 鍵らしき文字を含むまま送りました(${found})`,
570    copyCode: (i, of, lang) => `コピー${of > 1 ? ` ${i}` : ''}${lang === '' ? '' : ` ${lang}`}`,
571    latestCode: of => (of > 1 ? '最後のコードをコピー' : 'コードをコピー'),
572    copied: 'コードをコピーしました',
573    copyRefused: 'コピーできませんでした(他の mod が止めた可能性)',
574    toolDone: '完了',
575    toolRunning: '実行中',
576    toolError: 'エラー',
577    toolInterrupted: '中断',
578    toolDetails: '詳細',
579    toolHide: '閉じる',
580  },
581  en: {
582    tab: 'tab',
583    workers: n => `workers ${n}`,
584    attention: n => `attention ${n}`,
585    noWorkers: 'no workers',
586    more: n => `${n} more`,
587    ctxPending: 'before the first reply',
588    resetsIn: d => `resets in ${d}`,
589    state: w => {
590      if (w.attention === 'permission') return 'needs approval'
591      if (w.attention === 'question') return 'has a question'
592      if (w.attention === 'dialog') return 'waiting on a choice'
593      if (w.state === 'limited') return 'rate-limited'
594      if (w.state === 'failed') return 'exited with an error'
595      if (w.state === 'busy') return 'working'
596      if (w.state === 'idle') return 'idle'
597      return 'unknown'
598    },
599    thresholds: (c, l) => `the band shows ctx / limits from ${c}% / ${l}%`,
600    hide: 'Hide band',
601    show: 'Show band',
602    noView: 'No reply from tako (outside a tako pane, or tako has stopped)',
603    hidden: 'band hidden (/tako band on to show it)',
604    shown: 'band shown',
605    usage: 'usage: /tako (sidebar), /tako band on|off (band)',
606    notPlaced: r => `the sidebar cannot be placed: ${r}`,
607    command: "Show this pane's tako status in a sidebar (band on|off shows / hides the band)",
608    card: id => `card ${id}`,
609    copy: 'copy',
610    run: 'run',
611    next: 'next',
612    close: 'close',
613    cardClosed: 'this card was closed',
614    cardHint: (copy, run) => `in the band (ctrl+x → Tab): ${copy}: copy / ${run}: run`,
615    cardKeyHint: (copy, run) => `keys: in the band (ctrl+x → Tab) ${copy}: copy / ${run}: run`,
616    runRefused: reason => (reason === '' ? 'tako: could not run it' : `tako: could not run it (${reason})`),
617    runState: run =>
618      `→ pane ${run.pane} ${run.state === 'running' ? 'running' : run.state === 'exited' ? `exited ${run.exit_code ?? '?'}` : 'closed'}`,
619    guardHeader: 'tako',
620    guardQuestion: found => `This prompt looks like it contains a secret (${found}). Send it anyway?`,
621    guardSend: 'Send',
622    guardCancel: "Don't send",
623    guardDropped: 'tako: not sent because it looks like it contains a secret',
624    guardWarned: found => `tako: sent a prompt that looks like it contains a secret (${found})`,
625    copyCode: (i, of, lang) => `Copy${of > 1 ? ` ${i}` : ''}${lang === '' ? '' : ` ${lang}`}`,
626    latestCode: of => (of > 1 ? 'copy last code' : 'copy code'),
627    copied: 'Copied the code',
628    copyRefused: 'Could not copy (another mod may have stopped it)',
629    toolDone: 'done',
630    toolRunning: 'running',
631    toolError: 'error',
632    toolInterrupted: 'interrupted',
633    toolDetails: 'details',
634    toolHide: 'hide',
635  },
636}
637
638function words(code: string): Words {
639  return code === 'ja' ? WORDS.ja : WORDS.en
640}
641
642// --- 送信時の確認(#2050)-------------------------------------------------------------
643
644type GuardFinding = { rule: string; line: number; masked: string }
645type GuardCheck = { verdict?: string; findings?: GuardFinding[] }
646
647// 当たりの要約(規則名と伏せ字だけ。tako の応答に生の値は無い)
648function guardFound(findings: readonly GuardFinding[]): string {
649  const shown = findings.slice(0, GUARD_SHOW_MAX).map(f => `${f.rule} ${f.masked}`)
650  const rest = findings.length - shown.length
651  return rest > 0 ? `${shown.join(', ')} +${rest}` : shown.join(', ')
652}
653
654// 送る前に tako へ判定させ、答えに従う。'drop' = 送らない。CLI の失敗・時間切れは送信を通す
655async function guardPrompt($: EngineInterface, text: string): Promise<'pass' | 'drop'> {
656  const path = cli
657  const pane = paneId
658  if (path === undefined || pane === undefined || text.trim() === '') return 'pass'
659  let check: GuardCheck
660  try {
661    const done = await $.process.run([path, 'paste-guard', 'check', '--pane', pane], {
662      stdin: text,
663      timeoutMs: GUARD_TIMEOUT_MS,
664    })
665    if (done.exitCode !== 0) {
666      $.ui.log(`tako mod: paste-guard exit ${done.exitCode}`, { to: 'debug' })
667      return 'pass'
668    }
669    check = JSON.parse(done.stdout) as GuardCheck
670  } catch {
671    $.ui.log('tako mod: paste-guard check failed', { to: 'debug' })
672    return 'pass'
673  }
674  const w = words(lang)
675  const found = guardFound(check.findings ?? [])
676  if (check.verdict === 'warn') {
677    $.ui.toast(w.guardWarned(found), { timeoutMs: 8_000 })
678    return 'pass'
679  }
680  if (check.verdict !== 'confirm') return 'pass'
681  // 「やめる」を先頭(既定の選択)に置く: 送信のつもりで押した Enter で送らない(#2046 と同じ考え)
682  let answer: string
683  try {
684    answer = await $.ui.ask(w.guardQuestion(found), { options: [w.guardCancel, w.guardSend], header: w.guardHeader })
685  } catch {
686    // 閉じた(Esc)= やめる
687    answer = w.guardCancel
688  }
689  if (answer === w.guardSend) return 'pass'
690  await restoreDraft($, text)
691  return 'drop'
692}
693
694// やめた送信の文を入力欄へ戻す(鍵を消して送り直せるように。スマホの PWA と同じ)。
695// 戻せなくても送らないことは変えない
696async function restoreDraft($: EngineInterface, text: string): Promise<void> {
697  try {
698    await $.prompt.fill({ text, mode: 'replace' })
699  } catch {
700    $.ui.log('tako mod: paste-guard draft restore failed', { to: 'debug' })
701  }
702}
703
704// 端末の桁数(全角・CJK は 2 桁。Claude Code の配置と同じ数え方の近似)
705function isWide(c: number): boolean {
706  return (
707    (c >= 0x1100 && c <= 0x115f) ||
708    (c >= 0x2e80 && c <= 0xa4cf) ||
709    (c >= 0xac00 && c <= 0xd7a3) ||
710    (c >= 0xf900 && c <= 0xfaff) ||
711    (c >= 0xfe30 && c <= 0xfe4f) ||
712    (c >= 0xff00 && c <= 0xff60) ||
713    (c >= 0xffe0 && c <= 0xffe6) ||
714    (c >= 0x20000 && c <= 0x3fffd)
715  )
716}
717
718function cellWidth(text: string): number {
719  let width = 0
720  for (const ch of text) width += isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
721  return width
722}
723
724// max 桁に収める(溢れたら末尾を … にする)
725function clipCells(text: string, max: number): string {
726  if (cellWidth(text) <= max) return text
727  let out = ''
728  let width = 0
729  for (const ch of text) {
730    const w = isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
731    if (width + w > max - 1) break
732    out += ch
733    width += w
734  }
735  return `${out}…`
736}
737
738function limitName(kind: string): string {
739  if (kind === 'five_hour') return '5h'
740  if (kind === 'seven_day') return '7d'
741  if (kind.startsWith('seven_day_')) return `7d ${kind.slice('seven_day_'.length)}`
742  return kind.replace(/_/g, ' ')
743}
744
745/** 帯の区切り 1 つ。rank が小さいほど最後まで残す(0 / 1 = tako とペイン名は落とさない) */
746type BandSegment = { kind: string; label: string; tone?: 'warning' | 'accent'; rank: number }
747
748/** 押したときにすること(#1962)。tako / shell の argv は tako が組んだもの(view.button_args) */
749type Press = { kind: 'slash'; command: string } | { kind: 'prompt'; text: string } | { kind: 'tako' | 'shell'; argv: string[] }
750
751/** 帯のボタン 1 つ(#1962)。rank は区切りと同じ物差し(左のボタンほど最後まで残す) */
752type BandButton = { button: TakoButton; press: Press; rank: number }
753
754/** 帯のカードのボタンの操作(#1963)。code は「最新のコードをコピー」(#1964。同じ plain の形で並べる) */
755type CardOp = 'copy' | 'run' | 'next' | 'dismiss' | 'code'
756/** 帯のカードのボタン 1 つ(#1963)。`y: コピー` の形(plain = ホットキーを見せる)で描く */
757type CardButton = { op: CardOp; label: string; hotkey: string; rank: number }
758/** 帯で選んでいるカードのコマンド(#1963)。pairs は新しいカードから(カード, コマンド)の並び */
759type CardPair = { card: TakoCard; index: number; command: TakoCardCommand }
760type CardSel = CardPair & { pos: number; pairs: CardPair[] }
761
762// 帯の区切りを左から並べる(何を出すかは tako の view が決めている)。
763// s3 = #1881 の並び(A/B の S3 の描き方と、ui.json が届かない古い tako の応答)。S7 は ui.json の
764// band.segments の並びで、バーの置き場が帯なら bar(tako が描くと決めたバーの文字列)を ctx / limits の
765// 位置(無ければボタンの前)に 1 つ置く(バーを描くなら tako は警告を送ってこない = 同じ値を 2 か所で
766// 動かさない)
767function segmentsOf(view: TakoView, s3: boolean, bar: string | null, card: CardSel | null = null): BandSegment[] {
768  const w = words(view.lang)
769  const name = view.pane_title ?? `pane ${view.pane}`
770  const pane: BandSegment = { kind: 'pane', label: clipCells(name, NAME_MAX), rank: 1 }
771  const hasTab = view.tab_title !== undefined && view.tab_title !== '' && view.tab_title !== name
772  const tab = (rank: number): BandSegment => ({ kind: 'tab', label: `${w.tab} ${clipCells(view.tab_title ?? '', NAME_MAX)}`, rank })
773  const workers = (rank: number): BandSegment => ({ kind: 'workers', label: w.workers(view.worker_count), rank })
774  const attention: BandSegment = { kind: 'attention', label: w.attention(view.attention), tone: 'warning', rank: 2 }
775  // 使用制限は % の大きい順に来る。小さい方から落とす
776  const warning = (warn: TakoView['warnings'][number], i: number, base: number): BandSegment => {
777    const pct = `${Math.round(warn.percent)}%`
778    return warn.kind === 'ctx'
779      ? { kind: 'ctx', label: `ctx ${pct}`, tone: 'warning', rank: base }
780      : { kind: warn.kind, label: `${limitName(warn.kind)} ${pct}`, tone: 'warning', rank: base + 1 + i / 100 }
781  }
782  if (s3) {
783    const out: BandSegment[] = [{ kind: 'tako', label: 'tako', rank: 0 }, pane]
784    if (hasTab) out.push(tab(6))
785    if (view.worker_count > 0) out.push(workers(5))
786    if (view.attention > 0) out.push(attention)
787    view.warnings.forEach((warn, i) => out.push(warning(warn, i, 3)))
788    return out
789  }
790  const out: BandSegment[] = [{ kind: 'tako', label: 'tako', tone: 'accent', rank: 0 }]
791  let barPlaced = bar === null
792  const placeBar = (): void => {
793    if (!barPlaced) out.push({ kind: 'usage', label: bar ?? '', rank: 4 })
794    barPlaced = true
795  }
796  for (const seg of view.ui?.band.segments ?? DEFAULT_SEGMENTS) {
797    if (seg === 'pane') out.push(pane)
798    else if (seg === 'tab' && hasTab) out.push(tab(7))
799    else if (seg === 'workers' && view.worker_count > 0) out.push(workers(6))
800    else if (seg === 'attention' && view.attention > 0) out.push(attention)
801    else if ((seg === 'ctx' || seg === 'limits') && bar !== null) placeBar()
802    else if (seg === 'ctx') view.warnings.filter(warn => warn.kind === 'ctx').forEach((warn, i) => out.push(warning(warn, i, 4)))
803    else if (seg === 'limits') view.warnings.filter(warn => warn.kind !== 'ctx').forEach((warn, i) => out.push(warning(warn, i, 4)))
804    else if (seg === 'buttons') placeBar()
805    else if (seg === 'card' && card !== null) {
806      // #1963: `カード N`(会話の行の見出しと同じ番号 = tako のカード id)と、選んでいるコマンドの頭
807      const of = card.card.commands.length
808      out.push({ kind: 'card', label: of > 1 ? `${w.card(card.card.id)} (${card.index}/${of})` : w.card(card.card.id), tone: 'accent', rank: 2.52 })
809      out.push({ kind: 'card_head', label: clipCells(card.command.text.split('\n')[0] ?? '', CARD_HEAD_MAX), rank: 3.9 })
810    }
811  }
812  placeBar()
813  return out
814}
815
816// 帯のボタン(#1962。ui.json の buttons の並び)。押せないもの(Claude Code に無いコマンド・tako が
817// 引数を組めなかった操作)は描かない。band.segments に buttons が無ければ 1 つも描かない
818function buttonsOf(view: TakoView): BandButton[] {
819  const segments: readonly TakoBandSegment[] = view.ui?.band.segments ?? DEFAULT_SEGMENTS
820  if (!segments.includes('buttons')) return []
821  const out: BandButton[] = []
822  ;(view.ui?.buttons ?? []).forEach((button, i) => {
823    const action = button.action
824    let press: Press | undefined
825    if (action.kind === 'slash') {
826      if (commandNames === undefined || commandNames.has(action.command)) press = { kind: 'slash', command: action.command }
827    } else if (action.kind === 'prompt') {
828      press = { kind: 'prompt', text: action.text }
829    } else {
830      const argv = view.button_args?.[button.id]
831      if (argv !== undefined) press = { kind: action.kind, argv }
832    }
833    if (press !== undefined) out.push({ button, press, rank: 3 + i / 100 })
834  })
835  return out
836}
837
838function lineWidth(segments: readonly BandSegment[]): number {
839  return segments.reduce((sum, seg, i) => sum + cellWidth(seg.label) + (i === 0 ? 0 : SEP.length), 0)
840}
841
842// tako の行の桁: 区切りの Text と、ボタン 1 つごとに間の 1 桁 + `[ ` ラベル ` ]`(カードのボタンは
843// `y: ` ラベル)
844function rowWidth(segments: readonly BandSegment[], buttons: readonly BandButton[], cards: readonly CardButton[] = []): number {
845  return (
846    lineWidth(segments) +
847    buttons.reduce((sum, b) => sum + BUTTON_GAP + BUTTON_CHROME + cellWidth(b.button.label), 0) +
848    cards.reduce((sum, b) => sum + BUTTON_GAP + PLAIN_CHROME + cellWidth(b.label), 0)
849  )
850}
851
852// columns 桁に収まるまで、優先度の低いもの(区切りもボタンも同じ物差し)から落とす(並びは変えない)。
853// tako とペイン名だけでも溢れる幅では、描画側の wrap="truncate-end" が末尾を切る = 必ず 1 行
854function fitBand(
855  segments: BandSegment[],
856  buttons: BandButton[],
857  columns: number,
858  cards: CardButton[] = [],
859): { segments: BandSegment[]; buttons: BandButton[]; cards: CardButton[] } {
860  let keptSegments = segments
861  let keptButtons = buttons
862  let keptCards = cards
863  const order: Array<BandSegment | BandButton | CardButton> = [...segments, ...buttons, ...cards].sort((a, b) => b.rank - a.rank)
864  for (const drop of order) {
865    if (rowWidth(keptSegments, keptButtons, keptCards) <= columns || drop.rank <= 1) break
866    keptSegments = keptSegments.filter(seg => seg !== drop)
867    keptButtons = keptButtons.filter(b => b !== drop)
868    keptCards = keptCards.filter(b => b !== drop)
869  }
870  return { segments: keptSegments, buttons: keptButtons, cards: keptCards }
871}
872
873// --- コマンドカード(#1963)------------------------------------------------------------------
874
875// (カード, コマンド)の並び。新しいカードから、カードの中はコマンドの順
876function cardPairs(items: readonly TakoCard[]): CardPair[] {
877  const out: CardPair[] = []
878  for (const card of [...items].reverse()) {
879    card.commands.forEach((command, i) => out.push({ card, index: i + 1, command }))
880  }
881  return out
882}
883
884// 帯で選んでいるカードのコマンド。tako が描かせない(view.cards が無い)・カードが無い・band.segments に
885// card が無いなら null。選択が消えた(閉じた・押し出された)ら新しいカードの 1 件目
886function cardSelection(view: TakoView, cursor: { card: number; index: number } | null): CardSel | null {
887  const segments: readonly TakoBandSegment[] = view.ui?.band.segments ?? DEFAULT_SEGMENTS
888  if (view.cards === undefined || !segments.includes('card')) return null
889  const pairs = cardPairs(view.cards.items)
890  if (pairs.length === 0) return null
891  const found = cursor === null ? -1 : pairs.findIndex(p => p.card.id === cursor.card && p.index === cursor.index)
892  const pos = Math.max(0, found)
893  const pair = pairs[pos]
894  return pair === undefined ? null : { ...pair, pos, pairs }
895}
896
897// 帯のカードのボタン(Copy / Run を先に残し、閉じる・次はその後)。ホットキーは tako が選んだもの
898function cardButtonsOf(view: TakoView, card: CardSel | null): CardButton[] {
899  const keys = view.cards?.hotkeys
900  if (card === null || keys === undefined) return []
901  const w = words(view.lang)
902  const out: CardButton[] = [
903    { op: 'copy', label: w.copy, hotkey: keys.copy, rank: 2.5 },
904    { op: 'run', label: w.run, hotkey: keys.run, rank: 2.51 },
905  ]
906  if (card.pairs.length > 1) out.push({ op: 'next', label: w.next, hotkey: keys.next, rank: 2.9 })
907  out.push({ op: 'dismiss', label: w.close, hotkey: keys.dismiss, rank: 2.91 })
908  return out
909}
910
911// 帯のカードが押せる形で収まったか: Copy と Run があり、選べるコマンドが複数なら「次」もある
912// (「次」が無いと他のカードへ行けない = そのカードは帯からは押せない)
913function cardPressable(cards: readonly CardButton[], card: CardSel): boolean {
914  const has = (op: CardOp): boolean => cards.some(b => b.op === op)
915  return has('copy') && has('run') && (card.pairs.length === 1 || has('next'))
916}
917
918// 直近の描画を控え、変わったら次の報告で tako へ返す
919function noteBand(shown: boolean, columns: number | undefined, segments: string[], buttons = 0, bar = false, cards: number[] = []): void {
920  const key = JSON.stringify([shown, columns, segments, buttons, bar, cards])
921  if (key === lastBandKey) return
922  lastBandKey = key
923  bandShown = shown
924  bandColumns = columns
925  bandSegments = segments
926  bandButtons = buttons
927  bandBar = bar
928  bandCards = cards
929  dirty = true
930}
931
932// 入力欄の下の行にバーを描いたか(#1962)
933function noteHint(bar: boolean): void {
934  if (bar === hintBar) return
935  hintBar = bar
936  dirty = true
937}
938
939// 使用制限・ctx のバーの文字列(#1962)。描くかは tako が決める(view.usage_bar.draw)。値の無い項目は
940// 飛ばし、1 つも無ければ描かない。形は `<ラベル> <棒> <N>%`(tako は画面を読むときにこの形を除く)
941function barText(view: TakoView): string | null {
942  if (view.band_style === 's3' || view.usage_bar?.draw !== true) return null
943  const parts: string[] = []
944  for (const item of view.ui?.usage_bar.items ?? ['five_hour', 'seven_day', 'ctx']) {
945    const percent = item === 'ctx' ? view.ctx?.percent : view.rate_limits.find(l => l.kind === item)?.percent
946    if (percent === undefined) continue
947    const p = Math.max(0, Math.min(100, Math.round(percent)))
948    parts.push(`${item === 'ctx' ? 'ctx' : limitName(item)} ${BAR_GLYPHS[Math.min(7, Math.floor(p / 12.5))]} ${p}%`)
949  }
950  return parts.length === 0 ? null : parts.join(' ')
951}
952
953// バーの置き場(ui.json が届く前 = 古い tako は既定の prompt_hint)
954function barPlace(view: TakoView): 'prompt_hint' | 'band' | 'off' {
955  return view.ui?.usage_bar.place ?? 'prompt_hint'
956}
957
958// S3(#1881)の描き方(A/B の TAKO_1877_S7_LEGACY): tako の行の Text 1 本だけを返す(next を包まない)
959function drawBandS3($: EngineInterface, e: RenderInput<'AbovePrompt'>, view: TakoView, columns: number): RenderElement {
960  const segments = fitBand(segmentsOf(view, true, null), [], columns).segments
961  noteBand(true, columns, segments.map(seg => seg.kind))
962  const { Text } = $.ui.resolve(e)
963  const parts: Array<ReturnType<typeof Text> | string> = []
964  segments.forEach((seg, i) => {
965    if (i > 0) parts.push(SEP)
966    parts.push(seg.tone === 'warning' ? Text({ color: 'warning', children: seg.label }) : seg.label)
967  })
968  return Text({ dimColor: true, wrap: 'truncate-end', children: parts })
969}
970
971// tako の行(#1962): 区切りの Text とボタンを横に並べて 1 行。幅に合わせて優先度の低いものから落とす。
972// 色は ui.json の colors(Claude Code のテーマのキー)。コマンドカード(#1963)は `カード N` の区切りと
973// `y: コピー` 等のボタン。押せる形で収まらなければカードは描かない(tako が GPUI の帯へ出す)
974function bandRow(
975  $: EngineInterface,
976  e: RenderInput<'AbovePrompt'>,
977  view: TakoView,
978  columns: number,
979  bar: string | null,
980  cursor: { card: number; index: number } | null = null,
981  codes: readonly string[] = [],
982): RenderElement {
983  const s3 = view.ui === undefined
984  // #1964: 最新の返答のコードをキーで写す口(会話の行の Copy はクリックでしか押せない)
985  const code = codeButtonOf(view, codes)
986  const extra = (c: CardSel | null): CardButton[] => (code === null ? cardButtonsOf(view, c) : [...cardButtonsOf(view, c), code])
987  let card = cardSelection(view, cursor)
988  let fitted = fitBand(segmentsOf(view, s3, bar, card), buttonsOf(view), columns, extra(card))
989  if (card !== null && !cardPressable(fitted.cards, card)) {
990    card = null
991    fitted = fitBand(segmentsOf(view, s3, bar, null), buttonsOf(view), columns, extra(null))
992  }
993  const kinds = fitted.segments.map(seg => seg.kind)
994  if (fitted.cards.some(b => b.op === 'code')) kinds.push('code')
995  if (fitted.buttons.length > 0) kinds.push('buttons')
996  // 押せる形で描いたカード(「次」で全部へ行ける)= GPUI の帯から外してよいカード
997  const claimed = card === null ? [] : (view.cards?.items ?? []).map(c => c.id)
998  noteBand(true, columns, kinds, fitted.buttons.length, kinds.includes('usage'), claimed)
999  const colors = view.ui?.colors ?? DEFAULT_COLORS
1000  const { Box, Button, Text } = $.ui.resolve(e)
1001  const parts: Array<ReturnType<typeof Text> | string> = []
1002  fitted.segments.forEach((seg, i) => {
1003    if (i > 0) parts.push(SEP)
1004    if (seg.tone === 'warning') parts.push(Text({ color: colors.warn, children: seg.label }))
1005    else if (seg.tone === 'accent') parts.push(Text({ color: colors.accent, children: seg.label }))
1006    else parts.push(seg.label)
1007  })
1008  const line = Text({ color: colors.dim, wrap: 'truncate-end', children: parts })
1009  const selected = card
1010  const latest = codes.at(-1)
1011  const cardButtons = fitted.cards.flatMap(b => {
1012    if (b.op === 'code') {
1013      return latest === undefined
1014        ? []
1015        : [Button({ key: 'tako-code-latest', label: b.label, hotkey: b.hotkey, plain: true, onPress: press => copyCode($, latest, press) })]
1016    }
1017    return selected === null
1018      ? []
1019      : [Button({ key: `tako-card-${b.op}`, label: b.label, hotkey: b.hotkey, plain: true, onPress: press => pressCard($, b.op, selected, press) })]
1020  })
1021  if (fitted.buttons.length === 0 && cardButtons.length === 0) return line
1022  const buttons = fitted.buttons.map(b =>
1023    Button({ key: `tako-button-${b.button.id}`, label: b.button.label, hotkey: b.button.hotkey, onPress: () => pressButton($, b.press) }),
1024  )
1025  return Box({ flexDirection: 'row', columnGap: BUTTON_GAP, children: [line, ...cardButtons, ...buttons] })
1026}
1027
1028// 他の mod の行(next(e) の答え)を上に、tako の行を下に並べる(#1962 / 設計書 §9.5)。下に誰も
1029// 居なければ答えはエンジン自身の描画({ type: 'engine' }。調査票の無い帯は空)なので tako の行だけ
1030function stackBand($: EngineInterface, e: RenderInput<'AbovePrompt'>, below: RenderElement, row: RenderElement): RenderElement {
1031  if (below.type === 'engine') return row
1032  const { Box } = $.ui.resolve(e)
1033  return Box({ flexDirection: 'column', children: [below, row] })
1034}
1035
1036// ボタンを押したとき(#1962)。語彙どおりに実行し、結果(種類と成否だけ)を次の報告で tako へ返す。
1037// tako / shell は tako が組んだ CLI の引数をそのまま渡す(ここでシェルの文字列は組まない)
1038async function pressButton($: EngineInterface, press: Press): Promise<void> {
1039  let ok = false
1040  try {
1041    if (press.kind === 'slash') {
1042      await $.command.run({ command: press.command })
1043      ok = true
1044    } else if (press.kind === 'prompt') {
1045      ok = (await $.prompt.fill({ text: press.text, mode: 'insert' })).isFilled
1046    } else if (cli !== undefined) {
1047      const done = await $.process.run([cli, ...press.argv], { timeoutMs: PRESS_TIMEOUT_MS })
1048      ok = done.exitCode === 0
1049      if (!ok) $.ui.log(`tako mod: button exit ${done.exitCode}: ${done.stderr.trim().slice(0, 200)}`, { to: 'debug' })
1050    }
1051  } catch (err) {
1052    $.ui.log(`tako mod: button failed: ${String(err).slice(0, 200)}`, { to: 'debug' })
1053  }
1054  lastPress = { kind: press.kind, ok, at: await $.clock.now() }
1055  dirty = true
1056}
1057
1058// カードのボタンを押したとき(帯 = #1963・会話の行 = #2159。どちらもここを通る)。Copy は Claude Code の
1059// $.ui.copy(論理文字列をそのまま)。他の mod の ui.copy フックに拒まれる等で写らなければ tako の CLI
1060// (show-command --copy = GUI がクリップボードへ書く)へ落とす。Run / 閉じるは tako が組んだ引数をそのまま
1061// (実行記録はスマホ・GPUI のカードと同じ dispatch が付ける)。「次」は帯の選択を進めるだけ(tako へは何も送らない)。
1062// Run は同じコマンドの二重押しを捨て(runBusy)、tako に断られたら(実行中の再実行等)理由をトーストで知らせる
1063async function pressCard($: EngineInterface, op: CardOp, sel: CardSel, press: UiPressArgument): Promise<void> {
1064  if (op === 'next') {
1065    const next = sel.pairs[(sel.pos + 1) % sel.pairs.length] ?? sel
1066    await $.state.set(CARD_CURSOR, { card: next.card.id, index: next.index })
1067    return
1068  }
1069  // #2159: 読みと書きの間に await を挟まない = 同時に届いた 2 打目も必ずこの番に当たる
1070  const runKey = `${sel.card.id}:${sel.index}`
1071  if (op === 'run') {
1072    const now = await $.clock.now()
1073    if ((runBusy.get(runKey) ?? 0) > now) return
1074    for (const [key, until] of runBusy) if (until <= now) runBusy.delete(key)
1075    runBusy.set(runKey, Number.POSITIVE_INFINITY)
1076  }
1077  let kind: TakoPress['kind'] = op === 'copy' ? 'card_copy' : op === 'run' ? 'card_run' : 'card_dismiss'
1078  let ok = false
1079  let reason = ''
1080  try {
1081    if (op === 'copy') {
1082      const copied = await $.ui.copy({ text: sel.command.text, surface: press.surface })
1083      ok = copied.isCopied
1084      if (!copied.isCopied && cli !== undefined) {
1085        kind = 'card_copy_cli'
1086        const done = await $.process.run([cli, ...sel.command.copy_args], { timeoutMs: PRESS_TIMEOUT_MS })
1087        ok = done.exitCode === 0
1088      }
1089    } else if (cli !== undefined) {
1090      const argv = op === 'run' ? sel.command.run_args : sel.card.dismiss_args
1091      const done = await $.process.run([cli, ...argv], { timeoutMs: PRESS_TIMEOUT_MS })
1092      ok = done.exitCode === 0
1093      if (!ok) reason = refusedReason(done.stderr)
1094    }
1095    if (!ok) $.ui.log(`tako mod: card ${op} failed`, { to: 'debug' })
1096  } catch (err) {
1097    $.ui.log(`tako mod: card ${op} failed: ${String(err).slice(0, 200)}`, { to: 'debug' })
1098  }
1099  lastPress = { kind, ok, at: await $.clock.now() }
1100  if (op === 'run') {
1101    // 走らせたら少しの間だけ捨てる(ダブルクリックの 2 打目)・断られた / 失敗したらすぐ押し直せる
1102    if (ok) runBusy.set(runKey, lastPress.at + RUN_REPEAT_MS)
1103    else runBusy.delete(runKey)
1104    if (!ok) {
1105      try {
1106        $.ui.toast(words(lang).runRefused(reason), { timeoutMs: 5_000 })
1107      } catch {
1108        // トーストが出せなくても断られた結果は変わらない(last_press に残る)
1109      }
1110    }
1111  }
1112  // 実行記録・閉じたことは次の応答(view.cards)で届く
1113  dirty = true
1114}
1115
1116// tako の CLI が断った理由(`error: <理由>` の最後の行。tako の dispatch の文言 = 実行中なら「このコマンドは
1117// まだ実行中…」)。トーストに収まるよう切る
1118function refusedReason(stderr: string): string {
1119  const line = stderr.split('\n').map(l => l.trim()).filter(l => l !== '').at(-1) ?? ''
1120  return clipCells(line.replace(/^error:\s*/, ''), RUN_REASON_MAX)
1121}
1122
1123// tako_show_command の show(action を省いた呼び出しを含む)か
1124function isShowCall(tool: string, input: unknown): boolean {
1125  if (!SHOW_TOOL.test(tool)) return false
1126  const action = typeof input === 'object' && input !== null ? (input as { action?: unknown }).action : undefined
1127  return action === undefined || action === 'show'
1128}
1129
1130// 呼び出しの結果からカードの id を拾う(MCP の content の text に tako の応答の JSON =
1131// `{"card":{"id":N,…}}`)。形は Claude Code の版で揺れうるので、文字列・配列・{ text } / { content } を辿る
1132function cardIdOf(output: unknown, depth = 0): number | undefined {
1133  if (depth > 4 || output === null || output === undefined) return undefined
1134  if (typeof output === 'string') {
1135    try {
1136      return cardIdOf(JSON.parse(output) as unknown, depth + 1)
1137    } catch {
1138      return undefined
1139    }
1140  }
1141  if (Array.isArray(output)) {
1142    for (const item of output) {
1143      const id = cardIdOf(item, depth + 1)
1144      if (id !== undefined) return id
1145    }
1146    return undefined
1147  }
1148  if (typeof output !== 'object') return undefined
1149  const o = output as { card?: unknown; text?: unknown; content?: unknown }
1150  if (typeof o.card === 'object' && o.card !== null) {
1151    const id = (o.card as { id?: unknown }).id
1152    if (typeof id === 'number') return id
1153  }
1154  return cardIdOf(o.text, depth + 1) ?? cardIdOf(o.content, depth + 1)
1155}
1156
1157// 呼び出しの引数(モデルが送った形)のコマンドとラベル。カードがもう store に無い(閉じた)ときの表示用
1158function callCommands(input: unknown): { commands: string[]; label?: string } {
1159  const o = typeof input === 'object' && input !== null ? (input as { commands?: unknown; label?: unknown }) : {}
1160  const commands = Array.isArray(o.commands) ? o.commands.filter((c): c is string => typeof c === 'string') : []
1161  return { commands, label: typeof o.label === 'string' && o.label !== '' ? o.label : undefined }
1162}
1163
1164// 会話の行のカード(#1963): 見出し(tako・カード N・ラベル)・コマンドを Code で(見た目だけ折り返す。
1165// 写すのはボタン = 論理文字列)・実行記録・押す案内。クリックが届く(#2159: tako がクリックを渡す = view.cards.click
1166// ∧ 全画面の端末)ならコマンドごとに `[ 実行 ]` / `[ コピー ]`(クリック 1 回。帯と同じ pressCard)を置き、
1167// 届かなければ帯で押す案内だけ(押せないボタンを見せない)。カードが store に無い(閉じた・押し出された)
1168// なら引数から描いて「閉じた」と添える。下の他の mod が描いていればその下に足す(next の答えを包む)
1169function drawCardRow($: EngineInterface, e: RenderInput<'ToolUse'>, view: TakoView, below: RenderElement): RenderElement {
1170  const w = words(view.lang)
1171  const colors = view.ui?.colors ?? DEFAULT_COLORS
1172  const id = cardIdOf(e.props.output)
1173  const card = id === undefined ? undefined : view.cards?.items.find(c => c.id === id)
1174  const call = callCommands(e.props.input)
1175  const commands: Array<{ text: string; run?: TakoCardCommand['run'] }> =
1176    card === undefined ? call.commands.map(text => ({ text })) : card.commands
1177  const label = card === undefined ? call.label : card.label
1178  const clickable = card !== undefined && view.cards?.click === true && e.surface === 'terminal' && e.viewport?.isFullscreen === true
1179  const { Box, Button, Code, Text } = $.ui.resolve(e)
1180  const title: Array<ReturnType<typeof Text> | string> = [Text({ color: colors.accent, bold: true, children: 'tako' })]
1181  if (id !== undefined) title.push('  ', Text({ bold: true, children: w.card(id) }))
1182  if (label !== undefined) title.push(`  ${label}`)
1183  if (id !== undefined && card === undefined && !e.props.isRunning) title.push(Text({ color: colors.dim, children: `  ${w.cardClosed}` }))
1184  const rows: RenderElement[] = [Text({ wrap: 'wrap', children: title })]
1185  commands.forEach((command, i) => {
1186    const code = Code({ source: command.text, language: 'bash', wrap: 'wrap' })
1187    rows.push(
1188      commands.length > 1
1189        ? Box({ flexDirection: 'row', children: [Text({ color: colors.dim, children: `${i + 1} ` }), Box({ flexGrow: 1, flexShrink: 1, children: [code] })] })
1190        : code,
1191    )
1192    const state =
1193      command.run === undefined
1194        ? null
1195        : Text({
1196            color: command.run.state === 'running' ? colors.accent : command.run.exit_code === 0 ? 'success' : command.run.state === 'exited' ? 'error' : colors.dim,
1197            children: w.runState(command.run),
1198          })
1199    const pair = card === undefined ? undefined : card.commands[i]
1200    if (clickable && card !== undefined && pair !== undefined) {
types/index.d.ts 330 lines
1// tako mod が tako へ送る報告の契約(#1879。設計書 .agent/plans/2026-10-tako-mod.md §4.2)と、
2// tako が応答で返す帯・サイドバーの材料(#1881。§7 S3)・定型の UI 設定(#1960。§9.7)・描いたもの(#1962)・
3// コマンドカード(#1963。§9.3)・チャット風の描画(#1964。§9.3)、mod の $.state の契約。
4// 受け手 / 送り手の正本は tako_core::claude_mod::{ModReport, ModBand, ModRenders, BandView} と tako_core::claude_mod_ui::UiConfig。
5// キーを増やすときは両方を同じコミットで直す。
6//
7// **会話の本文・プロンプト・ツールの引数は載せない**(AGENTS.md の絶対ルール)。
8// pending_tool はツール名だけ。番犬 crates/tako-control/tests/issue1879_claude_mod_watchdog.rs が
9// 本文系のキーが紛れ込んでいないかを走査する。
10
11/** ターンの状態。permission = 権限ダイアログ表示中、question = AskUserQuestion 表示中 */
12export type TakoTurn = 'idle' | 'busy' | 'permission' | 'question'
13
14export type TakoContext = {
15  /** 最初の API 応答までは欠ける(0 埋めしない = 未観測) */
16  tokens?: number
17  window: number
18  percent?: number
19}
20
21export type TakoRateLimit = {
22  /** five_hour / seven_day / ゲートウェイの spend_limit など */
23  kind: string
24  percent_used: number
25  resets_at?: string
26  /**
27   * この値を観測した時刻(epoch ms)。% か resets_at が変わったときだけ打ち直す(heartbeat では
28   * 前の時刻のまま = #1903)。tako はアカウント単位の値を束ねるときに新しい方を採る
29   */
30  observed_at: number
31}
32
33/** $.state の limitsSeen(窓の種類 → 最後に値が変わった観測)。ホットリロードをまたいで残す */
34export type TakoLimitsSeen = Record<string, { percent_used: number; resets_at?: string; observed_at: number }>
35
36export type TakoModReport = {
37  schema: 1
38  mod_version: string
39  claude_version?: string
40  session_id?: string
41  /** 報告を組んだ時刻(epoch ms) */
42  at: number
43  model?: string
44  effort?: string
45  context?: TakoContext
46  rate_limits: TakoRateLimit[]
47  cost_usd?: number
48  turn: TakoTurn
49  pending_tool?: string
50  last_turn?: { duration_ms: number; reason: string }
51  /**
52   * classic 系のイベント(PermissionRequest 等)がこのセッションの mod へ届いているか。
53   * false のとき permission は ask ルール由来と ExitPlanMode だけ(ルールの無い ask は拾わない)
54   */
55  classic_events: boolean
56  /** CLAUDE_CONFIG_DIR(使用制限はアカウント単位なので束ねる鍵にする。ログには出さない) */
57  config_dir?: string
58  /** 帯の状態(#1881。描いた文字列は載せない = 区切りの種類だけ) */
59  band?: TakoBand
60  /**
61   * 休眠に入った理由(#1959)。user_disabled = 利用者が Claude Code の /plugin で tako@skills-dir を
62   * 止めた(env の注入で読まれていても従う)。これを最後に mod は報告を止める
63   */
64  dormant?: 'user_disabled'
65  /**
66   * 利用者の Claude Code に statusLine が設定されているか(#1962。$.settings.read() の statusLine の
67   * 有無だけで中身は載せない。読めなければ欠ける)。tako は画面の読み取りと合わせてバーを描くか決める
68   */
69  status_line?: boolean
70  /** 描いているもの(#1962。無い = 何も描いていない = S7-3 前の mod・A/B の S3 の描き方) */
71  renders?: TakoRenders
72  /** 最後に押されたボタン(#1962。種類と成否だけ) */
73  last_press?: TakoPress
74  /**
75   * 会話の行が足された回数(#1964。起きてからの session.append のうち本筋 = サブエージェントでない
76   * user / assistant の行。**数だけ**で本文・uuid は載せない)。GPUI のチャットはこれが変わったときだけ
77   * transcript を読み直す(renders.chat.notify が真のとき)
78   */
79  chat_seq?: number
80  /** session.end を受けた最後の報告。tako はそのペインの報告を即座に捨てる */
81  ended: boolean
82}
83
84/** 描いているもの(tako_core::claude_mod::ModRenders)。tako はこれを見て自分の表示を引っ込める */
85export type TakoRenders = {
86  /** 直近の帯の描画で tako の行を描いたか */
87  band: boolean
88  /** 使用制限・ctx のバーを描いた置き場(描いていなければ欠ける) */
89  usage_bar?: 'prompt_hint' | 'band'
90  /** 直近の帯の描画で描いたボタンの数 */
91  buttons: number
92  /** 起きてから帯(AbovePrompt)のフックが呼ばれたか(偽で hint_hook が真 = 外側の他の mod に帯を隠された) */
93  band_hook: boolean
94  /** 起きてから入力欄の下の行(PromptHint)のフックが呼ばれたか */
95  hint_hook: boolean
96  /**
97   * 直近の帯の描画で押せる形(Copy / Run のボタンつき)で描いたコマンドカードの id(#1963)。
98   * 応答に view.cards が無い(tako が描かせない)ときは欠ける。tako は載った id を GPUI のカード帯から外す
99   */
100  cards?: number[]
101  /**
102   * チャット風の描画で今あてている組(#1964。応答の view.chat をそのまま)。応答に view.chat が無い
103   * (A/B・古い tako)ときは欠ける。GUI モードで tako はこれがあるペインのチャットを mod に任せうる
104   */
105  chat?: TakoChatRenders
106}
107
108/** チャット風の描画で今あてている組(tako_core::claude_mod::ModChatRenders) */
109export type TakoChatRenders = {
110  bubble: boolean
111  code_copy: boolean
112  tool_summary: boolean
113  /** 会話の行が足されるたびにすぐ報告している(view.chat.notify を受けた) */
114  notify: boolean
115}
116
117/**
118 * ボタンを押した結果(tako_core::claude_mod::ModPress)。ラベル・コマンド・入力欄へ入れる文は載せない。
119 * card_* はコマンドカードの帯のボタン(#1963。card_copy_cli = $.ui.copy が拒まれて tako の CLI で写した)。
120 * code_copy はチャット風の描画のコードのコピー(#1964。会話の行のボタンと帯の「最新のコードをコピー」)
121 */
122export type TakoPress = {
123  kind: 'slash' | 'tako' | 'shell' | 'prompt' | 'card_copy' | 'card_copy_cli' | 'card_run' | 'card_dismiss' | 'code_copy'
124  ok: boolean
125  /** 押した時刻(epoch ms) */
126  at: number
127}
128
129/** 帯(プロンプトの上の 1 行)の状態(tako_core::claude_mod::ModBand) */
130export type TakoBand = {
131  /** 利用者が帯を隠している($.store の band) */
132  hidden: boolean
133  /** 直近の描画で帯を描いたか */
134  shown: boolean
135  /** 直近の描画の帯の本文の桁(AbovePrompt の bodyColumns) */
136  columns?: number
137  /** 描いた区切りの種類(左から。tako / pane / tab / workers / attention / ctx / five_hour …) */
138  segments: string[]
139  /** トグルを最後に変えた時刻(epoch ms) */
140  toggled_at?: number
141}
142
143/** worker の状態(tako_core::claude_mod::WorkerState) */
144export type TakoWorkerState = 'busy' | 'idle' | 'waiting' | 'limited' | 'failed' | 'unknown'
145/** 要注意の理由(tako_core::claude_mod::Attention) */
146export type TakoAttention = 'permission' | 'question' | 'dialog' | 'limited' | 'failed'
147
148export type TakoWorker = {
149  pane: number
150  name: string
151  state: TakoWorkerState
152  attention?: TakoAttention
153}
154
155/** tako が `tako mod report` の応答(tako.view)で返す帯・サイドバーの材料(tako_core::claude_mod::BandView) */
156export type TakoView = {
157  pane: number
158  pane_title?: string
159  tab_title?: string
160  /** tako の表示言語(ja / en) */
161  lang: string
162  worker_count: number
163  attention: number
164  /** 要注意を先に、上限まで */
165  workers: TakoWorker[]
166  /** 帯に出す警告(tako が閾値を超えたと判断したものだけ) */
167  warnings: { kind: string; percent: number; resets_at?: number }[]
168  /** サイドバー用(閾値に関わらず) */
169  ctx?: TakoContext
170  rate_limits: { kind: string; percent: number; resets_at?: number }[]
171  thresholds: { ctx_percent: number; limit_percent: number }
172  /**
173   * 帯のトグルの中継(at は epoch ms。$.store の時刻より新しいときだけ従う)。正本は ui.json の
174   * band.hidden / toggled_at(#1960)で、`tako mod band on|off`・`tako mod ui set band.hidden`・
175   * この mod の報告の取り込みのどれで変わっても同じ形で届く
176   */
177  band_request?: { hidden: boolean; at: number }
178  /** 定型の UI 設定(#1960。tako が検証した値だけが届く。古い tako の応答には無い) */
179  ui?: TakoUi
180  /**
181   * 使用制限・ctx のバーを描くか(#1962。tako が決める: 置き場が off・利用者の statusLine が既に数値を
182   * 出している = 描かない)。A/B と古い tako の応答には無い
183   */
184  usage_bar?: { draw: boolean; reason?: 'off' | 'status_line' }
185  /** tako / shell のボタンを押したときに叩く CLI の引数(ボタンの id → tako の後ろの argv。tako が組む) */
186  button_args?: Record<string, string[]>
187  /** 帯の描き方。's3' = #1962 前(next を包まない・ボタンとバーなし。A/B の TAKO_1877_S7_LEGACY) */
188  band_style?: 's3'
189  /**
190   * このペインのコマンドカード(#1963。tako が描かせると決めたときだけ届く = ui.json の cards.place が
191   * tako・A/B の TAKO_1963_LEGACY / TAKO_1877_S7_LEGACY・古い tako の応答には無い)
192   */
193  cards?: TakoCards
194  /**
195   * チャット風の描画(#1964。A/B の TAKO_1964_LEGACY / TAKO_1877_S7_LEGACY・古い tako の応答には無い =
196   * 何も描かない)。何を描くかは tako が ui.json の chat × 表示モードで決める
197   */
198  chat?: TakoChat
199}
200
201/** チャット風の描画(tako_core::claude_mod::ChatView) */
202export type TakoChat = {
203  /**
204   * どの組か: gui = GUI モードで mod がチャットを持つ / terminal = ターミナル表示・GPUI のチャットの裏
205   * (ui.json の always だけ)/ off = chat.place が tako(何も描かない)
206   */
207  mode: 'gui' | 'terminal' | 'off'
208  /** 利用者の発話(composer / bridge)を右寄せの吹き出しに描く */
209  bubble: boolean
210  /** AI の返答のコードブロックの下にコピーのボタン、帯に「最新のコードをコピー」 */
211  code_copy: boolean
212  /** ツールの呼び出しを 1 行の要約に描く(ToolGroup は展開して 1 呼び出し 1 行) */
213  tool_summary: boolean
214  /** 帯の「最新のコードをコピー」のホットキー(tako がボタン・カードと重ならない英小文字を選ぶ) */
215  hotkey: string
216  /** 会話の行が足されたらすぐ報告する(GUI モードで GPUI のチャットが表に出ているペイン) */
217  notify: boolean
218}
219
220/** コマンドカード(tako_core::claude_mod::CardsView)。正本は tako の store(`tako show-command --list`) */
221export type TakoCards = {
222  /** 帯のカードのボタンのホットキー(tako が ui.json のボタンと重ならない英小文字を選ぶ。数字は使わない) */
223  hotkeys: { copy: string; run: string; next: string; dismiss: string }
224  /**
225   * 会話の行のカードにクリックで押す「実行 / コピー」を置いてよいか(#2159。tako がこのペインの TUI へ
226   * 左クリックを渡す = `tako mouse` が on ∧ A/B でない)。置くのはさらに全画面(viewport.isFullscreen)の
227   * 端末のときだけ。偽なら帯で押す案内だけ(#1963 の形)。帯のボタンはどちらでも描く(キーの口)
228   */
229  click: boolean
230  /** 古い順(store の並び)。帯は新しいものから選ぶ */
231  items: TakoCard[]
232}
233
234/** カード 1 枚(tako_core::claude_mod::CardView) */
235export type TakoCard = {
236  /** tako のカード id(`tako show-command --card N`。帯と会話の行の「カード N」) */
237  id: number
238  label?: string
239  commands: TakoCardCommand[]
240  /** 閉じるで叩く CLI の引数(tako の後ろの argv。tako が組む) */
241  dismiss_args: string[]
242}
243
244/** カードのコマンド 1 件(tako_core::claude_mod::CardCommandView) */
245export type TakoCardCommand = {
246  /** 論理文字列(AI が渡したまま。画面の折り返しは混ざらない = Copy に渡すのはこれ) */
247  text: string
248  /** $.ui.copy が拒まれたときに叩く CLI の引数(tako の show-command --copy) */
249  copy_args: string[]
250  /** Run で叩く CLI の引数(tako の show-command --run = 新しいペインで実行・スマホと同じ実行記録) */
251  run_args: string[]
252  /** 最後の実行の記録(#1724。未実行は欠ける) */
253  run?: { pane: number; state: 'running' | 'exited' | 'closed'; exit_code?: number; count: number }
254}
255
256/** 帯に並べる区切り(tako_core::claude_mod_ui::BandSegment) */
257export type TakoBandSegment = 'pane' | 'tab' | 'workers' | 'attention' | 'ctx' | 'limits' | 'buttons' | 'card'
258/** カード・チャットを誰が描くか */
259export type TakoPlace = 'auto' | 'mod' | 'tako'
260/** チャット風の描き方をいつ出すか */
261export type TakoChatShow = 'always' | 'gui_only' | 'off'
262/** 色は Claude Code のテーマのキーだけ(ThemeKey の部分集合) */
263export type TakoThemeColor =
264  | 'text'
265  | 'inactive'
266  | 'subtle'
267  | 'suggestion'
268  | 'remember'
269  | 'success'
270  | 'error'
271  | 'warning'
272  | 'merged'
273  | 'claude'
274  | 'permission'
275  | 'planMode'
276  | 'autoAccept'
277  | 'ide'
278/** ボタンの動作(4 種の定型だけ。任意の JS は持たない) */
279export type TakoButtonAction =
280  | { kind: 'slash'; command: 'compact' | 'clear' | 'context' | 'cost' | 'model' | 'effort' | 'tako' }
281  | {
282      kind: 'tako'
283      op:
284        | 'split-right'
285        | 'split-down'
286        | 'session-restart-harness'
287        | 'session-restart-handoff'
288        | 'limit-resume-on'
289        | 'limit-resume-off'
290        | 'background'
291        | 'close'
292        | 'open-cwd'
293    }
294  | { kind: 'shell'; command: string }
295  | { kind: 'prompt'; text: string }
296/** カスタムボタン(8 個まで・label 16 桁・hotkey は数字か英小文字 1 字で重複なし) */
297export type TakoButton = { id: string; label: string; hotkey: string; action: TakoButtonAction }
298
299/** 定型の UI 設定(tako_core::claude_mod_ui::UiConfig = `<data_dir>/claude-mod/ui.json`) */
300export type TakoUi = {
301  schema_version: 1
302  band: { hidden: boolean; segments: TakoBandSegment[]; toggled_at?: number }
303  usage_bar: { place: 'prompt_hint' | 'band' | 'off'; items: ('five_hour' | 'seven_day' | 'ctx')[] }
304  buttons: TakoButton[]
305  cards: { place: TakoPlace }
306  chat: { place: TakoPlace; bubble: TakoChatShow; code_copy: boolean; tool_summary: TakoChatShow }
307  colors: { accent: TakoThemeColor; warn: TakoThemeColor; dim: TakoThemeColor }
308}
309
310declare module 'claude-code' {
311  interface PluginState {
312    tako: {
313      /** 最後に受け取った tako の材料(無い・古い = null で帯を描かない) */
314      view: TakoView | null
315      /** 帯を隠すトグル($.store の band の写し。描画が購読する) */
316      bandHidden: boolean
317      /** 使用制限の窓ごとの観測時刻(#1903。描画は読まない) */
318      limitsSeen: TakoLimitsSeen
319      /** 帯で選んでいるカードのコマンド(#1963。null = いちばん新しいカードの 1 件目) */
320      cardCursor: { card: number; index: number } | null
321      /**
322       * 最新の AI の返答のコードブロック(#1964。帯の「最新のコードをコピー」が写す。**報告には載せない**)
323       */
324      chatCodes: string[]
325      /** ツールの要約から「詳細」で開いた呼び出しの tool_use_id(#1964。開いた行はエンジンの描画に戻す) */
326      toolOpen: string[]
327    }
328  }
329}
330