/agent-builder-skills:kb-frontend-ssefrom agent-builder-skills
Provides SSE streaming patterns for frontend apps: basic parsing, event handling, two-phase idle timeout, retry logic, and mock implementations for local development.
Ships in agent-builder-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
SSE(Server-Sent Events)を使ったフロントエンドのストリーミング処理パターンを記録する。
const reader = response.body?.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // 不完全な行は次回に持ち越し
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const event = JSON.parse(data);
handleEvent(event);
} catch {
// JSONパースエラーは無視
}
}
}
}
function handleEvent(event) {
// APIによってcontent/dataのどちらかにペイロードが入る
const textValue = event.content || event.data;
switch (event.type) {
case 'text':
onText(textValue);
break;
case 'tool_use':
onToolUse(textValue); // ツール名が返る
break;
case 'markdown':
onMarkdown(textValue);
break;
case 'error':
onError(new Error(event.error || event.message || textValue));
break;
}
}
// ストリーミング中のエラー
case 'error':
if (event.error || event.message) {
callbacks.onError(new Error(event.error || event.message));
}
break;
// HTTPエラー
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
SSEストリームに2段階のタイムアウトを設定し、接続障害と推論ハングの両方を検知する。
async function readSSEStream(
reader: ReadableStreamDefaultReader<Uint8Array>,
onEvent: (event: Record<string, unknown>) => void,
idleTimeoutMs?: number, // 初回イベント受信前(短め: 10秒)
ongoingIdleTimeoutMs?: number // イベント間(長め: 60秒)
): Promise<void> {
let firstEventReceived = false;
while (true) {
// フェーズに応じてタイムアウト値を切り替え
const currentTimeout = firstEventReceived ? ongoingIdleTimeoutMs : idleTimeoutMs;
if (currentTimeout) {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => reject(new SSEIdleTimeoutError(currentTimeout)), currentTimeout);
});
readResult = await Promise.race([reader.read(), timeoutPromise]);
} else {
readResult = await reader.read();
}
// ... イベント処理後に firstEventReceived = true
}
}
| フェーズ | タイムアウト | 検知対象 |
|---|---|---|
| 初回イベント受信前 | 短め(10秒) | スロットリング、接続エラー |
| イベント間(初回受信後) | 長め(60秒) | 推論ハング、モデル無応答 |
設計では次の点を意識する。
※ モックは既定ではない。実物のバックエンドにつないで作る実装ファーストが原則で、AWS 認証がない環境で UI だけ確認するなどの限定用途で使う。
export async function invokeAgentMock(prompt, callbacks) {
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const thinkingText = `${prompt}について考えています...`;
for (const char of thinkingText) {
callbacks.onText(char);
await sleep(20);
}
callbacks.onStatus('生成中...');
await sleep(1000);
callbacks.onMarkdown('# 生成結果\n\n...');
callbacks.onComplete();
}
// 環境変数で切り替え
const useMock = import.meta.env.VITE_USE_MOCK === 'true';
const invoke = useMock ? invokeAgentMock : invokeAgent;
SSE経由のファイルエクスポート(PDF/PPTXなど)は、不安定なネットワークでストリームが切断されることがある。
export async function exportSlide(
markdown: string,
format: ExportFormat,
theme: string = 'border'
): Promise<Blob> {
const MAX_RETRIES = 1;
let lastError: Error | null = null;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
return await _exportSlideOnce(markdown, format, theme);
} catch (e) {
lastError = e as Error;
if (attempt < MAX_RETRIES) {
console.warn(`Export failed (attempt ${attempt + 1}), retrying...`, e);
await new Promise(r => setTimeout(r, 1000));
}
}
}
throw lastError!;
}
以下の点を押さえておく。
reader.read() が done: true を返しても resultBlob が null なら、ストリームが切断されているexport async function exportPdf(markdown: string): Promise<Blob> {
const response = await fetch(url, {
method: 'POST',
headers: { /* 認証ヘッダー等 */ },
body: JSON.stringify({ action: 'export_pdf', markdown }),
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const event = JSON.parse(line.slice(6));
if (event.type === 'pdf' && event.data) {
const binaryString = atob(event.data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return new Blob([bytes], { type: 'application/pdf' });
}
}
}
}
throw new Error('PDF生成に失敗しました');
}
// ダウンロード処理
const blob = await exportPdf(markdown);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'slide.pdf';
a.click();
URL.revokeObjectURL(url);
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
8 skills in this plugin
/cdkd-deployDeploy, diff, bootstrap, inspect, roll back, or destroy AWS CDK applications with the community CDKD CLI while preserving safe production and state-management boundaries. Use when the user mentions cdkd or CDK Direct, asks for faster CDK deployments in development or test environments, or wants to evaluate whether an existing CDK app can use CDKD. Also use for CDKD import, export, state, events, and deployment troubleshooting. Prefer the upstream AWS CDK CLI for production and for existing CloudFormation-managed stacks unless the user explicitly approves a management migration./kb-agentcore-cdkAgentCore CDK・デプロイ・ランタイム統合のナレッジ。Runtime作成、JWT認証、SSE、Dockerfile、コンテナ管理、Browser Tool等/kb-agentcore-identityAgentCore Identity(アウトバウンド認証)のナレッジ。3LO/M2M/デコレータ分離/callback等/kb-agentcore-observabilityAgentCore の Observability ナレッジ。OpenTelemetry 必須4点セット(OTEL_EXPORTER設定・StrandsTelemetry・traceable デコレータ・Langfuse連携)、EMF メトリクス、Jaeger/コンソールエクスポーターでのトレース確認、トレースが出ない・繋がらない場合のデバッグ手順等/kb-agent-webapp-cdkAIエージェントのWebアプリを「AWS CDK(デプロイはCDKD)+ S3 + CloudFront + AgentCore Runtime」で組むときの全体構成。画面は S3 から静的に配信し、サーバー側の処理が要るときだけ Lambda Web Adapter(または Lambda Web Functions)を足す判断基準。スタックの分け方、BucketDeployment での配置とキャッシュ指定、SPA の振り分け、runtime-config.json で環境値を渡す型、Lambda を足すときの Function URL と CloudFront OAC の権限、フロントから AgentCore を直接呼ぶ配線、ローカル開発、デプロイ前後の検証。新しくエージェントのWebアプリを作るとき、Amplify Hosting 以外の配信基盤を選ぶとき、画面の配信に Lambda が要るか迷ったとき、CloudFront 経由の Function URL が 403 になるときに読む。/kb-demo-app-authデモアプリ・Webアプリの Cognito 認証のおすすめ構成。「Googleで続ける」か「メール(パスキーかメールのワンタイムコード。パスワードなし)」の2経路をCDKとフロントでどう組むか、パスキーが動かない設定の罠、Google client secret の置き場、ログイン画面のUX規約、Googleの同意画面に出るアプリ名の扱い。新しくデモアプリを作るとき、既存アプリの認証を作り直すとき、パスキーやGoogleログインが動かないときに読む。npx claudepluginhub minorun365/agent-builder-skills --plugin agent-builder-skillsOther plugins' skills for the same job