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>
193 lines
6.0 KiB
TypeScript
Executable File
193 lines
6.0 KiB
TypeScript
Executable File
/**
|
|
* 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)
|
|
} |