mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
Before-merge items: 1. HTTPS enforced on every remote endpoint (RFC 8252 §8.3): baseUrl, issuer, authorization/token/revocation endpoints, and the traces endpoint all reject non-https, with a loopback (127.0.0.1/::1/ localhost) exception for offline tests and local dev. Enforcement is central (assertHttps) — the browser-open guard is no longer the only check whose failure was swallowed. 2. Credential store test isolation: CODEBURN_SYNC_TOKEN_STORE=file forces the file store (honors HOME) so the offline suite never touches the real macOS login keychain. Set in the e2e suite. 3. Golden pins for deriveSpanId/deriveTraceId/deriveDeviceId with fixed inputs and expected hex — the idempotency contract depends on these encodings being stable across releases; a green-tests encoding change would silently double-count history on span-ID-keyed backends. getDeviceId refactored over a pure deriveDeviceId(host, user). Smaller review items: - Callback server: ready promise resolves the actually-bound port from the listening event (kills the 100ms-sleep race after port fallback); Connection: close on all responses + closeAllConnections() on shutdown (pooled keep-alive sockets from a closed server could swallow requests aimed at a later server on the same port); error handler guarded so a post-bind error can never rebind to a different port than advertised; optional ports param ([0] = ephemeral) removes fixed-port contention between parallel test workers. - fetchOidcConfig verifies the issuer claim matches the fetch origin (OIDC Discovery §4.3 mix-up defense). - partialSuccess.rejectedSpans wrapped in Number() — proto3 int64 JSON mapping sends strings from strict protojson servers; += would concatenate. - Ledger writes are atomic (temp + rename); corrupt-ledger recovery and no-tmp-left-behind tests added; XDG_CACHE_HOME honored (ledger is reconstructible state, not config). - Mock IdP now implements /oauth2/authorize (registers PKCE challenge, 302s to redirect_uri) and verifies S256 code_verifier + single-use codes at the token endpoint. The e2e drives the real redirect flow and asserts wrong-verifier and code-reuse are rejected — PKCE binding is now exercised end to end. - sync reset calls clearLedger() instead of reimplementing the path. - push sets exit code 1 on rate-limited/server-error outcomes so cron and script callers can detect incomplete pushes. Deferred (noted for fast-follow): macOS 'security -i' stdin mode (untestable on this Linux box), ai.cost_estimated as a real ParsedApiCall flag (touches core parser types). Sync suite: 81 passing (5x stable), 5 developer-only. AI-Origin: human
143 lines
4.2 KiB
TypeScript
143 lines
4.2 KiB
TypeScript
/**
|
|
* codeburn sync — OTLP payload builder.
|
|
*
|
|
* Converts ParsedApiCall[] into an ExportTraceServiceRequest (OTLP/HTTP JSON).
|
|
* Span and trace IDs are derived deterministically from deduplicationKey/sessionId.
|
|
*/
|
|
|
|
import { createHash } from 'crypto'
|
|
import { hostname, userInfo } from 'os'
|
|
import type { ParsedApiCall } from '../types.js'
|
|
|
|
export interface OtlpSpan {
|
|
traceId: string
|
|
spanId: string
|
|
name: string
|
|
startTimeUnixNano: string
|
|
endTimeUnixNano: string
|
|
attributes: OtlpAttribute[]
|
|
}
|
|
|
|
export interface OtlpAttribute {
|
|
key: string
|
|
value: OtlpValue
|
|
}
|
|
|
|
export type OtlpValue =
|
|
| { stringValue: string }
|
|
| { intValue: string }
|
|
| { doubleValue: number }
|
|
| { boolValue: boolean }
|
|
| { arrayValue: { values: OtlpValue[] } }
|
|
|
|
export interface OtlpPayload {
|
|
resourceSpans: Array<{
|
|
resource: { attributes: OtlpAttribute[] }
|
|
scopeSpans: Array<{
|
|
spans: OtlpSpan[]
|
|
}>
|
|
}>
|
|
}
|
|
|
|
// --- Device ID (pseudonymous, stable) ---
|
|
|
|
let cachedDeviceId: string | null = null
|
|
|
|
/** Pure derivation — exposed so the encoding can be golden-pinned in tests. */
|
|
export function deriveDeviceId(host: string, username: string): string {
|
|
return createHash('sha256').update(`${host}:${username}`).digest('hex').slice(0, 16)
|
|
}
|
|
|
|
export function getDeviceId(): string {
|
|
if (cachedDeviceId) return cachedDeviceId
|
|
cachedDeviceId = deriveDeviceId(hostname(), userInfo().username)
|
|
return cachedDeviceId
|
|
}
|
|
|
|
// --- Span/Trace ID derivation (deterministic) ---
|
|
|
|
export function deriveSpanId(deduplicationKey: string): string {
|
|
return createHash('sha256').update(deduplicationKey).digest('hex').slice(0, 16)
|
|
}
|
|
|
|
export function deriveTraceId(sessionId: string): string {
|
|
return createHash('sha256').update(sessionId).digest('hex').slice(0, 32)
|
|
}
|
|
|
|
// --- Timestamp conversion ---
|
|
|
|
function toUnixNano(isoTimestamp: string): string {
|
|
const ms = new Date(isoTimestamp).getTime()
|
|
if (isNaN(ms)) return '0'
|
|
return (BigInt(ms) * 1_000_000n).toString()
|
|
}
|
|
|
|
// --- Payload construction ---
|
|
|
|
export interface CallWithSession {
|
|
call: ParsedApiCall
|
|
sessionId: string
|
|
project: string
|
|
}
|
|
|
|
export function buildOtlpPayload(calls: CallWithSession[]): OtlpPayload {
|
|
const deviceId = getDeviceId()
|
|
|
|
const spans: OtlpSpan[] = calls.map(({ call, sessionId, project }) => {
|
|
const startNano = toUnixNano(call.timestamp)
|
|
// End time = start + 1ms (we don't have real duration, but OTLP requires both)
|
|
const endNano = (BigInt(startNano) + 1_000_000n).toString()
|
|
|
|
const attributes: OtlpAttribute[] = [
|
|
{ key: 'ai.provider', value: { stringValue: call.provider } },
|
|
{ key: 'ai.model', value: { stringValue: call.model } },
|
|
{ key: 'ai.input_tokens', value: { intValue: String(call.usage.inputTokens) } },
|
|
{ key: 'ai.output_tokens', value: { intValue: String(call.usage.outputTokens) } },
|
|
{ key: 'ai.cost_usd', value: { doubleValue: call.costUSD } },
|
|
{ key: 'ai.project', value: { stringValue: project } },
|
|
{ key: 'ai.speed', value: { stringValue: call.speed } },
|
|
]
|
|
|
|
if (call.tools.length > 0) {
|
|
attributes.push({
|
|
key: 'ai.tools',
|
|
value: { arrayValue: { values: call.tools.map(t => ({ stringValue: t })) } },
|
|
})
|
|
}
|
|
|
|
// cost_estimated = true when provider reports char-based estimates
|
|
const isEstimated = call.provider === 'kiro' || call.usage.inputTokens === 0
|
|
attributes.push({ key: 'ai.cost_estimated', value: { boolValue: isEstimated } })
|
|
|
|
return {
|
|
traceId: deriveTraceId(sessionId),
|
|
spanId: deriveSpanId(call.deduplicationKey),
|
|
name: `${call.provider}/${call.model}`,
|
|
startTimeUnixNano: startNano,
|
|
endTimeUnixNano: endNano,
|
|
attributes,
|
|
}
|
|
})
|
|
|
|
return {
|
|
resourceSpans: [{
|
|
resource: {
|
|
attributes: [
|
|
{ key: 'codeburn.device_id', value: { stringValue: deviceId } },
|
|
],
|
|
},
|
|
scopeSpans: [{
|
|
spans,
|
|
}],
|
|
}],
|
|
}
|
|
}
|
|
|
|
/** Split calls into batches of maxBatchSize. */
|
|
export function batchCalls(calls: CallWithSession[], maxBatchSize: number): CallWithSession[][] {
|
|
const batches: CallWithSession[][] = []
|
|
for (let i = 0; i < calls.length; i += maxBatchSize) {
|
|
batches.push(calls.slice(i, i + maxBatchSize))
|
|
}
|
|
return batches
|
|
}
|