Files
Netcatty/infrastructure/ai/conversationExport.ts
T
bincxzandClaude Opus 4.6 72887c35b5 feat: add AI chat panel with Vercel AI SDK integration
Add a comprehensive AI assistant feature to netcatty, enabling AI-powered
terminal automation and multi-host orchestration.

Core features:
- AI chat side panel (Zed-style) with agent selector, session history,
  conversation export (Markdown/JSON/TXT), and streaming responses
- Catty Agent: built-in terminal assistant with 9 tools (terminal exec,
  SFTP read/write, multi-host orchestration) using zod schemas
- BYOK provider support: OpenAI, Anthropic, Google, Ollama, OpenRouter,
  and custom OpenAI-compatible endpoints
- Three-tier permission model: Observer / Confirm / Autonomous
- Command safety: blocklist patterns, doom loop detection, abort support
- External agent support: ACP protocol (JSON-RPC over stdio) for
  Claude Agent, Codex CLI, Gemini CLI, and custom agents

Tech stack:
- Vercel AI SDK (ai, @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google)
  with streamText + fullStream for streaming tool-call loops
- AI Elements: adapted conversation (use-stick-to-bottom), message
  (streamdown markdown), prompt-input (InputGroup) components
- Custom bridge fetch adapter routing all API calls through Electron
  main process IPC to avoid CORS
- zod for tool parameter schemas

UI components:
- AIChatSidePanel, AgentSelector, ChatInput, ChatMessageList
- PermissionDialog, ExecutionPlan, ConversationExport
- AI Elements: conversation, message, tool-call, prompt-input
- New UI primitives: InputGroup, Spinner
- Settings AI tab for BYOK configuration and safety settings

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 14:22:28 +08:00

126 lines
3.5 KiB
TypeScript

import type { AISession } from './types';
/**
* Export a session as Markdown
*/
export function exportAsMarkdown(session: AISession): string {
const lines: string[] = [];
lines.push(`# ${session.title || 'Untitled Chat'}`);
lines.push('');
lines.push(`- **Agent:** ${session.agentId}`);
lines.push(`- **Scope:** ${session.scope.type}${session.scope.targetId ? ` (${session.scope.targetId})` : ''}`);
lines.push(`- **Created:** ${new Date(session.createdAt).toLocaleString()}`);
lines.push(`- **Updated:** ${new Date(session.updatedAt).toLocaleString()}`);
lines.push('');
lines.push('---');
lines.push('');
for (const msg of session.messages) {
if (msg.role === 'system') continue;
const time = new Date(msg.timestamp).toLocaleTimeString();
if (msg.role === 'user') {
lines.push(`## User [${time}]`);
lines.push('');
lines.push(msg.content);
lines.push('');
} else if (msg.role === 'assistant') {
lines.push(`## Assistant [${time}]${msg.model ? ` (${msg.model})` : ''}`);
lines.push('');
lines.push(msg.content);
if (msg.toolCalls?.length) {
lines.push('');
for (const tc of msg.toolCalls) {
lines.push(`### Tool Call: \`${tc.name}\``);
lines.push('');
lines.push('```json');
lines.push(JSON.stringify(tc.arguments, null, 2));
lines.push('```');
lines.push('');
}
}
lines.push('');
} else if (msg.role === 'tool') {
if (msg.toolResults?.length) {
for (const tr of msg.toolResults) {
lines.push(`### Tool Result${tr.isError ? ' (Error)' : ''}`);
lines.push('');
lines.push('```');
lines.push(tr.content);
lines.push('```');
lines.push('');
}
}
}
}
return lines.join('\n');
}
/**
* Export a session as JSON
*/
export function exportAsJSON(session: AISession): string {
return JSON.stringify(session, null, 2);
}
/**
* Export a session as plain text
*/
export function exportAsPlainText(session: AISession): string {
const lines: string[] = [];
lines.push(`Chat: ${session.title || 'Untitled'}`);
lines.push(`Date: ${new Date(session.createdAt).toLocaleString()}`);
lines.push('='.repeat(60));
lines.push('');
for (const msg of session.messages) {
if (msg.role === 'system') continue;
const time = new Date(msg.timestamp).toLocaleTimeString();
if (msg.role === 'user') {
lines.push(`[${time}] You:`);
lines.push(msg.content);
lines.push('');
} else if (msg.role === 'assistant') {
lines.push(`[${time}] Assistant:`);
lines.push(msg.content);
if (msg.toolCalls?.length) {
for (const tc of msg.toolCalls) {
lines.push(` > Tool: ${tc.name}(${JSON.stringify(tc.arguments)})`);
}
}
lines.push('');
} else if (msg.role === 'tool') {
if (msg.toolResults?.length) {
for (const tr of msg.toolResults) {
lines.push(` > Result${tr.isError ? ' [ERROR]' : ''}:`);
lines.push(` ${tr.content}`);
}
lines.push('');
}
}
}
return lines.join('\n');
}
/**
* Generate a suggested filename for export
*/
export function getExportFilename(session: AISession, format: 'md' | 'json' | 'txt'): string {
const title = (session.title || 'chat')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
const date = new Date(session.createdAt).toISOString().slice(0, 10);
return `netcatty-${title}-${date}.${format}`;
}