P0-P8: Full V1.0.0 Alpha implementation + audit reports
Implements 123 tasks across 9 phases (T-001..T-809) totaling 146 source files. Monorepo (P0): - 7-package Bun + Turborepo + TypeScript monorepo - dependency-cruiser enforcing 7 forbidden edges + 5 deep-import rules Contracts (P0): - 16 type files (ids/error/event/runtime/ipc/task/worker-result/tool/artifact/evidence/project/provider/permission/ui/capability/platform) Storage & Events (P1): - DatabaseManager + MigrationRunner (19 tables, 22 indexes, 5 schema_meta seeds) - 16 repositories (Repository<T,I,U> pattern, INV-1 status columns via EventStore.project only) - EventSchemaRegistry (54 durable + 7 ephemeral), EventStore, EventBus, EventIngestor - Project/Session/Artifact/Evidence stores + 8-step Recovery Tools & Permission (P2): - PathClassifier (8 categories), CommandRiskAnalyzer (10 categories), SecretRedactor - PermissionEngine 6-layer evaluation (capability→profile→task_scope→risk→credential→user_prompt) - ToolRegistry with 20+ tools across fs/shell/git/project/artifact/context/permission/doctor - CapabilityManifestValidator + CapabilityRegistry LLM & Context (P3): - ModelConfigLoader, CapabilityMatrix, AnthropicCanonicalConverter - AnthropicAdapter + OpenAICompatibleAdapter - ProviderManager facade - PromptLayerLoader (L0/L1/L3/L5), CompactionPolicy, ContextAssembler Worker IPC & Scheduler (P4): - WorkerProtocol (NDJSON), WorkerProcess (exit codes 0-5), WorkerManager (spawn/handshake) - WorkerRuntime (INV-3: IPC only, no direct fs/shell/SQLite) - 5 worker roles (Executor/Reviewer/Debugger/Compactor/ExperienceMiner) - TaskGraph, WavePlanner, RetryPlanner, AgentMonitor, WorkspaceManager - Scheduler (state machine), 8-step Recovery C++ Toolchain (P5): - DiagnosticParser, CppProjectDetector, CMakeConfigurator, CppBuilder - CppTestRunner, CppcheckRunner, ClangdClient - CppToolRegistrar + capability manifest Projection & TUI (P6): - ProjectionStore (hydrate/apply/snapshot/subscribe) - TuiApp + 8 components (Session/Task/Agent/Tool/Diff/Evidence/Permission/Blocker/Hud) - ProjectionClient in-process ref Agents & Knowledge (P7): - MainAgent, ArchitectureDesigner - DebugKnowledgeStore + LearnedMemoryStore (single-writer, outbox model) - Role integration wiring CLI & Doctor & Release (P8): - Logger + DeveloperLogEncryptor (AES-256-GCM) - DoctorService (self_bootstrap first) - RuntimeApp + ServiceRegistry - 11 CLI commands: run/init/doctor/provider/resume/compact/history/session/restore/e2e/release - CliEntrypoint + air<TODO> Audit (in AirPlan/docs/): - Deepseek开发阶段审计.md (97 findings) - Opus开发阶段审计.md (140+ findings, 18 P0 blockers) - MiniMaxM3开发阶段审计.md (18 P0 blockers, focuses on executability) - AirPlan/TODO.md (technical debt + 42 TODOs by phase) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
233
packages/llm/src/adapters/AnthropicAdapter.ts
Executable file
233
packages/llm/src/adapters/AnthropicAdapter.ts
Executable file
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* AnthropicAdapter - Provider adapter for Anthropic API
|
||||
*
|
||||
* Implements ProviderAdapter contract (contracts §15); DD §12.2.
|
||||
*
|
||||
* @module packages/llm/src/adapters/AnthropicAdapter
|
||||
*/
|
||||
|
||||
import type { CanonicalMessage } from '../canonical/AnthropicCanonical.js'
|
||||
import { AnthropicCanonicalConverter } from '../canonical/AnthropicCanonical.js'
|
||||
|
||||
// Local type definitions (contract types not yet finalized)
|
||||
type CompleteOptions = { max_tokens?: number; temperature?: number; top_p?: number; system?: string }
|
||||
type StreamEvent = { type: 'text' | 'thinking' | 'done'; content?: string; reason?: string }
|
||||
type ModelRequirement = { model: string; provider?: string; min_output_tokens?: number; prefers_thinking?: boolean; requires_tools?: boolean }
|
||||
|
||||
export interface AnthropicConfig {
|
||||
api_key?: string
|
||||
base_url?: string
|
||||
max_retries?: number
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
// Provider stream events
|
||||
export type AnthropicStreamEvent =
|
||||
| { type: 'content_block_start'; index: number; block_type: string }
|
||||
| { type: 'content_block_delta'; index: number; delta: { type: string; text?: string; thinking?: string } }
|
||||
| { type: 'content_block_stop'; index: number }
|
||||
| { type: 'message_start'; message: { id: string; type: string; role: string; content: unknown[] } }
|
||||
| { type: 'message_delta'; delta: { stop_reason?: string; usage?: { output_tokens: number } } }
|
||||
| { type: 'message_stop' }
|
||||
|
||||
export class AnthropicAdapter {
|
||||
private api_key: string
|
||||
private base_url: string
|
||||
private max_retries: number
|
||||
private timeout: number
|
||||
private converter: AnthropicCanonicalConverter
|
||||
|
||||
constructor(config: AnthropicConfig = {}) {
|
||||
this.api_key = config.api_key || process.env.ANTHROPIC_API_KEY || ''
|
||||
this.base_url = config.base_url || process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com'
|
||||
this.max_retries = config.max_retries || 3
|
||||
this.timeout = config.timeout || 60000
|
||||
this.converter = new AnthropicCanonicalConverter()
|
||||
}
|
||||
|
||||
async list_models(): Promise<string[]> {
|
||||
// Anthropic doesn't have a list_models API, return known models
|
||||
return [
|
||||
'claude-opus-4-7-20251119',
|
||||
'claude-sonnet-4-6-20250501',
|
||||
'claude-haiku-4-5-20251001'
|
||||
]
|
||||
}
|
||||
|
||||
async validate_model(model: string): Promise<{ valid: boolean; error?: string }> {
|
||||
const known = await this.list_models()
|
||||
// Allow any model that looks like a Claude model
|
||||
if (model.startsWith('claude-')) {
|
||||
return { valid: true }
|
||||
}
|
||||
// Or check known list
|
||||
if (known.includes(model)) {
|
||||
return { valid: true }
|
||||
}
|
||||
return { valid: false, error: `Unknown model: ${model}` }
|
||||
}
|
||||
|
||||
async complete(
|
||||
messages: CanonicalMessage[],
|
||||
requirement: ModelRequirement,
|
||||
options: CompleteOptions = {}
|
||||
): Promise<{ content: string; usage?: { input_tokens: number; output_tokens: number } }> {
|
||||
const { canonical, report } = this.converter.from_provider('anthropic', messages as unknown[])
|
||||
|
||||
if (!report.ok) {
|
||||
throw new Error(`Conversion failed: ${report.warnings.join(', ')}`)
|
||||
}
|
||||
|
||||
const response = await this.make_request({
|
||||
model: requirement.model,
|
||||
messages: canonical.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content.map(c => {
|
||||
if (c.type === 'text') return { type: 'text', text: c.text }
|
||||
if (c.type === 'thinking') return { type: 'thinking', thinking: c.thinking }
|
||||
if (c.type === 'tool_use') return { type: 'tool_use', id: c.id, name: c.name, input: c.input }
|
||||
return { type: 'text', text: '[tool]' }
|
||||
})
|
||||
})),
|
||||
max_tokens: options.max_tokens || 4096,
|
||||
temperature: options.temperature,
|
||||
top_p: options.top_p,
|
||||
system: options.system,
|
||||
stream: false
|
||||
})
|
||||
|
||||
// Extract content from response
|
||||
const content = this.extract_content(response)
|
||||
const usage = response.usage ? { input_tokens: response.usage.input_tokens, output_tokens: response.usage.output_tokens } : undefined
|
||||
|
||||
return { content, usage }
|
||||
}
|
||||
|
||||
async *stream_complete(
|
||||
messages: CanonicalMessage[],
|
||||
requirement: ModelRequirement,
|
||||
options: CompleteOptions = {}
|
||||
): AsyncGenerator<StreamEvent> {
|
||||
const { canonical, report } = this.converter.from_provider('anthropic', messages as unknown[])
|
||||
|
||||
if (!report.ok) {
|
||||
throw new Error(`Conversion failed: ${report.warnings.join(', ')}`)
|
||||
}
|
||||
|
||||
const response = await this.make_request({
|
||||
model: requirement.model,
|
||||
messages: canonical.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content.map(c => {
|
||||
if (c.type === 'text') return { type: 'text', text: c.text }
|
||||
if (c.type === 'thinking') return { type: 'thinking', thinking: c.thinking }
|
||||
if (c.type === 'tool_use') return { type: 'tool_use', id: c.id, name: c.name, input: c.input }
|
||||
return { type: 'text', text: '[tool]' }
|
||||
})
|
||||
})),
|
||||
max_tokens: options.max_tokens || 4096,
|
||||
temperature: options.temperature,
|
||||
top_p: options.top_p,
|
||||
system: options.system,
|
||||
stream: true
|
||||
})
|
||||
|
||||
// Parse streaming response
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('No response body')
|
||||
}
|
||||
|
||||
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.trim() || !line.startsWith('data: ')) continue
|
||||
|
||||
const data = line.slice(6)
|
||||
if (data === '[DONE]') continue
|
||||
|
||||
try {
|
||||
const event = JSON.parse(data) as AnthropicStreamEvent
|
||||
yield this.normalize_stream_event(event)
|
||||
} catch {
|
||||
// Skip invalid JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async count_tokens(text: string): Promise<number> {
|
||||
// Simple estimation - in production use proper tokenization
|
||||
return Math.ceil(text.length / 4)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Private helpers
|
||||
// ============================================================================
|
||||
|
||||
private async make_request(body: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
const url = `${this.base_url}/v1/messages`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': this.api_key,
|
||||
'anthropic-version': '2023-06-01'
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
throw new Error(`Anthropic API error: ${response.status} - ${error}`)
|
||||
}
|
||||
|
||||
return response.json() as Promise<Record<string, unknown>>
|
||||
}
|
||||
|
||||
private extract_content(response: Record<string, unknown>): string {
|
||||
const content = response.content as Array<{ type: string; text?: string }> | undefined
|
||||
if (!content) return ''
|
||||
|
||||
return content
|
||||
.filter((b) => b.type === 'text')
|
||||
.map((b) => b.text || '')
|
||||
.join('')
|
||||
}
|
||||
|
||||
private normalize_stream_event(event: AnthropicStreamEvent): StreamEvent {
|
||||
switch (event.type) {
|
||||
case 'content_block_delta':
|
||||
if (event.delta.type === 'text_delta') {
|
||||
return { type: 'text', content: event.delta.text || '' }
|
||||
}
|
||||
if (event.delta.type === 'thinking_delta') {
|
||||
return { type: 'thinking', content: event.delta.thinking || '' }
|
||||
}
|
||||
return { type: 'text', content: '' }
|
||||
|
||||
case 'message_delta':
|
||||
if (event.delta.stop_reason) {
|
||||
return { type: 'done', reason: event.delta.stop_reason }
|
||||
}
|
||||
return { type: 'text', content: '' }
|
||||
|
||||
default:
|
||||
return { type: 'text', content: '' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createAnthropicAdapter(config?: AnthropicConfig): AnthropicAdapter {
|
||||
return new AnthropicAdapter(config)
|
||||
}
|
||||
193
packages/llm/src/adapters/OpenAICompatibleAdapter.ts
Executable file
193
packages/llm/src/adapters/OpenAICompatibleAdapter.ts
Executable file
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* OpenAICompatibleAdapter - Provider adapter for OpenAI-compatible APIs
|
||||
*
|
||||
* Implements ProviderAdapter; uses AnthropicCanonicalConverter.
|
||||
*
|
||||
* @module packages/llm/src/adapters/OpenAICompatibleAdapter
|
||||
*/
|
||||
|
||||
import type { CanonicalMessage } from '../canonical/AnthropicCanonical.js'
|
||||
import { AnthropicCanonicalConverter } from '../canonical/AnthropicCanonical.js'
|
||||
|
||||
// Local type definitions (contract types not yet finalized)
|
||||
type CompleteOptions = { max_tokens?: number; temperature?: number; top_p?: number; system?: string }
|
||||
type StreamEvent = { type: 'text' | 'thinking' | 'done'; content?: string; reason?: string }
|
||||
|
||||
export interface OpenAICompatibleConfig {
|
||||
api_key?: string
|
||||
base_url: string
|
||||
model: string
|
||||
max_retries?: number
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
export class OpenAICompatibleAdapter {
|
||||
private api_key: string
|
||||
private base_url: string
|
||||
private model: string
|
||||
private max_retries: number
|
||||
private timeout: number
|
||||
private converter: AnthropicCanonicalConverter
|
||||
|
||||
constructor(config: OpenAICompatibleConfig) {
|
||||
this.api_key = config.api_key || process.env.OPENAI_API_KEY || 'dummy'
|
||||
this.base_url = config.base_url
|
||||
this.model = config.model
|
||||
this.max_retries = config.max_retries || 3
|
||||
this.timeout = config.timeout || 60000
|
||||
this.converter = new AnthropicCanonicalConverter()
|
||||
}
|
||||
|
||||
async list_models(): Promise<string[]> {
|
||||
// Try to fetch model list, fallback to default
|
||||
try {
|
||||
const response = await fetch(`${this.base_url}/v1/models`, {
|
||||
headers: { Authorization: `Bearer ${this.api_key}` }
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json() as { data: Array<{ id: string }> }
|
||||
return data.data.map(m => m.id)
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
return [this.model]
|
||||
}
|
||||
|
||||
async validate_model(model: string): Promise<{ valid: boolean; error?: string }> {
|
||||
const known = await this.list_models()
|
||||
if (known.includes(model)) {
|
||||
return { valid: true }
|
||||
}
|
||||
// Allow unknown models - might be valid
|
||||
return { valid: true }
|
||||
}
|
||||
|
||||
async complete(
|
||||
messages: CanonicalMessage[],
|
||||
_requirement: { model: string },
|
||||
options: CompleteOptions = {}
|
||||
): Promise<{ content: string; usage?: { input_tokens: number; output_tokens: number } }> {
|
||||
// Convert to OpenAI format
|
||||
const openai_messages = messages.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content.map(c => {
|
||||
if (c.type === 'text') return { type: 'text', text: c.text }
|
||||
if (c.type === 'tool_use') return { type: 'tool_use', id: c.id, name: c.name, input: c.input }
|
||||
return { type: 'text', text: '' }
|
||||
})
|
||||
}))
|
||||
|
||||
const response = await this.make_request({
|
||||
model: this.model,
|
||||
messages: openai_messages,
|
||||
max_tokens: options.max_tokens || 4096,
|
||||
temperature: options.temperature,
|
||||
top_p: options.top_p,
|
||||
stream: false
|
||||
})
|
||||
|
||||
const content = (response.choices?.[0]?.message?.content as string) || ''
|
||||
const usage = response.usage ? { input_tokens: response.usage.prompt_tokens, output_tokens: response.usage.completion_tokens } : undefined
|
||||
|
||||
return { content, usage }
|
||||
}
|
||||
|
||||
async *stream_complete(
|
||||
messages: CanonicalMessage[],
|
||||
_requirement: { model: string },
|
||||
options: CompleteOptions = {}
|
||||
): AsyncGenerator<StreamEvent> {
|
||||
const openai_messages = messages.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content.map(c => {
|
||||
if (c.type === 'text') return { type: 'text', text: c.text }
|
||||
return { type: 'text', text: '' }
|
||||
})
|
||||
}))
|
||||
|
||||
const response = await this.make_request({
|
||||
model: this.model,
|
||||
messages: openai_messages,
|
||||
max_tokens: options.max_tokens || 4096,
|
||||
temperature: options.temperature,
|
||||
top_p: options.top_p,
|
||||
stream: true
|
||||
})
|
||||
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('No response body')
|
||||
}
|
||||
|
||||
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.trim() || !line.startsWith('data: ')) continue
|
||||
|
||||
const data = line.slice(6)
|
||||
if (data === '[DONE]') {
|
||||
yield { type: 'done', reason: 'stop' }
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const event = JSON.parse(data)
|
||||
const choice = event.choices?.[0]
|
||||
if (!choice) continue
|
||||
|
||||
if (choice.delta?.content) {
|
||||
yield { type: 'text', content: choice.delta.content }
|
||||
}
|
||||
if (choice.finish_reason) {
|
||||
yield { type: 'done', reason: choice.finish_reason }
|
||||
}
|
||||
} catch {
|
||||
// Skip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async count_tokens(text: string): Promise<number> {
|
||||
// Simple estimation
|
||||
return Math.ceil(text.length / 4)
|
||||
}
|
||||
|
||||
private async make_request(body: Record<string, unknown>): Promise<{ ok: boolean; status: number; body?: { getReader(): { read(): Promise<{ done: boolean; value: Uint8Array }> }; choices?: Array<{ message?: { content: string }; delta?: { content: string }; finish_reason?: string }>; usage?: { prompt_tokens: number; completion_tokens: number } } }> {
|
||||
const response = await fetch(`${this.base_url}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.api_key}`
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
throw new Error(`OpenAI-compatible API error: ${response.status} - ${error}`)
|
||||
}
|
||||
|
||||
// Handle streaming vs non-streaming
|
||||
const is_streaming = body.stream === true
|
||||
if (is_streaming) {
|
||||
return { ok: true, status: 200, body: response.body as any }
|
||||
}
|
||||
|
||||
return { ok: true, status: 200, body: await response.json() as any }
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenAICompatibleAdapter(config: OpenAICompatibleConfig): OpenAICompatibleAdapter {
|
||||
return new OpenAICompatibleAdapter(config)
|
||||
}
|
||||
Reference in New Issue
Block a user