【ClaudeCode】MaxプランのAPIクレジットをAgent SDKで使う|対話型のように動く自作チャット画面

スポンサーリンク
Claude
スポンサーリンク

Claude の Max プランに、毎月100ドル分の API クレジットが付くようになった。ところが、このクレジットは普段使っている対話型の Claude Code(ターミナル・VS Code の拡張機能・デスクトップアプリ)では使えない。使えるのは API や Agent SDK などに限られている。

そこで、対象に入っている Claude Agent SDK を使って、ブラウザで動く自分用のチャット画面を用意した。フォルダを開いて指示を出すと、Claude がファイルを読み、コマンドを実行し、必要なときは許可を求めてくる。料金は API クレジットから引かれる。さらに、サブスク側(デスクトップアプリやターミナルの Claude Code)で進めていた会話をこの画面で引き継ぎ、サブスクの利用枠が戻ったら元の側で続きをする、という行き来もできるようにした。

最初の版は ChatGPT に作らせた。そのあと Claude Code に見直しを頼み、表示の不具合の修正と、会話の引き継ぎなどの機能を足させた。この記事では、改修後の仕組みをまとめる。コードの全文は記事の最後に載せた。

Agent SDK で作った自分用のチャット画面
作ったチャット画面。左で作業フォルダと過去の会話を選び、下でモデルと権限を選んで指示を出す(画面は見本用のフォルダで撮ったもの)

API クレジットが使えるもの・使えないもの

公式ヘルプによると、Max プランの API クレジットは月100ドルで、対象は次のとおり。

使えるもの 使えないもの
Claude API(Messages API、Message Batches API) 対話型の Claude Code(ターミナル、IDE、デスクトップ、Web)
Console の Playground Claude・Claude Code・Claude Cowork の追加利用分(extra usage)
Claude Managed Agents Amazon Bedrock、Google Cloud Vertex AI、Microsoft Foundry 経由の Claude
Claude Agent SDK 連携した請求で支払う、他社製アプリの利用分

Claude Console の請求画面では「プロモーションクレジット」として表示され、適用対象の欄にも Agent SDK、API、Batch API、Playground、Managed Agents と書かれている。

Claude Console の請求画面に表示されたプロモーションクレジット
Console の請求画面。適用対象に Agent SDK が入っている

Agent SDK と claude -p(対話画面を出さずに1回だけ実行するモード)には条件がある。公式ヘルプによると、クレジットから引かれるのは、Console の組織で発行した API キーを使って自分で動かしたときだけである。Claude のプランでサインインした状態で動かすと、プランの利用枠のほうが減り、クレジットは使われない。また、IDE の拡張機能やデスクトップアプリから始まった実行は、-p を付けていても Claude Code の利用として扱われ、対象外になる。

つまり、クレジットを使うには「API キーで」「Agent SDK を自分で動かす」形にすればよい。

全体の仕組み

Agent SDK は、Claude Code が使っているのと同じツール(ファイルの読み書き、コマンドの実行、検索など)とエージェントの仕組みを、自分のプログラムから呼び出せるライブラリである。画面は付いていないので、指示を入力して結果を表示する部分を用意した。

ブラウザ(チャット画面)
   ↕  http://127.0.0.1:(空きポート)   1行に1つのJSONで逐次受け取る
Node.js のサーバー(agent_web.mjs)
   ↕  query() を呼び出す
Claude Agent SDK(ファイル操作やコマンド実行はここが行う)
   ↕  API キーで認証
Claude API(Console の組織の API クレジットから引かれる)

ファイルは次の構成にした。

api_credit\
├─ web_chat.bat      ← ダブルクリックで起動する
├─ agent_web.mjs     ← サーバー本体(Agent SDK を呼ぶ)
├─ package.json
├─ .runtime\         ← API キーと画面の状態を置く(Git で管理しない)
└─ web\
   ├─ index.html     ← チャット画面
   ├─ app.js
   └─ style.css

準備

API クレジットを受け取る

クレジットは自動では付かず、受け取りの操作が必要である。公式ヘルプの手順は次のとおり。

  1. ブラウザで claude.ai を開き、Settings → Billing を開く
  2. 「API credits」の欄で「Link organization」を選ぶ
  3. Claude Console の組織を選ぶか、新しく作る
  4. 規約(Supplemental Credit Terms)を確認して、組織を連携する

対象のプランになってから7日たっていることが条件になっている。Claude Console 側に支払い方法を登録する必要はない。

API キーを作って、ファイルに保存する

連携した組織の Claude Console で API キーを作る。キーはプログラムの中には書かず、ツールのフォルダの中の .runtime フォルダに、次の名前のテキストファイルとして保存する。中身はキーの1行だけである。

.runtime\anthropic_api_key.txt

.runtime は Git の管理から外しておく。.gitignore には次の3行を入れてある。

node_modules/
.runtime/
*.log

別の場所に置きたいときは、環境変数 CHAT_WEB_KEY_FILE にファイルのパスを入れると、そちらが優先される。

Agent SDK を入れて起動する

Node.js が必要である(私の環境は v26.13.1)。記事の最後に載せた6つのファイルを上の構成で置き、そのフォルダで次のコマンドを実行すると、Agent SDK(私の環境では 0.3.329)と、返答の Markdown を整形して表示するための markdown-it が入る。

npm install

起動は次のコマンドで、空いているポートでサーバーが立ち上がり、ブラウザが自動で開く。普段は、Node.js の有無の確認と npm install まで行うバッチファイル(web_chat.bat)をダブルクリックして起動している。

node agent_web.mjs

最初に開く作業フォルダは、ツールのフォルダの2つ上のフォルダである(作業フォルダの中の tools\api_credit にツールを置く前提にしている)。作業フォルダは、画面の左上からいつでも切り替えられる。

中心になるコード: query() に渡す設定

Agent SDK の入口は query() という関数1つである。指示の文章と設定を渡すと、Claude の返答やツールの実行状況が、メッセージとして順番に返ってくる。設定の部分は次のとおり。

  const { query } = await sdk();
  const abortController = new AbortController();
  currentAbort = abortController;
  const opts = {
    cwd: workingDirectory,
    model: selectedModel,
    permissionMode: selectedMode,
    canUseTool: (toolName, input, options) => takeApproval(toolName, input, options),
    includePartialMessages: true,
    abortController,
    settingSources: ['user', 'project', 'local'],
    hooks: { PreToolUse: [{ hooks: [async (input) => guardKey(input)] }] },
    env: { ...process.env, ANTHROPIC_API_KEY: apiKey, ENABLE_CLAUDEAI_MCP_SERVERS: 'false' },
  };
  if (sessionId) opts.resume = sessionId;
設定 意味
cwd 作業フォルダ。画面で選んだフォルダを渡す
model 使うモデルの ID。画面のプルダウンで選んだもの
permissionMode 権限モード。画面では auto(モデルによる判定で、操作を1件ずつ自動で許可または拒否する)と default(手動承認)の2つから選ぶ
canUseTool Claude が許可を求めてきたとき、質問をしてきたときに呼ばれる関数
includePartialMessages true にすると、返答が書かれていく途中の断片も受け取れる
abortController 停止ボタンで処理を中断するために渡す
settingSources 読み込む設定の範囲。user・project・local を指定して、CLAUDE.md や settings.json を読み込ませる
hooks ツールが実行される前に呼ばれる関数。API キーのファイルを読ませないために使う(後述)
env SDK に渡す環境変数。ここで API キーを渡す
resume 続きから再開する会話の ID
prompt(設定の外) 指示の文章。文字列ではなく、発言が1つずつ出てくる流れを渡している(後述)

クレジットを使ううえで大事なのは env の ANTHROPIC_API_KEY である。ファイルから読んだ API キーを、SDK を動かすときだけ渡している。PC 全体の環境変数には設定していないので、普段の Claude Code(Max プランでサインインしている)には影響しない。

ENABLE_CLAUDEAI_MCP_SERVERS を false にしているのは、API キーで動かしたときに次の警告が出ていたためである。API キーで動かしている間は claude.ai 側のコネクタは使えないので、読み込み自体をやめている。

claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth source is set and takes precedence over your claude.ai login · Unset it to load your organization's connectors

対話型のように動かすための工夫

会話を続ける(session_id と resume)

query() は、ひとまとまりの作業ごとに呼び出す。そのままでは毎回新しい会話になってしまうので、返ってくるメッセージに入っている session_id を保存しておき、次の指示のときに resume に渡す。これで前のやり取りを覚えたまま続けられる。ID・モデル・権限モード・画面に表示する履歴は、作業フォルダごとにファイルへ保存している。

やり取りを起きた順に下へ積む

最初の版では、返答の文章を1つの枠にまとめ、使ったツールの一覧をその下に並べていた。ツールを何十回も使う長い作業になると、最後の返答が一覧より上の枠に書き足されるので、画面の一番下を見ていても終わったことが分かりづらかった。

改修後は、文章・ツールの実行・注意書きを、届いた順に1つずつ下へ足していく。ツールの実行が挟まったら文章の枠をそこで区切り、次の文章は新しい枠としてその下に置く。最後の返答は必ず一番下に来て、その下に「完了」の行(その回の費用と終了時刻)が付く。別のタブを見ている間に終わったときは、タブの題名に「✓ 完了」と出し、許可してあれば通知も出す。

文章とツールの実行が時系列で並んだチャット画面
文章とツールの実行が、起きた順に並ぶ(画面確認用のテストモードで撮ったもので、返答はダミー)
最後の返答の下に完了の行が表示されたチャット画面
最後の返答が一番下に来て、その下に完了の行が出る(テストモード。金額はダミー)

タブを閉じても作業を続ける

最初の版は、ブラウザとの接続が切れると作業を中断する作りだった。うっかりページを読み込み直すと、長い作業がそこで止まってしまう。

改修後は、作業をブラウザとの接続から切り離した。サーバーは、作業中に起きたこと(文章の断片、ツールの実行、承認の依頼など)を1件ずつメモリに記録していく。ブラウザは「何件目から後を送って」と頼んで受け取る。ページを読み込み直したときは1件目から受け取り直して画面を作り直し、接続が切れたときは受け取った件数の続きから再開する。

function emit(event) {
  if (!run || run.done) return;
  run.events.push(event);
  const line = JSON.stringify(event) + '\n';
  for (const res of run.listeners) {
    if (!res.destroyed && !res.writableEnded) res.write(line);
  }
}

function handleEvents(req, res, url) {
  const id = url.searchParams.get('run');
  if (!run || run.id !== id) return json(res, 404, { error: 'この実行はもう残っていません。' });
  const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0);
  res.writeHead(200, { 'Content-Type': 'application/x-ndjson; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'X-Accel-Buffering': 'no' });
  res.flushHeaders();
  for (const event of run.events.slice(after)) res.write(JSON.stringify(event) + '\n');
  if (run.done) return res.end();
  const current = run;
  current.listeners.add(res);
  // Closing the tab only stops listening. The run itself continues.
  res.on('close', () => current.listeners.delete(res));
}

止めたいときは停止ボタンを押す。サーバー(起動したときの黒い画面)を閉じると、作業も止まる。

実行前の承認をブラウザで聞く(canUseTool)

対話型の Claude Code では、コマンドの実行やファイルの変更の前に、許可するかどうかを聞かれる。Agent SDK では、この問い合わせが canUseTool に渡した関数の呼び出しとして届く。関数が結果を返すまで Claude は待っているので、その間にブラウザへ確認画面を出し、押されたボタンに応じて結果を返すようにした。

function takeApproval(toolName, input, options) {
  return new Promise((resolve) => {
    const requestId = randomUUID();
    const suggestions = Array.isArray(options?.suggestions)
      ? options.suggestions.filter(s => s && s.destination === 'localSettings') : [];
    const canRemember = toolName !== 'AskUserQuestion' && suggestions.length > 0 && options?.suppressAlwaysAllowRule !== true;
    pending.set(requestId, {
      decide: (decision, answers) => {
        pending.delete(requestId);
        emit({ type: 'approval_closed', requestId, decision });
        if (decision !== 'allow' && decision !== 'always') {
          return resolve({ behavior: 'deny', message: 'User denied this operation.' });
        }
        if (toolName === 'AskUserQuestion') {
          if (!answers || typeof answers !== 'object') return resolve({ behavior: 'deny', message: 'No answers provided.' });
          return resolve({ behavior: 'allow', updatedInput: { ...input, answers } });
        }
        if (decision === 'always' && canRemember) {
          // Writes the suggested rule to .claude/settings.local.json of the project.
          return resolve({ behavior: 'allow', updatedInput: input, updatedPermissions: suggestions });
        }
        resolve({ behavior: 'allow', updatedInput: input });
      },
    });
    emit({
      type: 'approval', requestId, toolName,
      input,
      questions: toolName === 'AskUserQuestion' ? input?.questions : undefined,
      reason: options?.decisionReason || '',
      canRemember,
    });
  });
}

流れは次のとおり。

  1. SDK が canUseTool を呼ぶ。サーバーは問い合わせに番号(requestId)を付けて控え、ブラウザへ approval のイベントを送る
  2. ブラウザが確認画面を出す。ツールの名前と、実行しようとしている内容がそのまま表示される
  3. ボタンを押すと、ブラウザが番号と結果をサーバーへ送る
  4. サーバーは控えておいた問い合わせに結果を返す。許可なら behavior: 'allow'、拒否なら behavior: 'deny' で、Claude の処理が続く
コマンドの実行前に表示される確認画面
実行前の確認画面(テストモードで撮ったもの)

SDK は、問い合わせと一緒に「次からは聞かないための許可ルール」の候補を渡してくることがある。候補があるときは「今後も許可(このフォルダ)」のボタンも出し、押されたら候補を updatedPermissions に入れて返す。ルールは作業フォルダの .claude\settings.local.json に保存される。

Claude が選択肢つきの質問をしてくるとき(AskUserQuestion というツール)も、同じ canUseTool に届く。この場合は選択肢をボタンで出し、質問文をキー、選んだ答えを値にした answers を入力に足して返すと、Claude に答えが伝わる。

なお、すべての操作で確認画面が出るわけではない。公式ドキュメントによると、権限モードや許可ルールですでに許可・拒否が決まった操作では、canUseTool は呼ばれない。確認画面が出るのは、それらで決まらなかった操作だけである。

作業中でも追加の指示を送る(ストリーミング入力)

最初の版は、Claude の作業が終わるまで次の発言を送れなかった。長い作業の途中で「そこは違う」「これも一緒に」と伝えられないのは不便である。

query() の prompt には、文字列の代わりに「発言が1つずつ出てくる流れ」(非同期ジェネレーター)を渡せる。流れを開けたままにしておくと、作業の途中でも発言を追加で流し込める。公式ドキュメントによると、ツールの実行中に送った発言は、そのツールが終わったあとに Claude へ届き、Claude は前の発言と合わせて1つの回答で答える。

サーバーには発言を入れておく箱を用意し、画面から発言が届くたびに箱へ入れる。query() に渡した流れは、箱が空の間は待ち、発言が入ると取り出して SDK に渡す。

function pushInbox(text, images) {
  const uuid = randomUUID();
  const content = images.length
    ? [
      { type: 'text', text },
      ...images.map(image => ({
        type: 'image',
        source: { type: 'base64', media_type: image.mimeType, data: image.data },
      })),
    ]
    : text;
  inbox.unanswered.add(uuid);
  inbox.pending.push({ type: 'user', uuid, message: { role: 'user', content }, parent_tool_use_id: null });
  inbox.wake?.();
}

async function* inboxStream(box) {
  while (true) {
    const next = box.pending.shift();
    if (next) yield next;
    else if (box.closed) return;
    else {
      await new Promise(resolve => { box.wake = resolve; });
      box.wake = null;
    }
  }
}

流れを開けたままだと query() が終わらないので、閉じるタイミングが要る。発言には1つずつ ID(uuid)を付けておく。Claude が回答を終えるたびに届く result には、その回答がどの発言に答えたかの ID の一覧(user_message_uuids)が入っている。送った発言のすべてに答えが付いたら、流れを閉じて作業を終える。

試しに、8秒待つコマンドを実行させている間に「最後に一言足して」と送ったところ、コマンドが終わったあとの回答に、元の指示への答えと追加の一言の両方が入っていた。

作業中に追加で送った発言が表示されたチャット画面
作業中に送った発言は「作業中に追加」と付いて並び、その下に続きの回答が出る(テストモード)

発言には画像も付けられる。スクリーンショットを貼り付けて「これを見て」と頼めるように、文章と画像を並べた形の発言にして渡している。受け付けるのは PNG・JPEG・GIF・WebP で、1回に4枚まで、1枚5MBまでにしている。サーバー側で、ファイルの先頭のバイト列が申告された形式と合っているかも確かめている。

CLAUDE.md や設定を読み込ませる

settingSources に user・project・local を指定しているので、~/.claude/CLAUDE.md や、作業フォルダの CLAUDE.md・.claude\settings.json が読み込まれる。普段の Claude Code 用に書いてあるルール(作業ファイルを置く場所、返答の言葉づかいなど)が、この画面でもそのまま効く。

サブスク側の会話と行き来する

使い始めて不便だったのは、サブスク側(デスクトップアプリやターミナルの Claude Code)の会話と、この画面の会話がつながらないことだった。利用枠を使い切ったときにこの画面へ移り、枠が戻ったら元に戻る、という使い方をしたい。調べると、両方の会話は同じ場所に保存されていて、互いに引き継げることが分かった。

会話の記録は同じ場所にある

公式ドキュメントによると、Claude Code は会話の記録を次の場所に保存する。<フォルダ> は、作業フォルダのパスの英数字以外を - に置き換えた名前である。

~/.claude/projects/<フォルダ>/<会話のID>.jsonl

Agent SDK で作った会話も、デスクトップアプリで作った会話も、ここに並んで入っていた。記録はサインインの方法(プランか API キーか)とは関係なく、PC の中のファイルである。そのため、作業フォルダが同じなら、どちらで作った会話でも ID を resume に渡せば続きができる。

サブスク側の会話を、この画面で引き継ぐ

画面の左に「会話の履歴」を付け、開いている作業フォルダの会話を新しい順に並べた。選ぶと、記録を読み込んでこれまでのやり取りを表示し、次の指示からその会話の続きになる。「新しい会話」を押しても前の会話は消えず、この一覧に残る。

一覧は、Agent SDK の listSessions() で取得し、過去のやり取りは getSessionMessages() で読んでいる。ただ、listSessions() だけでは、私のデスクトップアプリの会話の大半が出てこなかった(48件のうち、出たのは7件)。デスクトップアプリのプロジェクトのスレッドから始めた会話は、私の発言が専用のタグに包まれて記録されていて、listSessions() が題名を取り出せずに一覧から外していたためである。そこで、保存フォルダを直接見て、足りない会話を補うようにした。会話の記録の形式は Claude Code の内部のもので、バージョンによって変わると公式ドキュメントに書かれているので、読むのは題名を取るための先頭部分だけにして、読めなければ題名なしで出すようにしてある。

確認のため、プロジェクトのスレッドから始めた会話を複製し、この画面で開いて、API キーで続きを頼んでみた(確認の作業は Claude Code に任せた)。前のやり取りを踏まえた返事が返ってきた。複製を使ったのは、元の会話に書き足さずに試すためである。

この画面の会話を、サブスク側で続ける

逆向きは、Claude Code のコマンドで行う。公式ドキュメントによると、Agent SDK や claude -p で作った会話は、ターミナルの会話の一覧(claude --resume や /resume で出るもの)には出てこないが、ID を指定すれば再開できる。作業フォルダでターミナルを開き、次のように実行する。

claude --resume <会話のID>

デスクトップアプリで開く場合は、次のコマンドになる。公式ドキュメントによると、Claude のプランでサインインしていることが条件で(API キーでの認証では使えない)、Claude Code v2.1.285 以降が必要である。

claude --desktop --resume <会話のID>

ID を調べて打ち込むのは手間なので、画面の右上に「サブスク側で続ける」というメニューを付けた。選ぶと、新しい PowerShell のウインドウが開き、作業フォルダで上のコマンドが実行される。このとき、API キーの環境変数を取り除いてから起動しているので、開いた先はプランのサインインで動く。

この画面から API キーで続きをした会話で試したところ、デスクトップアプリの一覧にその会話が現れ、API キーで進めた分のやり取りも含めて表示された。

サブスク側で続けるためのメニュー
右上のメニューから、今の会話をデスクトップアプリやターミナルへ引き継ぐ

サブスク側で続けたあと、またこの画面に戻ってきたときは、記録が外で更新されたことを見つけて、進んだ分を読み込み直す。

行き来するときの注意

  • 同じ会話を、両方で同時に動かさない。公式ドキュメントによると、同じ会話を2か所で同時に再開すると、両方が1つの記録に書き込み、あとで再開したときにやり取りの一部が欠けることがある
  • 長い会話を引き継ぐと、最初の1回は会話全体を読み直すことになる。API クレジットは使った量で引かれるので、長い会話ほど最初の1回の費用が大きい。3MB を超える記録を開くときは、確認を出すようにした
  • 引き継げるのは、同じ PC の、同じ作業フォルダの会話である

自分の PC の中だけで動かすための対策

このサーバーは、指示されたとおりに PC 上のファイルを書き換え、コマンドを実行できる。ほかの PC や、たまたま開いた別の Web ページから操作されないように、次の対策を入れた。

  • 待ち受けるアドレスは 127.0.0.1 だけにする(ほかの PC からは接続できない)
  • リクエストの Host ヘッダーと Origin ヘッダーを確かめ、自分のアドレス以外からのものは 403 で断る
  • Content-Security-Policy を付け、画面が読み込めるスクリプトや通信先を自分自身に限る
  • API キーは画面に表示しない。エラー文にキーが含まれていたら、伏せ字に置き換えてから表示する
  • Claude 自身に API キーのファイルを読ませない(次の項)

API キーのファイルを Claude に読ませない

API キーのファイルは PC の中にあるので、何もしなければ、Claude がファイルを読むツールで中身を読めてしまう。そこで、ツールが実行される前に呼ばれる PreToolUse フックを query() の設定に入れ、キーのファイル名やその置き場所を含む操作を断るようにした。

function guardKey(hookInput) {
  if (!keyFile) return {};
  let text;
  try { text = JSON.stringify(hookInput?.tool_input ?? {}); }
  catch { return {}; }
  const haystack = text.replaceAll('\\\\', '/').replaceAll('\\', '/').toLowerCase();
  const keyDir = path.dirname(keyFile).replaceAll('\\', '/').toLowerCase();
  const shell = hookInput?.tool_name === 'Bash' || hookInput?.tool_name === 'PowerShell';
  const hit = haystack.includes(KEY_FILE_NAME) || haystack.includes(keyDir) ||
    (shell && haystack.includes('anthropic_api_key'));
  if (!hit) return {};
  return {
    hookSpecificOutput: {
      hookEventName: 'PreToolUse',
      permissionDecision: 'deny',
      permissionDecisionReason: 'The API key of this chat tool is off limits. Do not read, print, or copy it.',
    },
  };
}

Claude に「このファイルを読んでみて」と頼んで確かめたところ、読み取りはフックで止まり、確認画面が出ることもなかった。ただし、これは完全な防御ではない。ワイルドカードでファイルを指す、環境変数を全部表示する、といった操作までは止められない。権限モードを手動承認にしておけば、そうしたコマンドは実行前に確認画面に出る。

対話型の Claude Code と違うところ

これは Agent SDK を使った自作の画面で、Claude Code そのものではない。今の時点で、次の違いがある。

  • 選べる権限モードは、Auto と手動承認の2つだけ
  • 添付できるのは画像だけ
  • 画面に出す過去のやり取りは、新しいほうから120件まで(記録そのものは消えない)
  • 表示される費用は SDK が報告する参考値。正確な残高は Claude Console の請求画面で確認する

ここまでに、ChatGPT に3つの版を作らせている。最初は claude -p を PowerShell のループから1回ずつ呼ぶ形、次に Agent SDK を使ったコンソール版、最後がブラウザ版である。claude -p の版には承認を画面で聞く仕組みを入れておらず、ファイルの編集を自動で許可するモード(acceptEdits)で動かしていた。Agent SDK にしてからは、canUseTool で承認と質問を受けられるようになった。そのブラウザ版を Claude Code に見直させたのが、今の版である。

使うときの注意

  • クレジットは翌月に繰り越せない。公式ヘルプによると、使わなかった分は請求の周期の終わりに失効する
  • クレジットを使い切ったあとの動きは、Console 側の設定で変わる。公式ヘルプによると、購入したクレジットがあるか自動チャージ(auto-reload)を有効にしていると、そちらから引かれて使い続けられる。どちらも無ければ、次のクレジットが届くまで API のリクエストが止まる。Claude のプランに請求が回ることはない
  • 連携した組織の API キーを使う全員で、同じ残高を分け合う
  • 公式ドキュメントによると、Agent SDK で作ったものを他人に提供する場合、claude.ai のログインやプランの利用枠を使わせることは(事前の承認が無い限り)認められていない。また「Claude Code」という名前や、Claude Code に似せた見た目を使うことも認められていない。私のものは自分の PC で自分だけが使う道具で、名前も Claude Agent としている

この記事のまとめ

この記事のまとめ
  • Max プランの API クレジットは月100ドル。対話型の Claude Code は対象外で、API・Batch API・Playground・Managed Agents・Agent SDK が対象
  • Agent SDK を、連携した Console の組織の API キーで動かすと、クレジットから引かれる
  • 承認と質問は canUseTool で受けて、ブラウザの確認画面に出す
  • 会話の記録はサブスク側と同じ場所にあるので、ID を resume に渡せば互いに引き継げる
  • サーバーは 127.0.0.1 だけで待ち受け、API キーは画面にもエラー文にも出さず、Claude にも読ませない

関連記事

参考

コードの全文

6つのファイルの全文を載せる。「全体の仕組み」の構成どおりに置き、npm install を実行してから起動する。API キーは含まれていない。

package.json

{
  "name": "claude-api-credit-agent-ui",
  "private": true,
  "version": "4.0.0",
  "type": "module",
  "description": "Local browser-based Claude Agent SDK interface",
  "dependencies": {
    "@anthropic-ai/claude-agent-sdk": "^0.3.329",
    "markdown-it": "^14.1.0"
  }
}

web_chat.bat

@echo off
setlocal EnableExtensions
chcp 65001 >nul
cd /d "%~dp0"
if errorlevel 1 goto :cd_failed

where node.exe >nul 2>&1
if errorlevel 1 goto :node_missing
where npm.cmd >nul 2>&1
if errorlevel 1 goto :npm_missing
if not exist "package.json" goto :files_missing
if not exist "agent_web.mjs" goto :files_missing
if not exist "web\index.html" goto :files_missing

if not exist "node_modules\@anthropic-ai\claude-agent-sdk\package.json" goto :install
if not exist "node_modules\markdown-it\dist\markdown-it.min.js" goto :install
goto :start

:install
echo [SETUP] Installing Claude Agent SDK and Markdown renderer...
call npm.cmd install --no-fund --no-audit
if errorlevel 1 goto :install_failed
if not exist "node_modules\markdown-it\dist\markdown-it.min.js" goto :install_failed
if not exist "node_modules\@anthropic-ai\claude-agent-sdk\package.json" goto :install_failed

:start
echo [START] Opening browser chat...
node.exe "%~dp0agent_web.mjs"
set "RUN_EXIT=%ERRORLEVEL%"
if not "%RUN_EXIT%"=="0" echo [ERROR] Web chat exited with code %RUN_EXIT%.
goto :end

:cd_failed
echo [ERROR] Could not change directory.
goto :end
:node_missing
echo [ERROR] Node.js is not installed or not on PATH.
goto :end
:npm_missing
echo [ERROR] npm.cmd was not found.
goto :end
:files_missing
echo [ERROR] Package files are missing. Extract all ZIP files.
goto :end
:install_failed
echo [ERROR] npm install failed. Check your network, proxy, and npm configuration.
echo [HINT] Try npm.cmd install --no-fund --no-audit in this folder.
goto :end
:end
echo.
pause
endlocal

agent_web.mjs

/**
 * Claude Agent SDK local web chat (v4).
 * Run from this folder using Node.js 20+.
 * Binds ONLY to 127.0.0.1, with no remote access.
 *
 * v4: runs keep going when the browser tab is closed or reloaded, the
 * conversation is stored in the order things happened, sessions made by other
 * Claude Code surfaces in the same folder can be opened and continued, and a
 * session can be handed back to the desktop app or the terminal.
 */
import http from 'node:http';
import path from 'node:path';
import { readFile, writeFile, mkdir, rename, stat, realpath, readdir, open } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';

const HERE = path.dirname(fileURLToPath(import.meta.url));
// The tool is meant to live in <project>/tools/api_credit, so the folder two
// levels up is the project opened on the very first start.
const DEFAULT_PROJECT = process.env.CHAT_WEB_DEFAULT_PROJECT || path.resolve(HERE, '..', '..');
const WEB = path.join(HERE, 'web');
// UI state is kept beside the application, not inside the currently opened project.
const APP_RUNTIME = process.env.CHAT_WEB_STATE_DIR || path.join(HERE, '.runtime');
const STATE_FILE = path.join(APP_RUNTIME, 'projects.json');
const LEGACY_STATE_FILE = path.join(DEFAULT_PROJECT, '.runtime', 'agent_web_state.json');
const KEY_FILE_NAME = 'anthropic_api_key.txt';
const KEY_FILE_CANDIDATES = [
  process.env.CHAT_WEB_KEY_FILE,
  path.join(HERE, '.runtime', KEY_FILE_NAME),
  path.join(DEFAULT_PROJECT, '.runtime', KEY_FILE_NAME),
].filter(Boolean);
const HOST = '127.0.0.1';
const API_VERSION = 4;
// JSON base64 is ~4/3 of the original image bytes; four images * 5 MiB.
const MAX_BODY = 32 * 1024 * 1024;
const MAX_IMAGES = 4;
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
const IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
const HISTORY_LIMIT = 120;
const SESSION_LIST_LIMIT = 60;
const TOOL_INPUT_CLIP = 4000;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const TEST_MODE = process.env.CHAT_WEB_TEST_MODE === '1';

let apiKey = '';
let keyFile = '';
let busy = false;
let currentAbort = null;
let run = null; // { id, events: [], listeners: Set<ServerResponse>, done }
let currentProject = DEFAULT_PROJECT;
let recentProjects = [DEFAULT_PROJECT];
const projectStates = {};
let stateWriteQueue = Promise.resolve();
let pickerBusy = false;
let sessionId = null;
let model = 'claude-fable-5-2';
let permissionMode = 'auto';
let history = [];
let totalCost = 0;
let syncedAt = 0;
const pending = new Map();
let sdkModule = null;

function sdk() {
  if (!sdkModule) sdkModule = import('@anthropic-ai/claude-agent-sdk');
  return sdkModule;
}

function json(res, code, value) {
  res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
  res.end(JSON.stringify(value));
}

function fail(statusCode, message) {
  return Object.assign(new Error(message), { statusCode });
}

function safeError(err) {
  const message = String(err?.message ?? err);
  return apiKey ? message.replaceAll(apiKey, '[API KEY HIDDEN]') : message;
}

async function readJson(req) {
  if (!(req.headers['content-type'] || '').startsWith('application/json')) {
    throw fail(415, 'Content-Type must be application/json');
  }
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > MAX_BODY) throw fail(413, 'Payload too large');
    chunks.push(chunk);
  }
  try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
  catch { throw fail(400, 'Invalid JSON'); }
}

function validImageMagic(bytes, mimeType) {
  if (mimeType === 'image/png') return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
  if (mimeType === 'image/jpeg') return bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
  if (mimeType === 'image/gif') return bytes.subarray(0, 6).toString('ascii') === 'GIF87a' || bytes.subarray(0, 6).toString('ascii') === 'GIF89a';
  if (mimeType === 'image/webp') return bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP';
  return false;
}

function parseImages(raw) {
  if (raw === undefined || raw === null) return [];
  if (!Array.isArray(raw) || raw.length > MAX_IMAGES) {
    throw fail(400, '画像は最大' + MAX_IMAGES + '枚までです。');
  }
  return raw.map((item, index) => {
    const mimeType = item?.mimeType;
    const base64 = item?.data;
    if (!IMAGE_MIME.has(mimeType) || typeof base64 !== 'string' || !base64 ||
        base64.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4 + 4 ||
        !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
      throw fail(400, '画像' + (index + 1) + ': 形式またはサイズが不正です。');
    }
    const bytes = Buffer.from(base64, 'base64');
    if (!bytes.length || bytes.length > MAX_IMAGE_BYTES || bytes.toString('base64') !== base64 || !validImageMagic(bytes, mimeType)) {
      throw fail(400, '画像' + (index + 1) + ': 画像ファイルを確認してください(最大5MB)。');
    }
    const name = typeof item.name === 'string' ? item.name.slice(0, 120) : '画像' + (index + 1);
    // Save only a small client-generated preview, not the original image bytes, to local chat history.
    const preview = typeof item.preview === 'string' &&
      /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(item.preview) &&
      item.preview.length < 140000 ? item.preview : '';
    return { name, mimeType, data: base64, preview };
  });
}

// ---------------------------------------------------------------- state

function captureProject() {
  projectStates[currentProject] = {
    sessionId,
    model,
    permissionMode,
    totalCost,
    syncedAt,
    history: history.slice(-HISTORY_LIMIT),
  };
}

function loadProject(projectPath) {
  const state = projectStates[projectPath] || {};
  sessionId = typeof state.sessionId === 'string' ? state.sessionId : null;
  model = typeof state.model === 'string' && state.model.length <= 120
    ? state.model : 'claude-fable-5-2';
  permissionMode = ['auto', 'default'].includes(state.permissionMode) ? state.permissionMode : 'auto';
  totalCost = Number.isFinite(Number(state.totalCost)) ? Number(state.totalCost) : 0;
  syncedAt = Number.isFinite(Number(state.syncedAt)) ? Number(state.syncedAt) : 0;
  history = Array.isArray(state.history)
    ? state.history.slice(-HISTORY_LIMIT).filter(x => x && ['user', 'assistant'].includes(x.role) && typeof x.text === 'string')
    : [];
}

async function saveState() {
  captureProject();
  const snapshot = JSON.stringify({
    version: 3,
    currentProject,
    recentProjects,
    projectStates,
  }, null, 2);
  stateWriteQueue = stateWriteQueue.catch(() => {}).then(async () => {
    await mkdir(APP_RUNTIME, { recursive: true });
    const tmp = STATE_FILE + '.' + process.pid + '.' + randomUUID() + '.tmp';
    await writeFile(tmp, snapshot, { encoding: 'utf8', mode: 0o600 });
    await rename(tmp, STATE_FILE);
  });
  return stateWriteQueue;
}

async function validDirectory(folder) {
  if (typeof folder !== 'string' || !folder.trim() || folder.length > 2048 || !path.isAbsolute(folder.trim())) {
    throw fail(400, '作業フォルダの絶対パスを指定してください。');
  }
  let canonical;
  try {
    canonical = await realpath(folder.trim());
    if (!(await stat(canonical)).isDirectory()) throw new Error('Not a directory');
  } catch {
    throw fail(400, 'フォルダが存在しないか、アクセスできません。');
  }
  return canonical;
}

async function loadState() {
  try {
    const stored = JSON.parse(await readFile(STATE_FILE, 'utf8'));
    if (stored && stored.version === 3 && stored.projectStates && typeof stored.projectStates === 'object') {
      for (const [folder, state] of Object.entries(stored.projectStates)) {
        if (typeof folder === 'string' && path.isAbsolute(folder) && state && typeof state === 'object') {
          projectStates[folder] = state;
        }
      }
      recentProjects = Array.isArray(stored.recentProjects)
        ? [...new Set(stored.recentProjects.filter(x => typeof x === 'string' && path.isAbsolute(x)))].slice(0, 12)
        : [DEFAULT_PROJECT];
      try { currentProject = await validDirectory(stored.currentProject); }
      catch { currentProject = DEFAULT_PROJECT; }
      if (!recentProjects.includes(currentProject)) recentProjects.unshift(currentProject);
      loadProject(currentProject);
      return;
    }
  } catch (e) {
    if (e.code !== 'ENOENT') console.warn('Could not read project list. Starting fresh.');
  }
  // Import the previous single-project conversation once; do not alter its original file.
  try {
    const old = JSON.parse(await readFile(LEGACY_STATE_FILE, 'utf8'));
    if (old && typeof old === 'object') projectStates[DEFAULT_PROJECT] = old;
  } catch (e) {
    if (e.code !== 'ENOENT') console.warn('Legacy session state unreadable.');
  }
  recentProjects = [DEFAULT_PROJECT];
  currentProject = DEFAULT_PROJECT;
  loadProject(DEFAULT_PROJECT);
  await saveState();
}

function assertIdle(message) {
  if (busy || pickerBusy) throw fail(409, message || '実行中は変更できません。');
}

async function activateProject(projectPath) {
  assertIdle('実行中は作業フォルダを切り替えられません。');
  const nextPath = await validDirectory(projectPath);
  captureProject();
  currentProject = nextPath;
  recentProjects = [currentProject, ...recentProjects.filter(x => x !== currentProject)].slice(0, 12);
  loadProject(currentProject);
  await saveState();
  return currentState();
}

function currentState() {
  return {
    apiVersion: API_VERSION,
    model,
    mode: permissionMode,
    history,
    busy,
    runId: run && !run.done ? run.id : null,
    sessionId,
    sessionExists: !!sessionId,
    totalCost,
    projectName: path.basename(currentProject) || currentProject,
    projectPath: currentProject,
    recentProjects: recentProjects.map(folder => ({ path: folder, name: path.basename(folder) || folder, active: folder === currentProject })),
    nativePicker: process.platform === 'win32',
    handoff: process.platform === 'win32',
  };
}

function chooseNativeFolder() {
  const script = [
    'Add-Type -AssemblyName System.Windows.Forms',
    '[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)',
    '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
    "$dialog.Description = 'Choose a project folder'",
    '$dialog.ShowNewFolderButton = $false',
    'if (Test-Path -LiteralPath $env:CLAUDE_AGENT_PICK_INITIAL -PathType Container) {',
    '  $dialog.SelectedPath = $env:CLAUDE_AGENT_PICK_INITIAL',
    '}',
    'if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {',
    '  [Console]::WriteLine($dialog.SelectedPath)',
    '}',
    '$dialog.Dispose()',
  ].join('\n');
  return new Promise((resolve, reject) => {
    const encoded = Buffer.from(script, 'utf16le').toString('base64');
    const child = spawn('powershell.exe', ['-NoProfile', '-STA', '-EncodedCommand', encoded], {
      env: { ...process.env, CLAUDE_AGENT_PICK_INITIAL: currentProject },
      windowsHide: false,
    });
    let output = '';
    let errors = '';
    child.stdout.setEncoding('utf8');
    child.stderr.setEncoding('utf8');
    child.stdout.on('data', chunk => { if (output.length < 8192) output += chunk; });
    child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk; });
    child.on('error', reject);
    child.on('close', code => {
      if (code !== 0) reject(new Error('フォルダ選択画面を開けませんでした。パス入力を利用してください。' + (errors ? ' (' + errors.slice(0, 150) + ')' : '')));
      else resolve(output.trim() || null);
    });
  });
}

async function handleProjectSelect(req, res) {
  const data = await readJson(req);
  json(res, 200, await activateProject(data.path));
}

async function handleProjectPick(req, res) {
  await readJson(req);
  assertIdle('処理中はフォルダを選択できません。');
  if (process.platform !== 'win32') return json(res, 501, { error: 'このOSではパスを直接入力してください。' });
  pickerBusy = true;
  let folder;
  try { folder = await chooseNativeFolder(); }
  finally { pickerBusy = false; }
  if (!folder) return json(res, 200, { cancelled: true });
  json(res, 200, { cancelled: false, ...(await activateProject(folder)) });
}

async function handleProjectRemove(req, res) {
  assertIdle();
  const data = await readJson(req);
  if (typeof data.path !== 'string' || data.path === currentProject) {
    return json(res, 400, { error: '現在使用中のプロジェクトは履歴から削除できません。' });
  }
  // Hiding a recent project does not delete its files, session, or saved conversation.
  recentProjects = recentProjects.filter(x => x !== data.path);
  await saveState();
  json(res, 200, currentState());
}

// ---------------------------------------------------------------- run events

// Every event of a run is kept in memory, so a browser that reloads or
// reconnects can replay the run from the start instead of losing it.
function emit(event) {
  if (!run || run.done) return;
  run.events.push(event);
  const line = JSON.stringify(event) + '\n';
  for (const res of run.listeners) {
    if (!res.destroyed && !res.writableEnded) res.write(line);
  }
}

function finishRun() {
  if (!run) return;
  run.done = true;
  for (const res of run.listeners) res.end();
  run.listeners.clear();
}

function handleEvents(req, res, url) {
  const id = url.searchParams.get('run');
  if (!run || run.id !== id) return json(res, 404, { error: 'この実行はもう残っていません。' });
  const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0);
  res.writeHead(200, { 'Content-Type': 'application/x-ndjson; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'X-Accel-Buffering': 'no' });
  res.flushHeaders();
  for (const event of run.events.slice(after)) res.write(JSON.stringify(event) + '\n');
  if (run.done) return res.end();
  const current = run;
  current.listeners.add(res);
  // Closing the tab only stops listening. The run itself continues.
  res.on('close', () => current.listeners.delete(res));
}

function clip(value) {
  let text;
  try { text = JSON.stringify(value ?? {}, null, 2); }
  catch { text = String(value); }
  return text.length > TOOL_INPUT_CLIP ? text.slice(0, TOOL_INPUT_CLIP) + '\n…(以下省略)' : text;
}

// Turn the recorded events into history entries. The parts of an assistant
// entry keep the order in which text and tool calls happened, and a message
// the user sent in the middle of the run starts a new entry.
function buildEntries(events, selectedModel) {
  const out = [];
  let parts = [];
  let cost = null;
  let success = false;
  const toolParts = new Map();
  const flush = () => {
    if (parts.length) {
      out.push({
        id: randomUUID(), role: 'assistant',
        text: parts.filter(p => p.type === 'text').map(p => p.text).join('\n\n'),
        parts,
        createdAt: new Date().toISOString(), model: selectedModel,
        success, cost,
      });
    }
    parts = [];
    cost = null;
    success = false;
  };
  for (const ev of events) {
    if (ev.type === 'user_message') {
      flush();
      out.push({ id: randomUUID(), role: 'user', text: ev.text || '', images: ev.images || [], createdAt: new Date().toISOString(), model: selectedModel });
      continue;
    }
    if (ev.type === 'result') {
      success = !!ev.success;
      if (Number.isFinite(ev.cost)) cost = (cost || 0) + ev.cost;
      continue;
    }
    if (ev.type === 'text' && ev.text) {
      const last = parts[parts.length - 1];
      if (last && last.type === 'text') last.text += ev.text;
      else if (ev.text.trim()) parts.push({ type: 'text', text: ev.text });
    } else if (ev.type === 'tool') {
      const part = { type: 'tool', name: ev.name || 'Tool', input: clip(ev.input), sub: !!ev.sub };
      if (ev.id) toolParts.set(ev.id, part);
      parts.push(part);
    } else if (ev.type === 'tool_result' && toolParts.has(ev.id)) {
      toolParts.get(ev.id).status = ev.isError ? 'error' : 'ok';
    } else if (ev.type === 'notice' || ev.type === 'error') {
      parts.push({ type: 'notice', text: (ev.type === 'error' ? 'エラー: ' : '') + (ev.message || '') });
    }
  }
  flush();
  return out;
}

// ---------------------------------------------------------------- input queue

// The prompt of query() is a stream, not a string. The stream stays open while
// Claude works, so a message typed in the middle of a run can be pushed into
// it. Claude reads such a message once the tool calls in progress finish.
let inbox = null; // { pending: [], wake, closed, unanswered: Set<uuid> }

function openInbox() {
  inbox = { pending: [], wake: null, closed: false, unanswered: new Set() };
}

function pushInbox(text, images) {
  const uuid = randomUUID();
  const content = images.length
    ? [
      { type: 'text', text },
      ...images.map(image => ({
        type: 'image',
        source: { type: 'base64', media_type: image.mimeType, data: image.data },
      })),
    ]
    : text;
  inbox.unanswered.add(uuid);
  inbox.pending.push({ type: 'user', uuid, message: { role: 'user', content }, parent_tool_use_id: null });
  inbox.wake?.();
}

function closeInbox() {
  if (!inbox) return;
  inbox.closed = true;
  inbox.wake?.();
}

async function* inboxStream(box) {
  while (true) {
    const next = box.pending.shift();
    if (next) yield next;
    else if (box.closed) return;
    else {
      await new Promise(resolve => { box.wake = resolve; });
      box.wake = null;
    }
  }
}

// ---------------------------------------------------------------- approvals

function takeApproval(toolName, input, options) {
  return new Promise((resolve) => {
    const requestId = randomUUID();
    const suggestions = Array.isArray(options?.suggestions)
      ? options.suggestions.filter(s => s && s.destination === 'localSettings') : [];
    const canRemember = toolName !== 'AskUserQuestion' && suggestions.length > 0 && options?.suppressAlwaysAllowRule !== true;
    pending.set(requestId, {
      decide: (decision, answers) => {
        pending.delete(requestId);
        emit({ type: 'approval_closed', requestId, decision });
        if (decision !== 'allow' && decision !== 'always') {
          return resolve({ behavior: 'deny', message: 'User denied this operation.' });
        }
        if (toolName === 'AskUserQuestion') {
          if (!answers || typeof answers !== 'object') return resolve({ behavior: 'deny', message: 'No answers provided.' });
          return resolve({ behavior: 'allow', updatedInput: { ...input, answers } });
        }
        if (decision === 'always' && canRemember) {
          // Writes the suggested rule to .claude/settings.local.json of the project.
          return resolve({ behavior: 'allow', updatedInput: input, updatedPermissions: suggestions });
        }
        resolve({ behavior: 'allow', updatedInput: input });
      },
    });
    emit({
      type: 'approval', requestId, toolName,
      input,
      questions: toolName === 'AskUserQuestion' ? input?.questions : undefined,
      reason: options?.decisionReason || '',
      canRemember,
    });
  });
}

function denyOutstanding() {
  for (const item of [...pending.values()]) item.decide('deny');
  pending.clear();
}

// ---------------------------------------------------------------- key guard

// Best effort: stop the agent from reading the API key through its own tools.
// This is not a sandbox. A command that reaches the file by a wildcard, or
// that dumps every environment variable, is not caught here.
function guardKey(hookInput) {
  if (!keyFile) return {};
  let text;
  try { text = JSON.stringify(hookInput?.tool_input ?? {}); }
  catch { return {}; }
  const haystack = text.replaceAll('\\\\', '/').replaceAll('\\', '/').toLowerCase();
  const keyDir = path.dirname(keyFile).replaceAll('\\', '/').toLowerCase();
  const shell = hookInput?.tool_name === 'Bash' || hookInput?.tool_name === 'PowerShell';
  const hit = haystack.includes(KEY_FILE_NAME) || haystack.includes(keyDir) ||
    (shell && haystack.includes('anthropic_api_key'));
  if (!hit) return {};
  return {
    hookSpecificOutput: {
      hookEventName: 'PreToolUse',
      permissionDecision: 'deny',
      permissionDecisionReason: 'The API key of this chat tool is off limits. Do not read, print, or copy it.',
    },
  };
}

// ---------------------------------------------------------------- one turn

async function runMockTurn(images) {
  const wait = ms => new Promise(r => setTimeout(r, ms));
  emit({ type: 'image_received', count: images.length });
  emit({ type: 'text', text: 'フォルダの中を確認します。\n\n' });
  await wait(300);
  emit({ type: 'tool', name: 'Glob', id: 't1', input: { pattern: '**/*.md' } });
  await wait(300);
  emit({ type: 'tool_result', id: 't1', isError: false });
  emit({ type: 'tool', name: 'Read', id: 't2', input: { file_path: 'README.md' } });
  await wait(300);
  emit({ type: 'tool_result', id: 't2', isError: false });
  emit({ type: 'text', text: 'README を読みました。次に、テスト用のコマンドを実行します。\n\n' });
  const d = await takeApproval('Bash', { command: 'echo test', description: 'Mock approval for UI validation' }, {});
  emit({ type: 'tool', name: 'Bash', id: 't3', input: { command: 'echo test' } });
  await wait(200);
  emit({ type: 'tool_result', id: 't3', isError: d.behavior !== 'allow' });
  emit({ type: 'text', text: '## 確認の結果\n\n**Markdown が整形されます。**\n\n| 項目 | 内容 |\n|---|---|\n| ファイル | README.md |\n| 承認の結果 | ' + d.behavior + ' |\n\n作業はここまでです。' });
  inbox.pending.shift(); // the first prompt
  while (inbox.pending.length) {
    inbox.pending.shift();
    emit({ type: 'text', text: '\n\n途中で送られた追加の指示も読みました。' });
  }
  closeInbox();
  emit({ type: 'result', success: true, cost: 0.0012, final: true, denials: [] });
  if (!sessionId) sessionId = randomUUID();
  return { success: true, cost: 0.0012 };
}

async function runSdkTurn(selectedModel, selectedMode, workingDirectory) {
  const { query } = await sdk();
  const abortController = new AbortController();
  currentAbort = abortController;
  const opts = {
    cwd: workingDirectory,
    model: selectedModel,
    permissionMode: selectedMode,
    canUseTool: (toolName, input, options) => takeApproval(toolName, input, options),
    includePartialMessages: true,
    abortController,
    settingSources: ['user', 'project', 'local'],
    hooks: { PreToolUse: [{ hooks: [async (input) => guardKey(input)] }] },
    env: { ...process.env, ANTHROPIC_API_KEY: apiKey, ENABLE_CLAUDEAI_MCP_SERVERS: 'false' },
  };
  if (sessionId) opts.resume = sessionId;
  let sawText = false;
  let resultSeen = false;
  let success = false;
  let cost = null;
  let currentMsgHadTextDeltas = false;
  const box = inbox;

  for await (const message of query({ prompt: inboxStream(box), options: opts })) {
    if (typeof message.session_id === 'string' && message.session_id) sessionId = message.session_id;
    // Messages of a subagent carry the id of the tool call that started it.
    const sub = !!message.parent_tool_use_id;
    if (message.type === 'stream_event') {
      const ev = message.event;
      if (ev?.type === 'message_start' && !sub) currentMsgHadTextDeltas = false;
      if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && !sub) {
        const delta = ev.delta.text || '';
        sawText = true;
        currentMsgHadTextDeltas = true;
        emit({ type: 'text', text: delta });
      }
      if (ev?.type === 'content_block_start' && ev.content_block?.type === 'tool_use') {
        emit({ type: 'tool_start', name: ev.content_block.name, id: ev.content_block.id });
      }
    } else if (message.type === 'assistant') {
      const blocks = message.message?.content || [];
      for (const block of blocks) {
        if (block.type === 'tool_use') emit({ type: 'tool', name: block.name, input: block.input, id: block.id, sub });
        if (block.type === 'text' && !sub && !currentMsgHadTextDeltas && block.text) {
          sawText = true;
          emit({ type: 'text', text: block.text });
        }
      }
      if (!sub) {
        currentMsgHadTextDeltas = false;
        // Keep text of separate assistant messages apart in the rendered Markdown.
        emit({ type: 'text', text: '\n\n' });
      }
    } else if (message.type === 'user') {
      const blocks = Array.isArray(message.message?.content) ? message.message.content : [];
      for (const block of blocks) {
        if (block?.type === 'tool_result') emit({ type: 'tool_result', id: block.tool_use_id, isError: !!block.is_error });
      }
    } else if (message.type === 'system' && message.subtype === 'permission_denied') {
      emit({ type: 'notice', message: '権限がないため、一部の操作が拒否されました。' });
    } else if (message.type === 'system' && message.subtype === 'compact_boundary') {
      emit({ type: 'notice', message: '会話が長くなったため、ここまでの内容が自動で要約されました。' });
    } else if (message.type === 'result') {
      resultSeen = true;
      success = message.subtype === 'success' && !message.is_error;
      const lastResult = String(message.result || '');
      const denials = Array.isArray(message.permission_denials) ? message.permission_denials : [];
      if (!sawText && lastResult) emit({ type: 'text', text: lastResult });
      sawText = false;
      // total_cost_usd counts up over the whole query() call, so the cost of
      // this response is the difference from the previous result.
      const total = Number.isFinite(Number(message.total_cost_usd)) ? Number(message.total_cost_usd) : null;
      const responseCost = total === null ? null : Math.max(0, total - (cost || 0));
      if (total !== null) cost = total;
      // The result names the messages it answered. When every message that was
      // pushed has been answered, close the stream so that query() can end.
      const answered = Array.isArray(message.user_message_uuids) ? message.user_message_uuids
        : (message.user_message_uuid ? [message.user_message_uuid] : null);
      let matched = 0;
      for (const id of answered || []) if (box.unanswered.delete(id)) matched += 1;
      // A CLI that does not report the ids: take the result as the answer to everything sent so far.
      if (!matched) box.unanswered.clear();
      const final = !success || box.unanswered.size === 0;
      if (final) closeInbox();
      emit({
        type: 'result', success, subtype: message.subtype, cost: responseCost, final,
        denials: denials.map(x => ({ name: x.tool_name || x.toolName || 'Tool' })),
        errors: message.errors || [],
      });
    }
  }
  if (!resultSeen) emit({ type: 'notice', message: 'SDKから最終結果が返りませんでした。' });
  return { success: resultSeen && success, cost };
}

async function executeRun(images, selectedModel, selectedMode, workingDirectory) {
  let answer = { success: false, cost: null };
  try {
    answer = TEST_MODE
      ? await runMockTurn(images)
      : await runSdkTurn(selectedModel, selectedMode, workingDirectory);
  } catch (e) {
    emit({ type: 'error', message: safeError(e) });
  } finally {
    closeInbox();
    denyOutstanding();
    history.push(...buildEntries(run.events, selectedModel));
    if (Number.isFinite(answer.cost)) totalCost += answer.cost;
    syncedAt = Date.now();
    busy = false;
    currentAbort = null;
    try { await saveState(); } catch (err) { console.warn('Could not save session:', safeError(err)); }
    emit({ type: 'done', success: answer.success, totalCost, sessionId });
    finishRun();
  }
}

async function handleRun(req, res) {
  const data = await readJson(req);
  const images = parseImages(data.images);
  let prompt = typeof data.prompt === 'string' ? data.prompt.trim() : '';
  if (!prompt && images.length) prompt = '添付画像を確認してください。';
  if (!prompt || prompt.length > 200000) return json(res, 400, { error: '指示を入力するか、画像を添付してください(最大20万文字)。' });
  const previews = images.map(({ name, preview }) => ({ name, preview }));
  if (busy && run && !run.done) {
    // A run is in progress: hand the message to the running agent.
    if (!inbox || inbox.closed) return json(res, 409, { error: '前の作業がちょうど終わるところです。', retry: true });
    pushInbox(prompt, images);
    emit({ type: 'user_message', text: prompt, images: previews });
    return json(res, 200, { ok: true, queued: true, runId: run.id });
  }
  assertIdle('別の処理を実行中です。');
  const selectedModel = typeof data.model === 'string' && data.model.trim() && data.model.trim().length <= 120 ? data.model.trim() : model;
  const selectedMode = ['auto', 'default'].includes(data.mode) ? data.mode : permissionMode;
  model = selectedModel;
  permissionMode = selectedMode;
  busy = true;
  run = { id: randomUUID(), events: [], listeners: new Set(), done: false };
  openInbox();
  pushInbox(prompt, images);
  history.push({ id: randomUUID(), role: 'user', text: prompt, images: previews, createdAt: new Date().toISOString(), model });
  await saveState();
  emit({ type: 'started', model, mode: permissionMode });
  json(res, 200, { ok: true, runId: run.id });
  // Not awaited: the run is independent of this HTTP request.
  executeRun(images, selectedModel, selectedMode, currentProject)
    .catch(err => console.error('[Run]', safeError(err)));
}

async function handleApproval(req, res) {
  const data = await readJson(req);
  const item = pending.get(data.requestId);
  if (!item) return json(res, 404, { error: '承認依頼は既に終了しています。' });
  item.decide(['allow', 'always'].includes(data.decision) ? data.decision : 'deny', data.answers);
  json(res, 200, { ok: true });
}

async function handleSettings(req, res) {
  assertIdle('実行中は設定を変更できません。');
  const data = await readJson(req);
  if (typeof data.model === 'string' && data.model.trim() && data.model.length <= 120) model = data.model.trim();
  if (['auto', 'default'].includes(data.mode)) permissionMode = data.mode;
  await saveState();
  json(res, 200, { model, mode: permissionMode });
}

async function handleNew(req, res) {
  assertIdle('実行中は新規会話を開始できません。');
  await readJson(req);
  // Only this screen is reset. The transcript of the old session stays on disk.
  sessionId = null;
  history = [];
  totalCost = 0;
  syncedAt = Date.now();
  await saveState();
  json(res, 200, currentState());
}

async function handleStop(req, res) {
  await readJson(req);
  if (!busy) return json(res, 409, { error: '実行中の処理はありません。' });
  denyOutstanding();
  currentAbort?.abort();
  json(res, 200, { ok: true });
}

// ---------------------------------------------------------------- sessions

// Sessions live in ~/.claude/projects/<folder>/ no matter which Claude Code
// surface created them, so sessions of the desktop app or the terminal in the
// same folder show up here as well.
async function handleSessionList(req, res) {
  const { listSessions } = await sdk();
  const listed = await listSessions({ dir: currentProject, limit: SESSION_LIST_LIMIT });
  const rows = listed.map(s => ({
    id: s.sessionId,
    title: String(s.customTitle || s.summary || s.firstPrompt || '').slice(0, 160),
    lastModified: s.lastModified,
    fileSize: s.fileSize || 0,
  }));
  const known = new Set(rows.map(r => r.id));
  for (const extra of await unlistedSessions(currentProject, known)) rows.push(extra);
  rows.sort((a, b) => b.lastModified - a.lastModified);
  json(res, 200, {
    sessions: rows.slice(0, SESSION_LIST_LIMIT).map(r => ({
      ...r,
      title: r.title || '(題名なし)',
      current: r.id === sessionId,
      // Somebody else (desktop app, terminal) appended to it after we last looked.
      changedOutside: r.id === sessionId && !busy && r.lastModified > syncedAt + 5000,
    })),
  });
}

// Where Claude Code keeps the transcripts of one folder: every character of
// the path that is not a letter or a digit becomes "-".
function transcriptDir(folder) {
  const name = folder.replace(/[^a-zA-Z0-9]/g, '-');
  if (name.length > 200) return null; // long names get a hash appended; not handled here
  const base = process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), '.claude');
  return path.join(base, 'projects', name);
}

const titleCache = new Map();

// listSessions() leaves out a session when it cannot find a title for it. That
// happens to sessions started from a project thread of the desktop app, whose
// prompts are wrapped in <wake> tags. Add those from the transcript folder.
// The transcript format is internal to Claude Code, so this only reads the
// start of each file and falls back to an empty title when anything is odd.
async function unlistedSessions(folder, known) {
  const dir = transcriptDir(folder);
  if (!dir) return [];
  let names;
  try { names = await readdir(dir); } catch { return []; }
  const out = [];
  for (const name of names) {
    if (!name.endsWith('.jsonl')) continue;
    const id = name.slice(0, -6);
    if (!UUID.test(id) || known.has(id)) continue;
    const file = path.join(dir, name);
    let info;
    try { info = await stat(file); } catch { continue; }
    if (!info.isFile() || info.size < 200) continue;
    const cacheKey = id + ':' + info.mtimeMs;
    if (!titleCache.has(cacheKey)) titleCache.set(cacheKey, await headTitle(file));
    const title = titleCache.get(cacheKey);
    if (title === null) continue; // a subagent transcript
    out.push({ id, title, lastModified: Math.round(info.mtimeMs), fileSize: info.size });
  }
  return out;
}

async function headTitle(file) {
  let text = '';
  let handle;
  try {
    handle = await open(file, 'r');
    const buffer = Buffer.alloc(262144);
    const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
    text = buffer.subarray(0, bytesRead).toString('utf8');
  } catch { return ''; }
  finally { await handle?.close(); }
  const lines = text.split('\n');
  if (lines[0].includes('"isSidechain":true')) return null;
  for (const line of lines) {
    if (!line.includes('"type":"user"')) continue;
    try {
      const entry = JSON.parse(line);
      if (entry.type !== 'user' || entry.isSidechain) continue;
      const title = userText(entry.message?.content).replace(/\s+/g, ' ').trim();
      if (title) return title.slice(0, 160);
    } catch { /* a line cut off at the end of the buffer */ }
  }
  return '';
}

function unescapeXml(text) {
  return text.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&apos;', "'").replaceAll('&amp;', '&');
}

function userText(content) {
  let text = '';
  if (typeof content === 'string') text = content;
  else if (Array.isArray(content)) {
    text = content.filter(b => b && b.type === 'text' && typeof b.text === 'string').map(b => b.text).join('\n');
  }
  text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
  // A prompt that arrived through a project thread of the desktop app: keep
  // only what the person wrote.
  if (text.startsWith('<wake')) {
    const pick = pattern => [...text.matchAll(pattern)].map(m => unescapeXml(m[1]).trim()).filter(Boolean);
    // The message that woke the session; earlier messages of the thread may be quoted beside it.
    const trigger = pick(/<message\b[^>]*\btrigger="true"[^>]*>([\s\S]*?)<\/message>/g);
    const said = trigger.length ? trigger : pick(/<message\b[^>]*\bfrom="human"[^>]*>([\s\S]*?)<\/message>/g);
    return said.join('\n\n');
  }
  // Wrappers written by slash commands, hooks and background tasks are not something the user typed.
  if (/^<(command-name|command-message|command-args|local-command-|task-notification|bash-|user-prompt-submit-hook)/.test(text)) return '';
  return text;
}

function transcriptToHistory(messages) {
  const out = [];
  let assistant = null;
  const toolParts = new Map();
  for (const m of messages) {
    if (!m || m.parent_tool_use_id) continue;
    const content = m.message?.content;
    if (m.type === 'user') {
      if (Array.isArray(content)) {
        for (const b of content) {
          if (b?.type === 'tool_result' && toolParts.has(b.tool_use_id)) {
            toolParts.get(b.tool_use_id).status = b.is_error ? 'error' : 'ok';
          }
        }
      }
      const text = userText(content);
      if (!text) continue;
      const imageCount = Array.isArray(content) ? content.filter(b => b?.type === 'image').length : 0;
      assistant = null;
      out.push({
        id: m.uuid || randomUUID(), role: 'user', text,
        images: Array.from({ length: imageCount }, (_, i) => ({ name: '画像' + (i + 1), preview: '' })),
      });
    } else if (m.type === 'assistant' && Array.isArray(content)) {
      for (const b of content) {
        let part = null;
        if (b?.type === 'text' && b.text) part = { type: 'text', text: b.text };
        if (b?.type === 'tool_use') {
          part = { type: 'tool', name: b.name || 'Tool', input: clip(b.input) };
          if (b.id) toolParts.set(b.id, part);
        }
        if (!part) continue;
        if (!assistant) {
          assistant = { id: m.uuid || randomUUID(), role: 'assistant', text: '', parts: [], model: m.message?.model || '', success: true, cost: null };
          out.push(assistant);
        }
        assistant.parts.push(part);
        if (part.type === 'text') assistant.text += (assistant.text ? '\n\n' : '') + part.text;
      }
    }
  }
  return out;
}

async function handleSessionOpen(req, res) {
  assertIdle('実行中は会話を切り替えられません。');
  const data = await readJson(req);
  const id = typeof data.sessionId === 'string' ? data.sessionId.trim() : '';
  if (!UUID.test(id)) return json(res, 400, { error: '会話のIDが正しくありません。' });
  const { getSessionInfo, getSessionMessages } = await sdk();
  const dir = transcriptDir(currentProject);
  const found = await getSessionInfo(id, { dir: currentProject }) || (dir && existsSync(path.join(dir, id + '.jsonl')));
  if (!found) return json(res, 404, { error: 'このフォルダの会話の中に見つかりませんでした。' });
  const messages = await getSessionMessages(id, { dir: currentProject });
  const converted = transcriptToHistory(messages);
  const reopening = id === sessionId;
  history = converted.slice(-HISTORY_LIMIT);
  sessionId = id;
  if (!reopening) totalCost = 0;
  syncedAt = Date.now();
  await saveState();
  json(res, 200, { ...currentState(), truncated: converted.length > HISTORY_LIMIT });
}

// Hand the current session back to the subscription side. The key is removed
// from the environment so that the launched program signs in with the plan.
async function handleHandoff(req, res) {
  assertIdle('実行中は引き継げません。');
  const data = await readJson(req);
  if (process.platform !== 'win32') return json(res, 501, { error: 'この機能はWindowsだけで使えます。表示されたコマンドを手で実行してください。' });
  if (!sessionId || !UUID.test(sessionId)) return json(res, 400, { error: '引き継ぐ会話がありません。' });
  const env = { ...process.env };
  delete env.ANTHROPIC_API_KEY;
  // "claude --desktop" refuses to run without a real console, so both
  // targets are started in a new PowerShell window. The id was checked against
  // the UUID pattern above, so it is safe to put on a command line.
  const commands = {
    terminal: 'claude --resume ' + sessionId,
    desktop: 'claude --desktop --resume ' + sessionId,
  };
  const command = commands[data.target];
  if (!command) return json(res, 400, { error: 'Unknown target.' });
  const child = spawn('cmd.exe', ['/c', 'start', '', 'powershell.exe', '-NoExit', '-Command', command], {
    cwd: currentProject, env, stdio: 'ignore', detached: true, windowsHide: false,
  });
  child.on('error', () => {});
  child.unref();
  json(res, 200, {
    ok: true,
    message: data.target === 'desktop'
      ? '新しいウインドウで claude --desktop を実行しました。結果はそのウインドウに表示されます。'
      : 'ターミナルを開きました。',
  });
}

// ---------------------------------------------------------------- http

async function serve(res, file, mime) {
  try {
    const data = await readFile(file);
    res.writeHead(200, { 'Content-Type': mime, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
    res.end(data);
  } catch { json(res, 404, { error: 'File not found. Run npm install if markdown renderer is missing.' }); }
}

async function requestHandler(req, res) {
  res.setHeader('Content-Security-Policy', "default-src 'none'; connect-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'");
  res.setHeader('Referrer-Policy', 'no-referrer');
  res.setHeader('X-Frame-Options', 'DENY');
  const port = server.address()?.port;
  const host = req.headers.host || '';
  if (host !== '127.0.0.1:' + port && host !== 'localhost:' + port) return json(res, 403, { error: 'Invalid host.' });
  const origin = req.headers.origin;
  if (origin && !['http://127.0.0.1:' + port, 'http://localhost:' + port].includes(origin)) return json(res, 403, { error: 'Invalid origin.' });
  const url = new URL(req.url, 'http://' + host);
  const pathname = url.pathname;
  try {
    if (req.method === 'GET' && pathname === '/') return await serve(res, path.join(WEB, 'index.html'), 'text/html; charset=utf-8');
    if (req.method === 'GET' && pathname === '/app.js') return await serve(res, path.join(WEB, 'app.js'), 'application/javascript; charset=utf-8');
    if (req.method === 'GET' && pathname === '/style.css') return await serve(res, path.join(WEB, 'style.css'), 'text/css; charset=utf-8');
    if (req.method === 'GET' && pathname === '/vendor/markdown-it.min.js') return await serve(res, path.join(HERE, 'node_modules', 'markdown-it', 'dist', 'markdown-it.min.js'), 'application/javascript; charset=utf-8');
    if (req.method === 'GET' && pathname === '/api/state') return json(res, 200, currentState());
    if (req.method === 'GET' && pathname === '/api/events') return handleEvents(req, res, url);
    if (req.method === 'GET' && pathname === '/api/sessions') return await handleSessionList(req, res);
    if (req.method === 'POST' && pathname === '/api/sessions/open') return await handleSessionOpen(req, res);
    if (req.method === 'POST' && pathname === '/api/handoff') return await handleHandoff(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/select') return await handleProjectSelect(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/pick') return await handleProjectPick(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/remove') return await handleProjectRemove(req, res);
    if (req.method === 'POST' && pathname === '/api/run') return await handleRun(req, res);
    if (req.method === 'POST' && pathname === '/api/approval') return await handleApproval(req, res);
    if (req.method === 'POST' && pathname === '/api/settings') return await handleSettings(req, res);
    if (req.method === 'POST' && pathname === '/api/new') return await handleNew(req, res);
    if (req.method === 'POST' && pathname === '/api/stop') return await handleStop(req, res);
    json(res, 404, { error: 'Not found.' });
  } catch (e) {
    if (!e.statusCode) console.error('[Server]', safeError(e));
    if (!res.headersSent) json(res, e.statusCode || 500, { error: safeError(e) });
    else res.end();
  }
}

function openBrowser(url) {
  if (process.env.CHAT_WEB_NO_BROWSER === '1') return;
  try {
    if (process.platform === 'win32') {
      const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', "Start-Process '" + url + "'"], { stdio: 'ignore', windowsHide: true, detached: true });
      child.unref();
    } else if (process.platform === 'darwin') {
      spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
    } else {
      spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
    }
  } catch { console.log('Open this URL in your browser: ' + url); }
}

if (!TEST_MODE) {
  keyFile = KEY_FILE_CANDIDATES.find(candidate => existsSync(candidate)) || '';
  if (!keyFile) {
    console.error('API key file is missing. Save the key to one of:');
    for (const candidate of KEY_FILE_CANDIDATES) console.error('  ' + candidate);
    process.exit(1);
  }
  apiKey = (await readFile(keyFile, 'utf8')).trim();
  if (!apiKey) { console.error('API key file is empty.'); process.exit(1); }
}
await loadState();
const server = http.createServer(requestHandler);
server.listen(Number(process.env.CHAT_WEB_PORT) || 0, HOST, () => {
  const url = 'http://' + HOST + ':' + server.address().port;
  console.log('===========================================');
  console.log('Claude Agent SDK - Local Web Chat');
  console.log('===========================================');
  console.log('Project:', currentProject);
  console.log('Open:', url);
  console.log(TEST_MODE ? 'TEST MODE: no API calls are made.' : 'API key: loaded (not displayed)');
  console.log('To stop: close this terminal or press Ctrl+C.');
  openBrowser(url);
});

for (const sig of ['SIGINT', 'SIGTERM']) {
  process.on(sig, () => { denyOutstanding(); currentAbort?.abort(); server.close(() => process.exit(0)); });
}

web\index.html

<!doctype html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="color-scheme" content="dark" />
  <title>Claude Agent Chat — ローカルワークスペース</title>
  <link rel="stylesheet" href="/style.css" />
  <script defer src="/vendor/markdown-it.min.js"></script>
  <script defer src="/app.js"></script>
</head>
<body>
  <div class="app">
    <aside class="sidebar" id="sidebar">
      <div class="brand"><div class="brand-symbol">✦</div><div><strong>Claude Agent</strong><small>LOCAL WORKSPACE</small></div></div>
      <button class="new-chat" id="newChat"><span class="plus">+</span> 新しい会話</button>
      <div class="side-section-title">作業スペース</div>
      <button class="workspace workspace-button" id="projectSwitch" title="作業フォルダを切り替える">
        <span class="workspace-icon">▣</span>
        <span class="workspace-info"><strong id="projectName">プロジェクト</strong><small id="projectPath">作業フォルダを選択</small></span>
        <span class="workspace-chevron">⌄</span>
      </button>
      <div class="side-section-title">会話の履歴(このフォルダ)</div>
      <div class="session-list" id="sessionList" aria-label="このフォルダの会話の履歴"></div>
      <div class="side-section-title recent-title">最近使ったプロジェクト</div>
      <div class="recent-list" id="recentProjects" aria-label="最近使ったプロジェクト"></div>
      <div class="side-section-title">利用モード</div>
      <div class="mode-info"><span class="info-dot"></span><span id="sideMode">Autoモード</span></div>
      <div class="sidebar-bottom">
        <button class="notify-button" id="notifyButton" type="button">🔔 完了を通知する</button>
        <div class="private-note">⌁ この画面はお使いのPCの中だけで動きます。サーバーは127.0.0.1に限定しています。</div>
        <div class="sidebar-version">Agent SDK · Web UI v4</div>
      </div>
    </aside>

    <main class="main">
      <header class="topbar">
        <button class="menu-toggle" id="menuToggle" aria-label="メニューを開く">☰</button>
        <div class="top-title"><strong>チャット</strong><small id="sessionLabel">新しい会話</small><small class="cost-label" id="costLabel"></small></div>
        <div class="top-actions">
          <details class="handoff hidden" id="handoff">
            <summary>サブスク側で続ける ▾</summary>
            <div class="handoff-menu">
              <button type="button" id="handoffDesktop"><strong>デスクトップアプリで開く</strong><small>claude --desktop --resume を実行します</small></button>
              <button type="button" id="handoffTerminal"><strong>ターミナルで開く</strong><small>このフォルダで claude --resume を実行します</small></button>
              <button type="button" id="handoffCopy"><strong>コマンドをコピー</strong><small>claude --resume と会話のID</small></button>
            </div>
          </details>
          <span class="status"><span class="status-dot" id="statusDot"></span><span id="statusText">準備完了</span></span>
        </div>
      </header>
      <div class="banner hidden" id="banner" role="status"></div>

      <div class="chat-scroll" id="chatScroll">
        <div class="chat-content" id="chatContent"></div>
      </div>

      <div class="composer-area">
        <div class="composer-wrap">
          <div class="composer-toolbar">
            <div class="selector-group"><label for="modelSelect">モデル</label><select id="modelSelect"><option value="claude-fable-5-2">Fable 5.2</option><option value="claude-opus-5-5">Opus 5.5</option><option value="claude-sonnet-5-5">Sonnet 5.5</option><option value="claude-haiku-5-5">Haiku 5.5</option><option value="custom">カスタムID…</option></select></div>
            <div class="selector-group"><label for="modeSelect">権限</label><select id="modeSelect"><option value="auto">Auto</option><option value="default">手動承認</option></select></div>
          </div>
          <div class="composer" id="composer" aria-label="ここに画像をドラッグして添付できます">
            <div class="attachment-list hidden" id="attachmentList" aria-live="polite"></div>
            <textarea id="prompt" rows="2" placeholder="Claudeへの指示を入力…" aria-label="メッセージを入力"></textarea>
            <div class="composer-footer"><span class="helptext"><kbd>Enter</kbd> 送信 <span class="separator">·</span> <kbd>Shift + Enter</kbd> 改行 <span class="separator">·</span> <kbd>Ctrl + V</kbd> 画像貼付</span><div class="send-actions"><input id="imageFileInput" type="file" class="hidden" accept="image/png,image/jpeg,image/gif,image/webp" multiple aria-label="画像ファイルを選択" /><button class="attach-button" id="attachButton" type="button" title="画像を添付" aria-label="画像を添付">📎</button><button class="stop-button hidden" id="stopButton">停止</button><button class="send-button" id="sendButton" aria-label="送信">➤</button></div></div>
          </div>
          <p class="footnote">画像は貼り付け・ドラッグ&ドロップ・📎ボタンに対応(PNG/JPEG/GIF/WebP、最大4枚・各5MB) · タブを閉じても作業は続きます</p>
        </div>
      </div>
    </main>
  </div>

  <div class="modal-backdrop hidden" id="projectModal" role="dialog" aria-modal="true" aria-labelledby="projectModalTitle">
    <div class="modal project-modal">
      <div class="modal-eyebrow">ワークスペース</div>
      <h2 id="projectModalTitle">作業フォルダを選択</h2>
      <p>切り替えたフォルダがClaudeの作業対象になります。プロジェクトごとに会話履歴・モデル・承認モードを保存します。</p>
      <button class="folder-picker-button" id="projectPick">▣ Windowsのフォルダ選択画面を開く</button>
      <div class="path-divider">または絶対パスを入力</div>
      <label for="projectPathInput" class="path-label">フォルダのパス</label>
      <input id="projectPathInput" type="text" placeholder="D:\work\my-project" autocomplete="off" spellcheck="false" />
      <div class="modal-actions"><button class="secondary-button" id="projectCancel">キャンセル</button><button class="primary-button" id="projectApply">このフォルダを開く</button></div>
      <p class="project-hint" id="projectHint">※ 切り替えてもプロジェクトのファイルや過去の会話履歴は削除されません。</p>
    </div>
  </div>
  <div class="modal-backdrop hidden" id="customModal" role="dialog" aria-modal="true" aria-labelledby="customTitle">
    <div class="modal small-modal"><div class="modal-eyebrow">モデル設定</div><h2 id="customTitle">モデルIDを指定</h2><p>Anthropic APIで利用可能なモデルIDを入力してください。</p><input id="customModelInput" type="text" placeholder="claude-..." maxlength="120" /><div class="modal-actions"><button class="secondary-button" id="customCancel">キャンセル</button><button class="primary-button" id="customSave">適用する</button></div></div>
  </div>
  <div class="modal-backdrop hidden" id="approvalModal" role="dialog" aria-modal="true" aria-labelledby="approvalTitle">
    <div class="modal approval-modal"><div class="modal-eyebrow">実行前の確認</div><h2 id="approvalTitle">この操作を許可しますか?</h2><p id="approvalDescription">Claudeが操作の承認を求めています。</p><div class="tool-heading" id="approvalTool"></div><div id="approvalQuestions"></div><details class="approval-details" open><summary>実行内容の詳細</summary><pre id="approvalInput"></pre></details><div class="modal-actions"><button class="secondary-button" id="approvalDeny">拒否する</button><button class="secondary-button hidden" id="approvalAlways" title="このフォルダの .claude/settings.local.json に許可ルールを保存します">今後も許可(このフォルダ)</button><button class="primary-button" id="approvalAllow">今回だけ許可</button></div><p class="approval-tip">Autoで拒否される操作は、手動承認モードに切り替えて再度指示してください。</p></div>
  </div>
  <div class="toast hidden" id="toast" role="status"></div>
</body>
</html>

web\app.js

(() => {
  'use strict';
  const $ = (id) => document.getElementById(id);
  const node = {
    chat: $('chatContent'), scroll: $('chatScroll'),
    prompt: $('prompt'), send: $('sendButton'), stop: $('stopButton'),
    model: $('modelSelect'), mode: $('modeSelect'),
    status: $('statusText'), statusDot: $('statusDot'),
    newChat: $('newChat'), sessionLabel: $('sessionLabel'), costLabel: $('costLabel'),
    customModal: $('customModal'), customInput: $('customModelInput'),
    approvalModal: $('approvalModal'), approvalTool: $('approvalTool'),
    approvalInput: $('approvalInput'), approvalDescription: $('approvalDescription'),
    approvalQuestions: $('approvalQuestions'), approvalAlways: $('approvalAlways'),
    approvalTitle: $('approvalTitle'), toast: $('toast'),
    projectSwitch: $('projectSwitch'), projectModal: $('projectModal'),
    projectPick: $('projectPick'), projectApply: $('projectApply'),
    projectCancel: $('projectCancel'), projectPathInput: $('projectPathInput'),
    recentProjects: $('recentProjects'), sessionList: $('sessionList'),
    composer: $('composer'), attachmentList: $('attachmentList'),
    attach: $('attachButton'), imageInput: $('imageFileInput'),
    handoff: $('handoff'), banner: $('banner'), notify: $('notifyButton'),
  };

  const md = typeof window.markdownit === 'function'
    ? window.markdownit({ html: false, linkify: true, breaks: true, typographer: false })
    : null;
  if (md) {
    const oldLinkOpen = md.renderer.rules.link_open || ((tokens, i, options, env, self) => self.renderToken(tokens, i, options));
    md.renderer.rules.link_open = (tokens, i, options, env, self) => {
      tokens[i].attrSet('target', '_blank');
      tokens[i].attrSet('rel', 'noopener noreferrer');
      return oldLinkOpen(tokens, i, options, env, self);
    };
  }
  let running = false;
  let currentModel = 'claude-fable-5-2';
  let currentMode = 'auto';
  let currentSessionId = null;
  let approval = null;
  let toastTimer = null;
  let switching = false;
  let activeProjectPath = '';
  let baseTitle = 'Claude Agent Chat';
  let live = null; // the assistant message that is being written right now
  const projectDrafts = new Map();
  const MAX_IMAGES = 4;
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
  const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
  const BIG_SESSION_BYTES = 3 * 1024 * 1024;
  let attachments = [];
  let readingImages = false;

  async function post(url, body) {
    const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    const out = await r.json();
    if (!r.ok) throw new Error(out.error || 'HTTP ' + r.status);
    return out;
  }
  function toast(message) {
    node.toast.textContent = message;
    node.toast.classList.remove('hidden');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => node.toast.classList.add('hidden'), 3300);
  }
  function showBanner(message) {
    node.banner.textContent = message;
    node.banner.classList.toggle('hidden', !message);
  }
  function setStatus(s, working = false) {
    node.status.textContent = s;
    node.statusDot.classList.toggle('working', working);
  }
  function setRunning(value) {
    running = value;
    // Sending stays possible during a run: the message goes to the running agent.
    node.prompt.placeholder = value
      ? '作業中でも送れます(今のツールの実行が終わったあとに Claude へ届きます)'
      : 'Claudeへの指示を入力…';
    node.stop.classList.toggle('hidden', !value);
    node.model.disabled = value;
    node.mode.disabled = value;
    node.newChat.disabled = value;
    node.projectSwitch.disabled = value;
    for (const button of document.querySelectorAll('#recentProjects button, #sessionList button, #handoff button')) button.disabled = value;
    setStatus(value ? '作業中…' : '準備完了', value);
  }
  function autoScroll(force = false) {
    const el = node.scroll;
    if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 300) {
      requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
    }
  }
  function setModelUI(id) {
    currentModel = id;
    for (const e of [...node.model.options]) {
      if (e.dataset.userModel === 'yes') e.remove();
    }
    const predefined = [...node.model.options].some(o => o.value === id);
    if (!predefined) {
      const option = new Option(id, id);
      option.dataset.userModel = 'yes';
      node.model.add(option, node.model.querySelector('option[value="custom"]'));
    }
    node.model.value = id;
  }
  function setModeUI(mode) {
    currentMode = mode;
    node.mode.value = mode;
    $('sideMode').textContent = mode === 'auto' ? 'Autoモード' : '手動承認モード';
  }
  function setSession(id, cost) {
    currentSessionId = id || null;
    node.handoff.classList.toggle('hidden', !currentSessionId);
    node.sessionLabel.textContent = currentSessionId ? '会話を継続中' : '新しい会話';
    node.costLabel.textContent = Number(cost) > 0 ? 'この会話の費用(参考) $' + Number(cost).toFixed(Number(cost) < 0.1 ? 4 : 2) : '';
  }
  function el(tag, className, text) {
    const e = document.createElement(tag);
    if (className) e.className = className;
    if (text !== undefined) e.textContent = text;
    return e;
  }
  function clearMessages() {
    node.chat.replaceChildren();
    const welcome = el('section', 'welcome');
    welcome.append(el('div', 'welcome-icon', '✦'), el('h1', '', '何から始めましょうか?'),
      el('p', '', 'フォルダの調査、設計の相談、ファイルの編集まで。左の「会話の履歴」から、前の会話の続きもできます。'));
    const suggestions = el('div', 'suggestions');
    for (const [label, example] of [
      ['フォルダの構成を確認', 'このフォルダの現在の構成を確認して、概要を説明してください。'],
      ['前回の続きを確認', 'この会話でここまでにやったことと、残っている作業を整理してください。'],
    ]) {
      const b = el('button', 'suggestion', label);
      b.addEventListener('click', () => { node.prompt.value = example; resizeInput(); node.prompt.focus(); });
      suggestions.append(b);
    }
    welcome.append(suggestions);
    node.chat.append(welcome);
  }

  // ------------------------------------------------------------ messages

  // An assistant message is a "flow": text, tool calls and notices are
  // appended in the order they happen, so the newest thing is always at the
  // bottom and the final answer comes last.
  function createMessage(role, selectedModel) {
    const w = node.chat.querySelector('.welcome');
    if (w) w.remove();
    const wrap = el('article', 'message ' + (role === 'user' ? 'message-user' : 'message-ai'));
    const avatar = el('div', 'avatar ' + (role === 'user' ? 'avatar-user' : 'avatar-ai'), role === 'user' ? '人' : '✦');
    const body = el('div', 'message-body');
    const header = el('div', 'message-header');
    header.append(el('strong', '', role === 'user' ? 'あなた' : 'Claude'), el('small', '', role === 'user' ? '' : (selectedModel || '')));
    const flow = el('div', role === 'user' ? 'message-text user-text' : 'flow');
    const actions = el('div', 'message-actions');
    const copy = el('button', 'copy-button', 'コピー');
    actions.append(copy);
    body.append(header, flow, actions);
    wrap.append(avatar, body);
    node.chat.append(wrap);
    const message = { wrap, flow, header, copy, model: selectedModel, text: '', segment: null, segmentText: '', timer: null, tools: new Map() };
    copy.addEventListener('click', async () => {
      try { await navigator.clipboard.writeText(message.text); toast('コピーしました'); }
      catch { toast('コピーできませんでした'); }
    });
    return message;
  }
  function renderMarkdown(target, text) {
    if (md) target.innerHTML = md.render(text || '');
    else target.textContent = text || '';
  }
  function flushText(message) {
    if (message.timer) { clearTimeout(message.timer); message.timer = null; }
    if (message.segment) renderMarkdown(message.segment, message.segmentText);
  }
  function closeText(message) {
    flushText(message);
    if (message.segment && !message.segmentText.trim()) message.segment.remove();
    message.segment = null;
    message.segmentText = '';
  }
  function place(message, element) {
    // Keep the "working" line as the last child while a run is in progress.
    if (message.working && message.working.parentNode === message.flow) message.flow.insertBefore(element, message.working);
    else message.flow.append(element);
  }
  function flowText(message, delta, immediate) {
    if (!delta) return;
    if (!message.segment) {
      if (!delta.trim()) return;
      message.segment = el('div', 'message-text markdown');
      place(message, message.segment);
    }
    message.segmentText += delta;
    message.text += delta;
    if (immediate) return flushText(message);
    if (!message.timer) message.timer = setTimeout(() => { message.timer = null; flushText(message); autoScroll(); }, 65);
  }
  function flowTool(message, part) {
    closeText(message);
    const details = el('details', 'tool-chip');
    const summary = el('summary');
    const mark = el('span', 'tool-mark', '◈');
    summary.append(mark, document.createTextNode(' ' + (part.sub ? '(サブエージェント) ' : '') + (part.name || 'Tool')));
    let input = part.input;
    if (typeof input !== 'string') {
      try { input = JSON.stringify(input || {}, null, 2); } catch { input = String(input); }
      if (input.length > 4000) input = input.slice(0, 4000) + '\n…(以下省略)';
    }
    details.append(summary, el('pre', '', input));
    place(message, details);
    const chip = { details, mark };
    if (part.id) message.tools.set(part.id, chip);
    if (part.status) markTool(chip, part.status === 'error');
    return chip;
  }
  function markTool(chip, isError) {
    chip.mark.textContent = isError ? '✕' : '✓';
    chip.details.classList.add(isError ? 'tool-error' : 'tool-ok');
  }
  function flowNotice(message, text) {
    closeText(message);
    place(message, el('div', 'notice', text));
  }
  function flowResult(message, event) {
    closeText(message);
    const line = el('div', 'result-line');
    // A result that is not the last one: Claude goes on to a message sent during the run.
    if (event.success && event.final === false) line.append(el('span', '', '↓ 途中で送られた指示に、続けて対応します'));
    else line.append(el('span', event.success ? 'success' : 'failure', event.success ? '✓ 完了' : '⚠ 処理が正常終了していません'));
    if (Number.isFinite(Number(event.cost)) && event.cost !== null) {
      line.append(el('span', '', 'この回の費用 $' + Number(event.cost).toFixed(4) + '(SDKの報告値・参考)'));
    }
    line.append(el('span', '', new Date().toLocaleTimeString('ja-JP', { hour: '2-digit', minute: '2-digit' }) + ' 終了'));
    place(message, line);
    if (event.denials?.length) flowNotice(message, event.denials.length + '件の操作が拒否されました。Autoモードの場合は手動承認に切り替え、再度依頼してください。');
    if (event.errors?.length) flowNotice(message, event.errors.join('\n'));
  }
  function renderMessageImages(container, images) {
    if (!images?.length) return;
    const grid = el('div', 'message-image-grid');
    for (const image of images) {
      if (image.preview && /^data:image\/(jpeg|png|webp);base64,/.test(image.preview)) {
        const img = document.createElement('img');
        img.src = image.preview;
        img.alt = image.name || '添付画像';
        img.title = image.name || '';
        grid.append(img);
      } else {
        grid.append(el('span', 'message-image-fallback', '🖼 ' + (image.name || '添付画像')));
      }
    }
    container.append(grid);
  }
  function addUser(text, images, duringRun) {
    const m = createMessage('user');
    if (duringRun) m.header.querySelector('small').textContent = '作業中に追加';
    m.flow.textContent = text;
    m.text = text;
    renderMessageImages(m.flow, images);
    return m;
  }
  // A message sent during a run: end the assistant message shown so far, show
  // the user message, and continue the run in a new assistant message below it.
  function splitLive(ev) {
    const old = live;
    closeText(old);
    const working = old.working;
    old.working = null;
    if (working) working.remove();
    if (!old.flow.childElementCount) old.wrap.remove();
    addUser(ev.text || '', ev.images, true);
    const next = createMessage('assistant', old.model);
    next.tools = old.tools; // results of tools started above still find their chip
    if (working) { next.working = working; next.flow.append(working); }
    live = next;
    autoScroll(true);
  }
  function addPast(entry) {
    if (entry.role === 'user') return addUser(entry.text, entry.images);
    const m = createMessage('assistant', entry.model);
    if (Array.isArray(entry.parts) && entry.parts.length) {
      for (const part of entry.parts) {
        if (part.type === 'text') { flowText(m, part.text, true); closeText(m); }
        else if (part.type === 'tool') flowTool(m, part);
        else if (part.type === 'notice') flowNotice(m, part.text || '');
      }
    } else {
      flowText(m, entry.text, true);
      closeText(m);
    }
    m.text = entry.text || m.text;
    if (entry.cost !== null && entry.cost !== undefined && Number.isFinite(Number(entry.cost))) {
      const line = el('div', 'result-line');
      line.append(el('span', entry.success === false ? 'failure' : 'success', entry.success === false ? '⚠ 正常終了していません' : '✓ 完了'),
        el('span', '', 'この回の費用 $' + Number(entry.cost).toFixed(4) + '(参考)'));
      m.flow.append(line);
    }
    return m;
  }

  // ------------------------------------------------------------ attachments

  function renderAttachments() {
    node.attachmentList.replaceChildren();
    node.attachmentList.classList.toggle('hidden', !attachments.length);
    attachments.forEach((attachment, index) => {
      const item = el('div', 'attachment-item');
      const img = document.createElement('img');
      img.src = attachment.preview || 'data:' + attachment.mimeType + ';base64,' + attachment.data;
      img.alt = attachment.name;
      const remove = el('button', 'attachment-remove', '×');
      remove.type = 'button';
      remove.title = attachment.name + ' を削除';
      remove.setAttribute('aria-label', remove.title);
      remove.addEventListener('click', () => { attachments.splice(index, 1); renderAttachments(); });
      item.append(img, el('span', 'attachment-name', attachment.name), remove);
      node.attachmentList.append(item);
    });
  }
  function readDataURL(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result));
      reader.onerror = () => reject(new Error('画像を読み取れませんでした。'));
      reader.readAsDataURL(file);
    });
  }
  function imagePreview(file) {
    return new Promise(resolve => {
      const src = URL.createObjectURL(file);
      const img = new Image();
      const cleanup = () => URL.revokeObjectURL(src);
      img.onload = () => {
        try {
          const ratio = Math.min(1, 240 / Math.max(img.naturalWidth, img.naturalHeight));
          const canvas = document.createElement('canvas');
          canvas.width = Math.max(1, Math.round(img.naturalWidth * ratio));
          canvas.height = Math.max(1, Math.round(img.naturalHeight * ratio));
          const ctx = canvas.getContext('2d');
          ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL('image/jpeg', 0.72));
        } catch { resolve(''); }
        cleanup();
      };
      img.onerror = () => { cleanup(); resolve(''); };
      img.src = src;
    });
  }
  async function addImages(files) {
    if (switching || readingImages) return;
    const images = [...files];
    if (!images.length) return;
    if (attachments.length + images.length > MAX_IMAGES) return toast('画像は最大' + MAX_IMAGES + '枚です。');
    readingImages = true;
    node.attach.disabled = true;
    try {
      for (const file of images) {
        if (!IMAGE_TYPES.has(file.type)) { toast('PNG・JPEG・GIF・WebPだけ添付できます。'); continue; }
        if (!file.size || file.size > MAX_IMAGE_BYTES) { toast((file.name || '画像') + ' は5MB以下にしてください。'); continue; }
        const url = await readDataURL(file);
        const data = url.slice(url.indexOf(',') + 1);
        const preview = await imagePreview(file);
        attachments.push({ name: file.name || '貼り付け画像', mimeType: file.type, data, preview });
      }
      renderAttachments();
      node.prompt.focus();
    } catch (e) { toast('画像の添付に失敗: ' + e.message); }
    finally { readingImages = false; node.attach.disabled = switching; }
  }
  function resizeInput() {
    node.prompt.style.height = 'auto';
    node.prompt.style.height = Math.min(Math.max(node.prompt.scrollHeight, 55), 230) + 'px';
  }

  // ------------------------------------------------------------ approvals

  function showApproval(ev) {
    approval = ev;
    const isQuestion = ev.toolName === 'AskUserQuestion';
    node.approvalTitle.textContent = isQuestion ? 'Claudeからの質問' : 'この操作を許可しますか?';
    node.approvalTool.textContent = '◈ ' + ev.toolName;
    node.approvalTool.classList.toggle('hidden', isQuestion);
    node.approvalDescription.textContent = isQuestion
      ? '選択肢を選ぶか、自由に入力して回答してください。'
      : (ev.reason || '実行内容を確認し、許可または拒否を選択してください。');
    node.approvalInput.textContent = JSON.stringify(ev.input || {}, null, 2);
    node.approvalInput.parentElement.open = !isQuestion;
    node.approvalAlways.classList.toggle('hidden', !ev.canRemember);
    $('approvalAllow').textContent = isQuestion ? '回答する' : '今回だけ許可';
    $('approvalDeny').textContent = isQuestion ? '答えない' : '拒否する';
    node.approvalQuestions.replaceChildren();
    if (Array.isArray(ev.questions)) {
      for (const q of ev.questions) {
        const block = el('div', 'question-block');
        block.dataset.question = q.question;
        block.dataset.multi = q.multiSelect ? 'yes' : 'no';
        block.append(el('div', 'question-label', q.question));
        const options = el('div', 'question-options');
        for (const o of (Array.isArray(q.options) ? q.options : [])) {
          const b = el('button', 'question-option');
          b.type = 'button';
          b.dataset.label = o.label;
          b.append(el('strong', '', o.label));
          if (o.description) b.append(el('small', '', o.description));
          b.addEventListener('click', () => {
            if (!q.multiSelect) for (const other of options.children) if (other !== b) other.classList.remove('selected');
            b.classList.toggle('selected');
          });
          options.append(b);
        }
        const input = el('input', 'question-answer');
        input.type = 'text';
        input.placeholder = 'その他(自由に入力)';
        block.append(options, input);
        node.approvalQuestions.append(block);
      }
    }
    node.approvalModal.classList.remove('hidden');
    if (document.hidden) document.title = '● 確認待ち — ' + baseTitle;
  }
  function hideApproval(requestId) {
    if (approval && (!requestId || approval.requestId === requestId)) {
      approval = null;
      node.approvalModal.classList.add('hidden');
    }
  }
  async function submitApproval(decision) {
    if (!approval) return;
    const ev = approval;
    const answers = {};
    if (decision !== 'deny' && Array.isArray(ev.questions)) {
      for (const block of node.approvalQuestions.querySelectorAll('.question-block')) {
        const typed = block.querySelector('input').value.trim();
        const labels = [...block.querySelectorAll('.question-option.selected')].map(b => b.dataset.label);
        const answer = typed ? (labels.length && block.dataset.multi === 'yes' ? labels.concat(typed).join(', ') : typed) : labels.join(', ');
        if (!answer) return toast('質問に回答してください');
        answers[block.dataset.question] = answer;
      }
    }
    try {
      await post('/api/approval', { requestId: ev.requestId, decision, answers });
      hideApproval(ev.requestId);
    } catch (e) { toast('承認エラー: ' + e.message); hideApproval(ev.requestId); }
  }

  // ------------------------------------------------------------ a run

  function startLive(selectedModel) {
    const message = createMessage('assistant', selectedModel);
    message.working = el('div', 'thinking');
    message.working.append(el('span', 'spinner'), el('span', 'working-text', 'Claudeが考えています…'));
    message.flow.append(message.working);
    live = message;
    setRunning(true);
    autoScroll(true);
    return message;
  }
  function setWorking(text) {
    if (live?.working) live.working.querySelector('.working-text').textContent = text;
  }
  function handleEvent(ev) {
    if (!live) return;
    if (ev.type === 'text') { flowText(live, ev.text || ''); setWorking('回答を書いています…'); }
    else if (ev.type === 'tool_start') setWorking((ev.name || 'ツール') + ' を準備しています…');
    else if (ev.type === 'tool') { flowTool(live, ev); setWorking((ev.name || 'ツール') + ' を実行しています…'); }
    else if (ev.type === 'tool_result') {
      const chip = live.tools.get(ev.id);
      if (chip) markTool(chip, ev.isError);
      setWorking('Claudeが考えています…');
    }
    else if (ev.type === 'approval') { showApproval(ev); setWorking('あなたの確認を待っています…'); }
    else if (ev.type === 'approval_closed') { hideApproval(ev.requestId); setWorking('Claudeが考えています…'); }
    else if (ev.type === 'user_message') splitLive(ev);
    else if (ev.type === 'notice') flowNotice(live, ev.message || '');
    else if (ev.type === 'error') flowNotice(live, 'エラー: ' + ev.message);
    else if (ev.type === 'result') flowResult(live, ev);
    autoScroll();
  }
  function finishLive(doneEvent) {
    const message = live;
    live = null;
    if (message) {
      closeText(message);
      if (message.working) message.working.remove();
      message.working = null;
      if (!message.flow.childElementCount) message.flow.append(el('div', 'notice', '回答がありませんでした。'));
      message.wrap.classList.add('just-finished');
    }
    hideApproval();
    setRunning(false);
    if (doneEvent) setSession(doneEvent.sessionId || currentSessionId, doneEvent.totalCost);
    autoScroll(true);
    node.prompt.focus();
    if (document.hidden) {
      document.title = '✓ 完了 — ' + baseTitle;
      if ('Notification' in window && Notification.permission === 'granted') {
        try { new Notification('Claude Agent: 作業が終わりました', { body: baseTitle }); } catch { /* ignore */ }
      }
    }
    loadSessions();
  }
  // Read the events of a run. If the connection drops, reconnect and continue
  // from the number of events already shown.
  async function attachRun(runId) {
    let seen = 0;
    let failures = 0;
    while (true) {
      let doneEvent = null;
      try {
        const response = await fetch('/api/events?run=' + encodeURIComponent(runId) + '&after=' + seen);
        if (response.status === 404) { await refreshState(); return; }
        if (!response.ok) throw new Error('HTTP ' + response.status);
        failures = 0;
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let unparsed = '';
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          unparsed += decoder.decode(value, { stream: true });
          const lines = unparsed.split('\n');
          unparsed = lines.pop();
          for (const line of lines) {
            if (!line.trim()) continue;
            let ev;
            try { ev = JSON.parse(line); } catch { continue; }
            seen += 1;
            if (ev.type === 'done') doneEvent = ev;
            else handleEvent(ev);
          }
        }
      } catch (e) {
        failures += 1;
        if (failures > 20) {
          if (live) flowNotice(live, 'サーバーに接続できません: ' + e.message);
          return finishLive(null);
        }
      }
      if (doneEvent) return finishLive(doneEvent);
      setWorking('再接続しています…');
      await new Promise(r => setTimeout(r, 1000));
    }
  }
  let sending = false;
  async function send() {
    if (switching || sending) return;
    if (readingImages) return toast('画像の読み込みが終わってから送信してください。');
    const prompt = node.prompt.value.trim();
    if (!prompt && !attachments.length) return;
    const images = attachments.slice();
    const submittedText = prompt || '添付画像を確認してください。';
    if (running) {
      // Hand the message to the running agent. It appears in the chat when the
      // server reports it back through the event stream.
      sending = true;
      try {
        for (let attempt = 0; running && attempt < 20; attempt += 1) {
          const r = await fetch('/api/run', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt: submittedText, images }),
          });
          const out = await r.json();
          if (r.ok) {
            node.prompt.value = ''; attachments = []; renderAttachments(); resizeInput();
            return;
          }
          if (!out.retry) return toast('送信できませんでした: ' + (out.error || 'HTTP ' + r.status));
          // The run is just ending: wait, then send it as a normal message.
          await new Promise(resolve => setTimeout(resolve, 300));
        }
      } catch (e) { return toast('送信できませんでした: ' + e.message); }
      finally { sending = false; }
      if (running) return toast('送信できませんでした。少し待ってからもう一度送ってください。');
    }
    setRunning(true);
    let started;
    try {
      started = await post('/api/run', { prompt: submittedText, images, model: currentModel, mode: currentMode });
    } catch (e) {
      setRunning(false);
      return toast('送信できませんでした: ' + e.message);
    }
    node.prompt.value = ''; attachments = []; renderAttachments(); resizeInput();
    addUser(submittedText, images);
    startLive(currentModel);
    attachRun(started.runId);
  }

  // ------------------------------------------------------------ sessions

  function when(ms) {
    const d = new Date(ms);
    const today = new Date();
    const time = d.toLocaleTimeString('ja-JP', { hour: '2-digit', minute: '2-digit' });
    if (d.toDateString() === today.toDateString()) return '今日 ' + time;
    return (d.getMonth() + 1) + '/' + d.getDate() + ' ' + time;
  }
  async function openSession(session, quiet) {
    if (running || switching) return toast('処理中は切り替えできません');
    if (!quiet && !session.current && session.fileSize > BIG_SESSION_BYTES &&
        !confirm('長い会話です。APIクレジットで続けると、最初の1回は会話全体を読み直すぶんの費用がかかります。開きますか?')) return;
    try {
      const state = await post('/api/sessions/open', { sessionId: session.id });
      applyState(state);
      if (!quiet) toast(state.truncated ? '会話を開きました(画面には新しいほうから一部だけ表示)' : '会話を開きました');
      $('sidebar').classList.remove('open');
      loadSessions();
    } catch (e) { toast('開けませんでした: ' + e.message); }
  }
  async function loadSessions() {
    let data;
    try {
      const r = await fetch('/api/sessions');
      if (!r.ok) throw new Error('HTTP ' + r.status);
      data = await r.json();
    } catch { return; }
    node.sessionList.replaceChildren();
    if (!data.sessions.length) node.sessionList.append(el('div', 'session-empty', 'このフォルダの会話はまだありません'));
    for (const s of data.sessions) {
      const b = el('button', 'session-item' + (s.current ? ' active' : ''));
      b.type = 'button';
      b.disabled = running || switching;
      b.title = s.title + '\n' + s.id + (s.current ? '\n(クリックで読み込み直す)' : '');
      b.append(el('strong', '', s.title), el('small', '', when(s.lastModified) + (s.current ? ' · 表示中' : '')));
      b.addEventListener('click', () => openSession(s, false));
      node.sessionList.append(b);
    }
    // The desktop app or the terminal continued this session: show their part too.
    const current = data.sessions.find(s => s.current);
    if (current?.changedOutside && !running) {
      await openSession(current, true);
      toast('ほかのアプリで進んだ分を読み込みました');
    }
  }
  async function handoff(target) {
    if (!currentSessionId) return;
    if (running) return toast('作業が終わってから引き継いでください');
    node.handoff.open = false;
    if (target === 'copy') {
      try { await navigator.clipboard.writeText('claude --resume ' + currentSessionId); toast('コマンドをコピーしました(このフォルダのターミナルで実行)'); }
      catch { toast('コピーできませんでした'); }
      return;
    }
    try {
      const out = await post('/api/handoff', { target });
      toast(out.message || '引き継ぎました');
      showBanner('この会話をサブスク側に引き継ぎました。向こうで作業している間は、こちらから同じ会話に指示を出さないでください(同時に書き込むと会話が欠けることがあります)。戻るときは、左の一覧からこの会話を選び直します。');
    } catch (e) { toast(e.message); }
  }

  // ------------------------------------------------------------ projects

  async function saveSettings() {
    try { await post('/api/settings', { model: currentModel, mode: currentMode }); }
    catch (e) { toast('設定保存エラー: ' + e.message); }
  }
  function renderProjects(projects) {
    node.recentProjects.replaceChildren();
    for (const project of projects || []) {
      const row = el('div', 'recent-row' + (project.active ? ' active' : ''));
      const open = el('button', 'recent-project');
      open.type = 'button';
      open.disabled = running || switching;
      open.title = project.path;
      open.append(el('strong', '', project.name), el('small', '', project.path));
      open.addEventListener('click', () => switchProject(project.path));
      row.append(open);
      if (!project.active) {
        const remove = el('button', 'recent-remove', '×');
        remove.type = 'button';
        remove.title = '最近使った一覧から外す(ファイル・履歴は削除しません)';
        remove.setAttribute('aria-label', project.name + ' を一覧から外す');
        remove.disabled = running || switching;
        remove.addEventListener('click', async (ev) => {
          ev.stopPropagation();
          try { renderProjects((await post('/api/projects/remove', { path: project.path })).recentProjects); }
          catch (e) { toast(e.message); }
        });
        row.append(remove);
      }
      node.recentProjects.append(row);
    }
  }
  function applyState(data) {
    if (activeProjectPath && activeProjectPath !== data.projectPath) {
      projectDrafts.set(activeProjectPath, { text: node.prompt.value, attachments: attachments.slice() });
    }
    const changedProject = activeProjectPath !== data.projectPath;
    activeProjectPath = data.projectPath;
    setModelUI(data.model || 'claude-fable-5-2');
    setModeUI(data.mode || 'auto');
    $('projectName').textContent = data.projectName || 'プロジェクト';
    $('projectPath').textContent = data.projectPath || '';
    node.projectSwitch.title = data.projectPath || '作業フォルダを切り替える';
    setSession(data.sessionId, data.totalCost);
    $('handoffDesktop').classList.toggle('hidden', !data.handoff);
    $('handoffTerminal').classList.toggle('hidden', !data.handoff);
    renderProjects(data.recentProjects);
    showBanner('');
    clearMessages();
    for (const entry of data.history || []) addPast(entry);
    if (data.history?.length) autoScroll(true);
    if (changedProject) {
      const draft = projectDrafts.get(activeProjectPath);
      node.prompt.value = draft?.text || '';
      attachments = draft?.attachments?.slice() || [];
      renderAttachments(); resizeInput();
    }
    baseTitle = (data.projectName || 'プロジェクト') + ' — Claude Agent Chat';
    document.title = baseTitle;
    node.projectPick.classList.toggle('hidden', !data.nativePicker);
  }
  async function refreshState() {
    const r = await fetch('/api/state');
    if (!r.ok) throw new Error('HTTP ' + r.status);
    const data = await r.json();
    live = null;
    setRunning(false);
    applyState(data);
    if (!data.apiVersion) {
      showBanner('画面は新しい版ですが、サーバーが古い版のまま動いています。起動した黒い画面を閉じて、web_chat.bat を開き直してください。');
      node.send.disabled = true;
      return data;
    }
    // A run is still going (for example the page was reloaded): show it again from its first event.
    if (data.runId) {
      startLive(data.model);
      attachRun(data.runId);
    }
    return data;
  }

  function closeProjectModal() { node.projectModal.classList.add('hidden'); }
  function openProjectModal() {
    if (running || switching) return toast('処理中は切り替えできません');
    node.projectPathInput.value = activeProjectPath;
    node.projectModal.classList.remove('hidden');
    node.projectPathInput.focus();
    node.projectPathInput.select();
  }
  function setSwitching(value, message = 'フォルダを切り替えています…') {
    switching = value;
    node.projectApply.disabled = value;
    node.projectPick.disabled = value;
    node.projectCancel.disabled = value;
    node.projectPathInput.disabled = value;
    node.projectSwitch.disabled = value || running;
    for (const button of document.querySelectorAll('#recentProjects button, #sessionList button')) button.disabled = value || running;
    if (value) setStatus(message, true);
    else setStatus('準備完了', false);
  }
  async function switchProject(folderPath) {
    if (running || switching) return toast('処理中は切り替えできません');
    setSwitching(true);
    try {
      const state = await post('/api/projects/select', { path: folderPath });
      applyState(state);
      closeProjectModal();
      $('sidebar').classList.remove('open');
      toast('「' + state.projectName + '」に切り替えました');
      node.prompt.focus();
    } catch (e) { toast('切り替え失敗: ' + e.message); }
    finally { setSwitching(false); loadSessions(); }
  }

  async function init() {
    clearMessages();
    try {
      const data = await refreshState();
      if (!md) toast('Markdown描画ライブラリがありません。npm installを確認してください。');
      if (data.apiVersion) loadSessions();
    } catch (e) { toast('サーバーに接続できません: ' + e.message); }
    node.prompt.focus();
  }

  node.projectSwitch.addEventListener('click', openProjectModal);
  node.projectCancel.addEventListener('click', closeProjectModal);
  node.projectApply.addEventListener('click', () => switchProject(node.projectPathInput.value.trim()));
  node.projectPathInput.addEventListener('keydown', e => {
    if (e.key === 'Enter') { e.preventDefault(); switchProject(node.projectPathInput.value.trim()); }
  });
  node.projectPick.addEventListener('click', async () => {
    if (running || switching) return;
    setSwitching(true, 'Windowsのフォルダ選択画面を確認してください…');
    try {
      const state = await post('/api/projects/pick', {});
      if (!state.cancelled) {
        applyState(state);
        closeProjectModal();
        toast('「' + state.projectName + '」に切り替えました');
      }
    } catch (e) { toast('フォルダ選択に失敗: ' + e.message); }
    finally { setSwitching(false); loadSessions(); }
  });
  node.attach.addEventListener('click', () => node.imageInput.click());
  node.imageInput.addEventListener('change', async () => {
    await addImages(node.imageInput.files || []);
    node.imageInput.value = '';
  });
  document.addEventListener('paste', async event => {
    if (document.querySelector('.modal-backdrop:not(.hidden)')) return;
    const files = [...(event.clipboardData?.items || [])]
      .filter(item => item.kind === 'file' && item.type.startsWith('image/'))
      .map(item => item.getAsFile()).filter(Boolean);
    if (files.length) { event.preventDefault(); await addImages(files); }
  });
  document.addEventListener('dragover', event => {
    if (!event.dataTransfer?.types?.includes('Files')) return;
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
    node.composer.classList.add('drag-active');
  });
  document.addEventListener('dragleave', event => {
    if (!event.relatedTarget || !document.documentElement.contains(event.relatedTarget)) {
      node.composer.classList.remove('drag-active');
    }
  });
  document.addEventListener('drop', async event => {
    if (!event.dataTransfer?.files?.length) return;
    event.preventDefault(); node.composer.classList.remove('drag-active');
    await addImages(event.dataTransfer.files);
  });
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) document.title = baseTitle;
  });
  node.prompt.addEventListener('input', resizeInput);
  node.prompt.addEventListener('keydown', (ev) => {
    if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing && !ev.ctrlKey) {
      ev.preventDefault(); send();
    }
  });
  node.send.addEventListener('click', send);
  node.stop.addEventListener('click', async () => {
    try { await post('/api/stop', {}); toast('停止を要求しました'); }
    catch (e) { toast(e.message); }
  });
  node.newChat.addEventListener('click', async () => {
    if (running) return;
    try {
      applyState(await post('/api/new', {}));
      toast('新しい会話を開始しました(前の会話は左の履歴に残ります)');
      loadSessions();
    } catch (e) { toast(e.message); }
  });
  node.model.addEventListener('change', async () => {
    if (node.model.value === 'custom') {
      node.customInput.value = currentModel;
      node.customModal.classList.remove('hidden');
      node.customInput.focus(); node.customInput.select(); return;
    }
    currentModel = node.model.value;
    await saveSettings();
  });
  node.mode.addEventListener('change', async () => {
    setModeUI(node.mode.value);
    await saveSettings();
  });
  node.notify.addEventListener('click', async () => {
    if (!('Notification' in window)) return toast('このブラウザは通知に対応していません');
    const result = await Notification.requestPermission();
    toast(result === 'granted' ? '別のタブを見ているときに、完了を通知します' : '通知は許可されませんでした');
  });
  $('customCancel').addEventListener('click', () => { node.customModal.classList.add('hidden'); setModelUI(currentModel); });
  $('customSave').addEventListener('click', async () => {
    const value = node.customInput.value.trim();
    if (!value) return toast('モデルIDを入力してください');
    setModelUI(value); node.customModal.classList.add('hidden'); await saveSettings();
  });
  node.customInput.addEventListener('keydown', ev => { if (ev.key === 'Enter') $('customSave').click(); });
  $('approvalAllow').addEventListener('click', () => submitApproval('allow'));
  node.approvalAlways.addEventListener('click', () => submitApproval('always'));
  $('approvalDeny').addEventListener('click', () => submitApproval('deny'));
  $('handoffDesktop').addEventListener('click', () => handoff('desktop'));
  $('handoffTerminal').addEventListener('click', () => handoff('terminal'));
  $('handoffCopy').addEventListener('click', () => handoff('copy'));
  $('menuToggle').addEventListener('click', () => $('sidebar').classList.toggle('open'));
  init();
})();

web\style.css

:root{color-scheme:dark;font-family:Inter,"Segoe UI","Yu Gothic UI","Meiryo",sans-serif;font-size:14px;font-weight:400;line-height:1.6;background:#101318;color:#e7ebf0}
*{box-sizing:border-box}
html,body{margin:0;width:100%;height:100%}
button,input,select,textarea{font:inherit}
button{cursor:pointer}
button:disabled{cursor:not-allowed;opacity:.46}
.hidden{display:none!important}
.app{display:flex;width:100%;height:100dvh;overflow:hidden}
.sidebar{background:#15191f;border-right:1px solid #252b34;width:258px;flex:0 0 258px;display:flex;flex-direction:column;padding:25px 16px}
.brand{display:flex;align-items:center;gap:12px;margin:0 7px 31px}
.brand-symbol{width:38px;height:38px;display:grid;place-items:center;background:#244e52;border:1px solid #386e71;border-radius:11px;color:#7ae4d3;font-size:24px}
.brand strong{font-size:16px;letter-spacing:-.3px}
.brand small{display:block;color:#83919f;font-size:10px;letter-spacing:1.5px;margin-top:-2px}
.new-chat{display:flex;align-items:center;justify-content:flex-start;gap:9px;width:100%;padding:12px;border-radius:10px;border:1px solid #373f4a;background:#20262e;color:#e8eef3;font-weight:650;text-align:left}
.new-chat:hover{background:#2b333d}
.plus{font-size:19px;font-weight:400}
.side-section-title{color:#788595;font-size:11px;font-weight:700;letter-spacing:.07em;margin:30px 8px 11px}
.workspace{padding:11px 9px;display:flex;align-items:center;gap:12px;background:#1c222a;border-radius:10px}
.workspace-icon{color:#6fc7be;font-size:22px}
.workspace strong{display:block;font-size:12.5px;max-width:168px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.workspace small{display:block;font-size:10.5px;color:#8694a1}
.mode-info{padding:7px 11px;display:flex;align-items:center;gap:10px;color:#bfc8d3;font-size:12px}
.info-dot{width:8px;height:8px;background:#69cdb3;border-radius:50%;box-shadow:0 0 9px #68cdb34b}
.sidebar-bottom{margin-top:auto}
.private-note{color:#85919e;background:#1c222a;border:1px solid #262d36;padding:12px;border-radius:10px;font-size:11px;line-height:1.8}
.sidebar-version{font-size:11px;color:#657381;margin-top:18px;padding:0 4px}
.main{min-width:0;flex:1;display:flex;flex-direction:column;background:#101318}
.topbar{min-height:69px;display:flex;align-items:center;justify-content:space-between;padding:0 31px;border-bottom:1px solid #262b32;gap:10px}
.top-title{display:flex;align-items:center;gap:13px}
.top-title strong{font-size:16px;font-weight:700}
.top-title small{color:#87939f;border-left:1px solid #3a424a;padding-left:13px;font-size:12px}
.top-actions{display:flex;gap:15px;align-items:center}
.status{display:flex;align-items:center;gap:8px;color:#9ca9b4;font-size:12px}
.status-dot{width:7px;height:7px;border-radius:50%;background:#67cbb4}
.status-dot.working{background:#e5b56d;animation:pulse 1.3s infinite}
.menu-toggle{display:none;border:none;background:transparent;color:#eee;font-size:20px}
@keyframes pulse{50%{opacity:.3}
}
.chat-scroll{flex:1;min-height:0;overflow:auto;scroll-behavior:smooth}
.chat-content{max-width:920px;min-height:100%;margin:0 auto;padding:28px 32px 22px}
.welcome{text-align:center;min-height:calc(100dvh - 325px);display:flex;flex-direction:column;align-items:center;justify-content:center;max-width:620px;margin:0 auto}
.welcome-icon{width:72px;height:72px;display:grid;place-items:center;background:radial-gradient(circle at 40% 30%,#286c6c,#153039);color:#b1fff2;font-size:42px;border:1px solid #2f636a;border-radius:22px;margin-bottom:20px}
.welcome h1{font-size:28px;letter-spacing:-1px;font-weight:750;margin:0 0 6px}
.welcome p{color:#97a4af;margin:0;font-size:13px;line-height:1.9}
.suggestions{display:flex;flex-wrap:wrap;gap:10px;justify-content:center;margin-top:29px}
.suggestion{background:#20262d;border:1px solid #3b444e;border-radius:11px;color:#cbd4db;padding:12px 16px;font-size:12px}
.suggestion:hover{background:#2b343e}
.message{display:flex;gap:14px;margin:16px 0 27px;min-width:0}
.avatar{flex:0 0 31px;height:31px;border-radius:10px;display:grid;place-items:center;font-size:17px;font-weight:600}
.avatar-user{background:#273744;color:#afd8ef}
.avatar-ai{background:#224540;color:#9eecdd}
.message-body{min-width:0;flex:1}
.message-header{display:flex;align-items:baseline;gap:10px;margin:2px 0 9px}
.message-header strong{font-size:13px}
.message-header small{font-size:11px;color:#84909c}
.message-text{font-size:14px;line-height:1.85;min-width:0;overflow-wrap:anywhere}
.user-text{white-space:pre-wrap;background:#1e2630;padding:13px 17px;border-radius:6px 15px 15px 15px;border:1px solid #303b48;color:#e6eaf0;max-width:100%}
.markdown{color:#dce2e9}
.markdown h1,.markdown h2,.markdown h3,.markdown h4{color:#eff4f8;line-height:1.35;letter-spacing:-.35px;margin:1.5em 0 .65em;font-weight:720}
.markdown h1{font-size:24px}
.markdown h2{font-size:19px;border-bottom:1px solid #313a44;padding-bottom:9px}
.markdown h3{font-size:16px}
.markdown h4{font-size:14px}
.markdown p{margin:0 0 1em}
.markdown h1:first-child,.markdown h2:first-child,.markdown h3:first-child{margin-top:0}
.markdown strong{color:#f7f9fb;font-weight:700}
.markdown ul,.markdown ol{padding-left:23px;margin:0 0 1.1em}
.markdown li{padding-left:2px;margin:.2em 0}
.markdown li::marker{color:#81cdbd}
.markdown code{background:#29333e;color:#a7e5ce;font-family:"Cascadia Code","Consolas",monospace;padding:2px 5px;border-radius:4px;font-size:.89em}
.markdown pre{background:#181f27;border:1px solid #313e49;padding:15px 16px;border-radius:10px;overflow:auto;line-height:1.6;max-height:650px}
.markdown pre code{background:transparent;padding:0;border-radius:0;color:#d1dae2}
.markdown table{width:100%;border-collapse:collapse;font-size:12.5px;margin:17px 0 22px;display:block;overflow-x:auto;border:1px solid #37424c;border-radius:8px}
.markdown th,.markdown td{padding:10px 13px;text-align:left;border-right:1px solid #35404a;border-bottom:1px solid #35404a;min-width:90px;vertical-align:top}
.markdown th{background:#26323c;color:#f2f5f6;font-weight:700}
.markdown tr:nth-child(2n){background:#1a222b}
.markdown tr:last-child td{border-bottom:0}
.markdown blockquote{border-left:3px solid #569f99;color:#bac8d0;background:#1a2529;padding:9px 17px;margin:16px 0;border-radius:0 8px 8px 0}
.markdown hr{border:0;border-top:1px solid #313943;margin:25px 0}
.markdown a{color:#88d7d5;text-decoration:underline;text-underline-offset:3px}
.markdown img{max-width:100%;border-radius:7px}
.message-actions{display:flex;gap:10px;margin-top:10px}
.copy-button{font-size:11px;background:transparent;color:#7f8e9e;border:none;padding:3px 0}
.copy-button:hover{color:#bcd9e1}
.tool-list{display:flex;flex-direction:column;gap:8px;margin:12px 0}
.tool-chip{border:1px solid #36434a;background:#1b252b;border-radius:9px;overflow:hidden}
.tool-chip summary{cursor:pointer;color:#a5ccc4;font-size:11px;padding:7px 10px;font-weight:600}
.tool-chip pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:0;padding:10px;font-size:11px;color:#a3adb7;border-top:1px solid #303a42;max-height:280px;overflow:auto}
.notice{font-size:12px;padding:9px 11px;border:1px solid #594932;background:#2e271c;color:#ecc68d;border-radius:8px;margin:11px 0}
.result-line{display:flex;flex-wrap:wrap;gap:12px;margin:11px 0;color:#8799a6;font-size:11px}
.result-line .success{color:#72ccb0}
.result-line .failure{color:#ff9893}
.thinking{color:#8d9daa;font-size:12px;display:flex;align-items:center;gap:8px;margin:10px 0}
.spinner{display:inline-block;width:13px;height:13px;border:2px solid #43535b;border-top-color:#85ddcc;border-radius:50%;animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}
}
.composer-area{border-top:1px solid #242b33;background:linear-gradient(to bottom,#13181e,#101318);padding:13px 30px 17px}
.composer-wrap{max-width:920px;margin:0 auto}
.composer-toolbar{display:flex;flex-wrap:wrap;gap:22px;align-items:center;margin:0 0 9px;padding:0 5px}
.selector-group{display:flex;align-items:center;gap:8px}
.selector-group label{color:#80919e;font-size:11px;font-weight:700}
.selector-group select{background:#202831;color:#dce8ec;border:1px solid #3a4754;border-radius:7px;padding:6px 29px 6px 10px;font-size:12px;max-width:210px}
.composer{border:1px solid #3d5158;background:#202830;border-radius:15px;padding:12px 14px 10px;box-shadow:0 5px 26px #00000020}
.composer:focus-within{border-color:#629c9c;box-shadow:0 0 0 2px #538b8b18}
.composer textarea{display:block;resize:none;overflow-y:auto;max-height:230px;min-height:55px;width:100%;border:none;outline:none;color:#f2f3f5;background:transparent;line-height:1.7;font-size:14px}
.composer textarea::placeholder{color:#81909d}
.composer-footer{display:flex;justify-content:space-between;align-items:center;gap:8px}
.helptext{color:#8495a1;font-size:11px}
.helptext kbd{font-size:11px;font-family:inherit;color:#b2c1c9}
.separator{padding:0 5px}
.send-actions{display:flex;gap:8px}
.send-button{width:35px;height:35px;border:0;border-radius:10px;background:#71cbbb;color:#0c2423;font-size:18px;font-weight:800}
.send-button:hover{background:#8fddcf}
.stop-button{background:#3c2c2f;border:1px solid #905758;color:#f4b5af;border-radius:8px;padding:7px 13px;font-size:12px}
.footnote{text-align:center;margin:8px 0 0;color:#687786;font-size:10.5px}
.modal-backdrop{position:fixed;inset:0;background:#000b;z-index:50;display:flex;align-items:center;justify-content:center;padding:16px}
.modal{width:min(650px,100%);max-height:90dvh;overflow:auto;border:1px solid #405058;border-radius:17px;background:#1a222b;box-shadow:0 20px 80px #0009;padding:25px}
.small-modal{max-width:440px}
.modal-eyebrow{font-size:11px;letter-spacing:.1em;font-weight:750;color:#80d7c7;margin-bottom:7px}
.modal h2{font-size:19px;margin:0 0 7px}
.modal p{margin:0 0 17px;color:#a4b0bc;font-size:13px;line-height:1.7}
.modal input[type=text]{background:#10171d;color:#edf1f4;border:1px solid #45535c;border-radius:8px;padding:11px 12px;width:100%;outline-color:#73cabb}
.modal-actions{display:flex;justify-content:flex-end;gap:11px;margin-top:20px}
.secondary-button,.primary-button{border-radius:9px;padding:10px 15px;font-size:12px;font-weight:700}
.secondary-button{background:#28313a;color:#ecf0f4;border:1px solid #42515b}
.primary-button{background:#69c7b8;color:#0f2525;border:1px solid #69c7b8}
.tool-heading{font-size:12px;color:#9ce2d5;background:#25363a;border:1px solid #3d5b5e;border-radius:8px;padding:9px 12px;margin:15px 0}
.approval-details{margin-top:16px;border:1px solid #374650;border-radius:9px;overflow:hidden}
.approval-details summary{font-size:12px;padding:10px 12px;cursor:pointer;color:#b3c3cd}
.approval-details pre{font-size:11px;white-space:pre-wrap;word-break:break-word;background:#111920;margin:0;padding:13px;max-height:310px;overflow:auto;color:#c8d3df}
.modal .approval-tip{margin-top:14px;font-size:11px;color:#8393a1}
.question-label{font-size:12px;font-weight:650;margin:16px 0 5px}
.question-answer{width:100%;padding:10px;color:#eceff3;background:#111920;border:1px solid #41505c;border-radius:7px}
.toast{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);background:#2b3a40;border:1px solid #517474;color:#e5f8f4;padding:10px 17px;border-radius:9px;z-index:100;box-shadow:0 12px 30px #0008;font-size:12px}
@media(max-width:850px){.sidebar{position:fixed;z-index:30;inset:0 auto 0 0;transform:translateX(-100%);transition:transform .2s}
.sidebar.open{transform:translateX(0)}
.menu-toggle{display:block}
.topbar{padding:0 17px;min-height:57px}
.chat-content{padding:15px 16px}
.composer-area{padding:10px 13px}
.welcome h1{font-size:23px}
.top-title small{display:none}
.markdown table{font-size:12px}
.helptext{font-size:10px}
}
/* Project switcher */
.workspace-button{width:100%;text-align:left;color:inherit;border:1px solid #35414b;cursor:pointer;transition:background .15s}
.workspace-button:hover{background:#28343e}
.workspace-info{min-width:0;flex:1;display:block}
.workspace-info strong{max-width:100%;font-size:12.5px}
.workspace-info small{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.workspace-chevron{font-size:21px;color:#9dafb7}
.recent-title{margin-top:19px}
.recent-list{display:flex;flex-direction:column;gap:4px;overflow:auto;max-height:min(33vh,260px);min-height:30px;padding:0 2px}
.recent-row{display:flex;align-items:center;min-width:0;gap:4px;border-radius:9px}
.recent-row.active{background:#213139}
.recent-project{padding:8px 9px;display:flex;flex-direction:column;align-items:flex-start;flex:1;min-width:0;background:none;color:#c0cbd2;border:0;border-radius:8px;text-align:left}
.recent-project:hover{background:#28323c}
.recent-project strong{font-size:12px;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.recent-project small{font-size:10px;color:#81919d;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.recent-remove{flex:0 0 24px;color:#93a4af;background:transparent;border:0;border-radius:6px;padding:5px 0;font-size:15px}
.recent-remove:hover{background:#3f3033;color:#ffc2c2}
.project-modal{max-width:560px}
.folder-picker-button{width:100%;padding:13px 12px;border:1px solid #508880;background:#24453f;color:#e6fff9;border-radius:10px;text-align:center;font-weight:650}
.folder-picker-button:hover{background:#2d584f}
.path-divider{margin:17px 0 10px;color:#94a3ad;font-size:12px;text-align:center}
.path-label{display:block;color:#b1bec9;margin:0 0 6px;font-size:12px}
.project-modal input[type=text]{font-family:'Cascadia Code','Consolas',monospace;font-size:13px}
.modal .project-hint{font-size:11px;color:#8297a5;margin:15px 0 0}
/* Image attachments */
.attach-button{width:35px;height:35px;border:1px solid #44535d;border-radius:10px;background:#2b3843;color:#dbe8ef;font-size:19px;display:grid;place-items:center}
.attach-button:hover{background:#38505a;border-color:#78cabe}
.composer.drag-active{border-color:#76d4bf;background:#263c3c;box-shadow:0 0 0 3px #76d4bf33}
.attachment-list{display:flex;flex-wrap:wrap;gap:10px;padding:0 0 13px}
.attachment-item{position:relative;width:106px;min-width:0;border:1px solid #465661;background:#172027;border-radius:10px;overflow:hidden}
.attachment-item img{display:block;width:100%;height:84px;object-fit:cover;background:#26323d}
.attachment-item .attachment-name{display:block;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding:4px 7px;color:#cfdae2}
.attachment-remove{position:absolute;top:3px;right:3px;width:23px;height:23px;display:grid;place-items:center;background:#1b232cef;border:1px solid #59646e;color:white;border-radius:50%;font-size:17px;line-height:1}
.attachment-remove:hover{background:#743a3a}
.message-image-grid{display:flex;flex-wrap:wrap;gap:8px;margin-top:9px}
.message-image-grid img{max-width:min(240px,100%);max-height:200px;object-fit:contain;border:1px solid #475560;border-radius:9px;background:#12191f}
.message-image-fallback{display:inline-block;font-size:11px;border:1px solid #4b5c69;border-radius:8px;padding:7px 9px;color:#b8ccd7}
@media(max-width:850px){.attachment-item{width:90px}
.attachment-item img{height:74px}
.helptext{font-size:9px}
}

/* v4: sidebar scrolls as a whole, session history list */
.sidebar{overflow-y:auto}
.side-section-title{margin:22px 8px 9px}
.session-list{display:flex;flex-direction:column;gap:3px;overflow:auto;max-height:min(38vh,330px);min-height:34px;padding:0 2px;flex:0 0 auto}
.session-item{padding:7px 9px;display:flex;flex-direction:column;align-items:flex-start;background:none;color:#c0cbd2;border:0;border-radius:8px;text-align:left;min-width:0}
.session-item:hover{background:#28323c}
.session-item.active{background:#213139}
.session-item strong{font-size:12px;font-weight:600;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.session-item small{font-size:10px;color:#81919d}
.session-empty{font-size:11px;color:#71808d;padding:6px 9px}
.sidebar-bottom{padding-top:18px}
.notify-button{width:100%;margin-bottom:9px;padding:8px 10px;font-size:11px;color:#b6c5cf;background:#1c222a;border:1px solid #2c3540;border-radius:9px;text-align:left}
.notify-button:hover{background:#28323c}

/* v4: messages are a flow in time order */
.flow{display:flex;flex-direction:column;gap:9px;min-width:0}
.flow .message-text{min-width:0}
.flow .markdown>:last-child{margin-bottom:0}
.flow .notice,.flow .result-line,.flow .thinking{margin:0}
.tool-mark{display:inline-block;width:1.1em;color:#7fb7ad}
.tool-chip.tool-ok .tool-mark{color:#72ccb0}
.tool-chip.tool-error{border-color:#6a4144}
.tool-chip.tool-error .tool-mark,.tool-chip.tool-error summary{color:#ff9d98}
.result-line{border-top:1px solid #2a323b;padding-top:10px;font-size:12px}
.result-line .success{font-weight:700}
.thinking{position:sticky;bottom:0;background:#101318;padding:6px 0}
.message.just-finished .result-line .success{animation:finished 1.6s ease-out 1}
@keyframes finished{0%{background:#2f6f61;box-shadow:0 0 0 6px #2f6f61}100%{background:transparent;box-shadow:0 0 0 6px transparent}}

/* v4: top bar extras */
.cost-label{border-left:1px solid #3a424a;padding-left:13px;color:#87939f;font-size:12px}
.cost-label:empty{display:none}
.handoff{position:relative}
.handoff summary{list-style:none;cursor:pointer;font-size:12px;color:#cfe6e1;background:#20303a;border:1px solid #3a5560;border-radius:8px;padding:6px 11px;white-space:nowrap}
.handoff summary::-webkit-details-marker{display:none}
.handoff summary:hover{background:#28404a}
.handoff-menu{position:absolute;right:0;top:calc(100% + 6px);z-index:20;width:300px;background:#1a222b;border:1px solid #405058;border-radius:11px;box-shadow:0 14px 40px #0009;padding:6px;display:flex;flex-direction:column;gap:2px}
.handoff-menu button{display:flex;flex-direction:column;align-items:flex-start;gap:1px;background:none;border:0;border-radius:8px;color:#e3eaf0;padding:9px 10px;text-align:left}
.handoff-menu button:hover{background:#28323c}
.handoff-menu strong{font-size:12.5px}
.handoff-menu small{font-size:10.5px;color:#8a99a6}
.banner{background:#2e271c;border-bottom:1px solid #594932;color:#ecc68d;font-size:12px;line-height:1.7;padding:9px 31px}

/* v4: approval dialog */
.question-block{margin:14px 0 4px}
.question-options{display:flex;flex-direction:column;gap:6px;margin:0 0 8px}
.question-option{display:flex;flex-direction:column;align-items:flex-start;gap:1px;text-align:left;background:#111920;border:1px solid #41505c;border-radius:9px;color:#e6edf2;padding:9px 12px}
.question-option:hover{border-color:#6aa9a0}
.question-option.selected{border-color:#69c7b8;background:#1d3a38}
.question-option strong{font-size:13px}
.question-option small{font-size:11px;color:#9aa9b5}
.modal-actions{flex-wrap:wrap}
@media(max-width:850px){.banner{padding:8px 17px}.cost-label{display:none}.handoff-menu{width:260px}}

コメント

タイトルとURLをコピーしました