@niscorp/signal 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +139 -0
- package/DOCS.md +502 -0
- package/LICENSE +202 -0
- package/README.md +117 -0
- package/dist/index.cjs +1847 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +591 -0
- package/dist/index.d.ts +591 -0
- package/dist/index.js +1825 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/estimate-usage.ts","../src/errors.ts","../src/registry.ts","../src/utils/sdk-loader.ts","../src/adapters/openai-compatible.adapter.ts","../src/adapters/anthropic.adapter.ts","../src/adapters/google.adapter.ts","../src/adapters/systemone.adapter.ts","../src/transport/protocol.ts","../src/decide/gate.ts","../src/stream/execute-step-stream.ts","../src/output-trust.ts","../src/run.ts","../src/wire/repair.ts","../src/wire/strategies/failed-generation.ts","../src/wire/strategies/jsonl-lines.ts","../src/wire/strategies/index.ts","../src/wire/router.ts","../src/signal.ts","../src/tools/define-tool.ts","../src/transport/resolve.ts","../src/types.ts"],"names":["fn","z","output","tryParse","apiKey","routed","CHARS_PER_TOKEN","injectSchemaDoc"],"mappings":";;;;;AAkBA,IAAM,eAAA,GAAkB,CAAA;AACxB,IAAM,WAAA,GAAc,CAAA;AAEpB,IAAM,QAAA,GAAW,CAAC,OAAA,KAA8B,OAAO,OAAA,KAAY,QAAA,GAAW,OAAA,CAAQ,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,OAAA,IAAW,EAAE,CAAA,CAAE,MAAA;AAEtH,IAAM,gBAAgB,CAC3B,QAAA,EACA,OAAA,EACA,SAAA,GAAqC,EAAC,KACkD;AACxF,EAAA,IAAI,WAAA,GAAc,CAAA;AAClB,EAAA,KAAA,MAAW,OAAA,IAAW,QAAA,EAAU,WAAA,IAAe,WAAA,GAAc,IAAA,CAAK,KAAK,QAAA,C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aAAA,KAAkB,MAAA;AAC1D,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,aAAA;AAAA,IACA,mBAAmB,EAAE,IAAA,EAAM,iBAAA,EAAmB,WAAA,EAAa,qBAAqB,UAAA,EAAW;AAAA,IAC3F,cAAA,EAAgB,iBAAA;AAAA,IAChB,GAAI,IAAA,CAAK,SAAA,IAAa,EAAE,YAAY,UAAA,EAAoB;AAAA,IACxD,eAAA;AAAA,IACA,gBAAgB,cAAA,CAAe,YAAA,CAAa,SAAA,EAAW,IAAA,EAAM,eAAe,CAAC,CAAA;AAAA,IAC7E,WAAA,EAAa,YAAY,SAAS;AAAA,GACpC;AACF;;;AClIO,IAAM,iBAAA,GAAoB,CAAC,MAAA,EAAQ,SAAA,EAAW,WAAW,KAAA,EAAO,QAAA,EAAU,MAAA,EAAQ,OAAA,EAAS,KAAK","file":"index.js","sourcesContent":["import type { Message, StepToolCall } from '../types';\n\n// What a call cost, when the provider will not say.\n//\n// Two paths need this and neither gets a number from the wire:\n//\n// the streamed frame never arrived — OpenAI-compatible streams send usage\n// after the last content chunk and are not reliable about it. The same\n// provider emits it twice on one call and omits it on the next.\n//\n// the generation was REJECTED and recovered — the 400 carries the model's\n// attempt in `failed_generation` and no usage at all, though the provider\n// plainly processed the request and billed for it.\n//\n// Heuristic, ~4 characters per token plus a per-message overhead — the same one\n// `count()` uses. Every result built from this is marked `reported: false`, so a\n// consumer can tell a measurement from a reckoning. An estimate within a few\n// percent is worth far more than a zero that reads as free.\nconst CHARS_PER_TOKEN = 4;\nconst PER_MESSAGE = 4;\n\nconst lengthOf = (content: unknown): number => (typeof content === 'string' ? content.length : JSON.stringify(content ?? '').length);\n\nexport const estimateUsage = (\n messages: readonly Message[],\n content: string,\n toolCalls: readonly StepToolCall[] = [],\n): { inputTokens: number; outputTokens: number; totalTokens: number; reported: false } => {\n let inputTokens = 0;\n for (const message of messages) inputTokens += PER_MESSAGE + Math.ceil(lengthOf(message.content) / CHARS_PER_TOKEN);\n const emitted = content + toolCalls.map((call) => `${call.name}${JSON.stringify(call.args)}`).join('');\n const outputTokens = Math.ceil(emitted.length / CHARS_PER_TOKEN);\n return { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens, reported: false };\n};\n","export const ErrorCode = {\n PROVIDER_NOT_FOUND: 'E_PROVIDER_NOT_FOUND',\n MISSING_API_KEY: 'E_MISSING_API_KEY',\n MISSING_MODEL: 'E_MISSING_MODEL',\n MISSING_SDK: 'E_MISSING_SDK',\n VALIDATION_FAILED: 'E_VALIDATION_FAILED',\n MAX_RETRIES: 'E_MAX_RETRIES',\n MAX_ITERATIONS: 'E_MAX_ITERATIONS',\n PROVIDER_ERROR: 'E_PROVIDER_ERROR',\n TOOL_NOT_FOUND: 'E_TOOL_NOT_FOUND',\n TOOL_EXECUTION: 'E_TOOL_EXECUTION',\n TOOL_VALIDATION: 'E_TOOL_VALIDATION',\n VERB_NOT_SUPPORTED: 'E_VERB_NOT_SUPPORTED',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nexport class SignalError extends Error {\n readonly code: ErrorCode;\n readonly context?: Record<string, unknown>;\n\n constructor(message: string, code: ErrorCode, context?: Record<string, unknown>) {\n super(message);\n this.name = 'SignalError';\n this.code = code;\n this.context = context;\n }\n}\n","import type { EndpointCapabilities, ModelCapabilities, ReasoningEffort } from './types';\n\n// ═══════════════════════════════════════════════════════════\n// Registry — two records, two owners\n// ═══════════════════════════════════════════════════════════\n//\n// `providerRegistry` says what an ENDPOINT is and does, for every model behind\n// it: where it lives, which key opens it, which adapter speaks to it, and the\n// endpoint-level capabilities (types.ts EndpointCapabilities).\n//\n// `modelRegistry` says what one MODEL does on one provider, as measured by\n// scripts/probe-model.ts: the model-level capabilities (ModelCapabilities),\n// the reasoning efforts the endpoint accepts for it, and the day that was\n// measured. Keyed `provider/model id` — the same model behind two providers is\n// two rows, because what it does depends on who serves it.\n//\n// The rules that keep this from rotting:\n// - a row is PASTED from the probe's output, never typed; `verified` is the\n// day the probe ran;\n// - every field is stated — no row inherits from another, and the two record\n// types share no field, so a client's capabilities are a join, not a merge\n// where something silently wins;\n// - a model with no row is not guessed at: it gets UNMEASURED_MODEL, the\n// least a model can do, and describe() says it was not measured;\n// - apps do not keep capability tables of their own. A fact about a model is\n// a row here.\n// test/registry.test.ts holds the invariants.\n\ntype ProviderEntryBase = {\n id: string;\n baseUrl: string;\n envKey: string;\n defaultModel: string;\n};\n\nexport type ChatProviderEntry = ProviderEntryBase & {\n adapter: 'openai-compatible' | 'anthropic' | 'google';\n endpoint: EndpointCapabilities;\n // Wire strategies (src/wire/strategies.ts) — provider-specific\n // recovery/normalization, selected by id. The default repair ladder\n // runs everywhere; this list is only what is true of THIS provider.\n wire?: string[];\n // EXTRA REQUEST PARAMS THAT ASK THIS PROVIDER TO STREAM ITS REASONING.\n // Merged into a STREAMING request, and only when the caller set\n // `reasoningEffort` — so a plain call, or a call to a non-reasoning model on\n // this provider, is untouched. That opt-in is load-bearing: Groq's\n // `reasoning_format` 400s on its non-reasoning models, so it must not ride\n // every request. First-party, like `baseUrl` and `wire`: maintainer-authored\n // constants reviewed in code, not an untrusted declaration.\n reasoningRequest?: Record<string, unknown>;\n};\n\n// A decision provider has no chat, so it has none of chat's capabilities, wire\n// strategies or reasoning params to declare. The adapter it names IS what it\n// can do.\nexport type DecisionProviderEntry = ProviderEntryBase & {\n adapter: 'systemone';\n};\n\nexport type ProviderEntry = ChatProviderEntry | DecisionProviderEntry;\n\nexport type ModelEntry = {\n capabilities: ModelCapabilities;\n // The `reasoning_effort` values the endpoint ACCEPTS for this model. Empty =\n // it takes none; a client that sets one is refused at construction.\n reasoningEfforts: readonly ReasoningEffort[];\n // YYYY-MM-DD — the day scripts/probe-model.ts measured this row.\n verified: string;\n};\n\nexport const providerRegistry: Record<string, ProviderEntry> = {\n groq: {\n id: 'groq',\n baseUrl: 'https://api.groq.com/openai/v1',\n envKey: 'GROQ_API_KEY',\n defaultModel: 'qwen/qwen3.8-27b',\n endpoint: {\n nativeTools: true,\n nativeJsonMode: true,\n // Groq validates tool args server-side (tool_use_failed 400s).\n validatesToolArgs: true,\n supportsEmbedding: false,\n },\n adapter: 'openai-compatible',\n // tool_use_failed / json_validate_failed 400s carry the model's\n // attempt in failed_generation — recover and route it.\n wire: ['failed-generation'],\n // Reasoning models stream their trace only when asked to parse it out;\n // `reasoning_format` is rejected on the non-reasoning ones, which is why\n // this is opt-in (see reasoningRequest above).\n reasoningRequest: { reasoning_format: 'parsed' },\n },\n openai: {\n id: 'openai',\n baseUrl: 'https://api.openai.com/v1',\n envKey: 'OPENAI_API_KEY',\n defaultModel: 'gpt-4o',\n endpoint: {\n nativeTools: true,\n nativeJsonMode: true,\n validatesToolArgs: false,\n supportsEmbedding: true,\n },\n adapter: 'openai-compatible',\n // 4o-era models occasionally emit JSONL where one value was asked\n // for; the acceptance gate decides, so this can never misfire.\n wire: ['jsonl-lines'],\n },\n openrouter: {\n id: 'openrouter',\n baseUrl: 'https://openrouter.ai/api/v1',\n envKey: 'OPENROUTER_API_KEY',\n defaultModel: 'openai/gpt-4o',\n endpoint: {\n nativeTools: true,\n nativeJsonMode: true,\n validatesToolArgs: false,\n supportsEmbedding: false,\n },\n adapter: 'openai-compatible',\n // OpenRouter unifies reasoning across the models it routes; `enabled` turns\n // the trace on for those that have one and is ignored by those that don't.\n reasoningRequest: { reasoning: { enabled: true } },\n },\n anthropic: {\n id: 'anthropic',\n baseUrl: 'https://api.anthropic.com/v1',\n envKey: 'ANTHROPIC_API_KEY',\n defaultModel: 'claude-sonnet-4-20250514',\n endpoint: {\n nativeTools: true,\n nativeJsonMode: true,\n validatesToolArgs: false,\n supportsEmbedding: false,\n },\n adapter: 'anthropic',\n },\n google: {\n id: 'google',\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta',\n envKey: 'GOOGLE_API_KEY',\n defaultModel: 'gemini-2.0-flash',\n endpoint: {\n nativeTools: true,\n nativeJsonMode: true,\n validatesToolArgs: false,\n supportsEmbedding: false,\n },\n adapter: 'google',\n },\n typesafe: {\n id: 'typesafe',\n baseUrl: 'https://api.typesafe.ai/v1',\n envKey: 'TYPESAFE_API_KEY',\n // The moving alias. A caller that records calibration against a model pins\n // a version (`jev-1.13.0`) with `.model()`.\n defaultModel: 'jev-latest',\n adapter: 'systemone',\n },\n};\n\n// Every row below is pasted from scripts/probe-model.ts, trailing comment and\n// all. \"nested: k of n\" is the evidence behind manglesNestedToolArgs — one\n// failing trial is enough to mark it.\n//\n// On OpenRouter, reasoningEfforts is what the proxy ACCEPTS, which is not what\n// the routed model honours: it passes `reasoning_effort` through even to\n// non-reasoning models (gpt-4o takes all seven). The check still prevents a\n// 400; it cannot promise the effort does anything.\nexport const modelRegistry: Record<string, ModelEntry> = {\n // ── groq ──\n 'groq/qwen/qwen3.8-27b': {\n capabilities: { nativeJsonSchema: false, toolsWithStructuredOutput: false, manglesNestedToolArgs: true, multimodal: true }, // nested: 3 of 20 trials failed\n reasoningEfforts: ['none', 'default', 'low', 'medium', 'high'],\n verified: '2026-09-24',\n },\n 'groq/openai/gpt-oss-120b': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: false, manglesNestedToolArgs: true, multimodal: false }, // nested: 1 of 20 trials failed\n reasoningEfforts: ['low', 'medium', 'high'],\n verified: '2026-09-24',\n },\n 'groq/openai/gpt-oss-20b': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: false, manglesNestedToolArgs: true, multimodal: false }, // nested: 6 of 20 trials failed\n reasoningEfforts: ['low', 'medium', 'high'],\n verified: '2026-09-24',\n },\n // ── openai ──\n 'openai/gpt-4o': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: [],\n verified: '2026-09-24',\n },\n 'openai/gpt-4o-mini': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: [],\n verified: '2026-09-24',\n },\n 'openai/gpt-4.1-mini': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: [],\n verified: '2026-09-24',\n },\n // ── openrouter ──\n 'openrouter/qwen/qwen3.8-27b': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/openai/gpt-4o': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/openai/gpt-4o-mini': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/openai/gpt-oss-120b': {\n capabilities: { nativeJsonSchema: false, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: false }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/z-ai/glm-5.2': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: true, multimodal: false }, // nested: 1 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/openai/gpt-5.6-luna': {\n capabilities: { nativeJsonSchema: true, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: true }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/openai/gpt-oss-20b': {\n capabilities: { nativeJsonSchema: false, toolsWithStructuredOutput: true, manglesNestedToolArgs: false, multimodal: false }, // nested: 0 of 20 trials failed\n reasoningEfforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n 'openrouter/meta-llama/llama-3.3-70b-instruct': {\n capabilities: { nativeJsonSchema: false, toolsWithStructuredOutput: true, manglesNestedToolArgs: true, multimodal: false }, // nested: 9 of 20 trials failed\n reasoningEfforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],\n verified: '2026-09-24',\n },\n};\n\n// WHAT AN UNMEASURED MODEL IS ASSUMED TO DO: the least. No grammar, no\n// structured output beside tools, and a tool channel it is not trusted with —\n// so its output rides the content channel (`emit`), which every model can do.\nexport const UNMEASURED_MODEL: ModelCapabilities = {\n nativeJsonSchema: false,\n toolsWithStructuredOutput: false,\n manglesNestedToolArgs: true,\n multimodal: false,\n};\n\nexport const modelKey = (provider: string, model: string): string => `${provider}/${model}`;\n\nexport const modelEntry = (provider: string, model: string): ModelEntry | undefined => modelRegistry[modelKey(provider, model)];\n\nexport const resolveApiKey = (envKey: string, explicitKey?: string): string | undefined =>\n explicitKey ?? (typeof process !== 'undefined' ? process.env?.[envKey] : undefined);\n\n// The row for a provider that generates text — the one a capability-aware\n// consumer means when it reads `endpoint`, `wire` or `reasoningRequest`.\n// Undefined for an unknown id and for a decision provider, which has none.\nexport const chatProviderEntry = (id: string): ChatProviderEntry | undefined => {\n const entry = providerRegistry[id];\n return entry === undefined || entry.adapter === 'systemone' ? undefined : entry;\n};\n","import { SignalError, ErrorCode } from '../errors';\n\nexport const loadSdk = async (pkg: string): Promise<unknown> => {\n try {\n // The provider SDK to load is decided at runtime (whichever\n // adapter the user configured). Bundlers can't statically\n // analyse that, so opt out — the @vite-ignore hint silences\n // the warning, and bundlers that need the actual module bound\n // (Vite, esbuild, etc.) should pre-bundle it via their own\n // optimizeDeps / external configuration.\n const mod = await import(/* @vite-ignore */ pkg);\n return mod.default ?? mod;\n } catch {\n throw new SignalError(\n `Missing dependency: ${pkg}. Install it with: pnpm add ${pkg}`,\n ErrorCode.MISSING_SDK,\n { package: pkg },\n );\n }\n};\n","import type { ChatAdapter, ProviderRequest, ProviderResponse, ProviderStreamDelta, EmbedRequest, EmbedResponse, Message, ContentPart } from '../types';\nimport { SignalError, ErrorCode } from '../errors';\nimport { loadSdk } from '../utils/sdk-loader';\n\n// ═══════════════════════════════════════════════════════════\n// Types for the OpenAI SDK shape\n// ═══════════════════════════════════════════════════════════\n\ntype OpenAIMessage = {\n role: string;\n content: string | Array<{ type: string; text?: string; image_url?: { url: string } }> | null;\n tool_calls?: Array<{ id: string; type: string; function: { name: string; arguments: string } }>;\n tool_call_id?: string;\n};\n\ntype OpenAICompletion = {\n choices?: Array<{\n message?: {\n role: string;\n content?: string | null;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n};\n\n// Overloaded to mirror the SDK: a request with `stream: true` returns a\n// streaming async-iterable; otherwise a single completion. This lets the\n// streaming call site resolve to `OpenAIStream` with no cast.\n// The SDK's `create` takes request options as a second argument (RequestOptions);\n// `signal` is the one we use — it reaches the underlying fetch.\ntype RequestOptions = { signal?: AbortSignal };\n\ntype ChatCreateFn = {\n (params: Record<string, unknown> & { stream: true }, options?: RequestOptions): Promise<OpenAIStream>;\n (params: Record<string, unknown>, options?: RequestOptions): Promise<OpenAICompletion>;\n};\n\ntype OpenAIStreamChunk = {\n choices?: Array<{\n delta?: {\n content?: string | null;\n // Reasoning tokens. Two spellings across providers, both non-standard and\n // absent from the SDK's own delta type — declared here so the parse can\n // read them: OpenRouter and Groq's gpt-oss use `reasoning`, GLM and\n // DeepSeek use `reasoning_content`.\n reasoning?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n};\n\ntype OpenAIStream = AsyncIterable<OpenAIStreamChunk>;\n\ntype OpenAIEmbeddingResponse = {\n data?: Array<{ embedding: number[]; index: number }>;\n usage?: { prompt_tokens?: number; total_tokens?: number };\n};\n\ntype EmbedCreateFn = (params: Record<string, unknown>) => Promise<OpenAIEmbeddingResponse>;\n\n// ═══════════════════════════════════════════════════════════\n// Message Translation\n// ═══════════════════════════════════════════════════════════\n\nconst translateContentParts = (parts: ContentPart[]): Array<{ type: string; text?: string; image_url?: { url: string } }> =>\n parts.map((part) => {\n if (part.type === 'text') return { type: 'text', text: part.text };\n if (part.type === 'image') {\n const url = part.source.type === 'url'\n ? part.source.url\n : `data:${part.source.mediaType};base64,${part.source.data}`;\n return { type: 'image_url', image_url: { url } };\n }\n return { type: 'text', text: '' };\n });\n\nconst translateMessage = (msg: Message): OpenAIMessage => {\n switch (msg.role) {\n case 'system':\n return { role: 'system', content: msg.content };\n case 'user':\n return {\n role: 'user',\n content: typeof msg.content === 'string'\n ? msg.content\n : translateContentParts(msg.content),\n };\n case 'assistant': {\n // Assistant messages may carry tool calls. When they do, the\n // OpenAI API expects them in the `tool_calls` field of the\n // message and `content` MAY be empty (some models return both).\n // Each subsequent `tool` message references one of these calls\n // by `tool_call_id`. This is the standard OpenAI tool-calling\n // contract — Cortex's tool loop relies on it for multi-step\n // tool use to actually work without hallucination.\n const out: OpenAIMessage = { role: 'assistant', content: msg.content };\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n out.tool_calls = msg.toolCalls.map((tc) => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: tc.args },\n }));\n }\n return out;\n }\n case 'tool':\n return { role: 'tool', content: msg.content, tool_call_id: msg.toolCallId };\n default:\n return { role: 'user', content: '' };\n }\n};\n\n// ═══════════════════════════════════════════════════════════\n// SDK Loading\n// ═══════════════════════════════════════════════════════════\n\n// Pluck a bound method off an SDK-shaped object — the injected client\n// (browsers can't resolve the dynamic import; relay/showroom inject)\n// or a freshly constructed SDK instance.\nconst bindAt = <T>(obj: unknown, path: readonly string[]): T | undefined => {\n let parent: unknown;\n let current = obj;\n for (const key of path) {\n if (!current || typeof current !== 'object') return undefined;\n parent = current;\n current = (current as Record<string, unknown>)[key];\n }\n return typeof current === 'function' ? ((current as (...args: unknown[]) => unknown).bind(parent) as T) : undefined;\n};\n\nconst createSdkInstance = async (config: OpenAICompatibleConfig): Promise<unknown> => {\n const Sdk = await loadSdk('openai');\n const Constructor = (typeof Sdk === 'function' ? Sdk : (Sdk as Record<string, unknown>)['default']) as\n new (params: { apiKey?: string; baseURL?: string; dangerouslyAllowBrowser?: boolean }) => unknown;\n\n return new Constructor({\n apiKey: config.apiKey,\n baseURL: config.baseUrl,\n dangerouslyAllowBrowser: typeof globalThis.window !== 'undefined',\n });\n};\n\n// strictClient: chat REQUIRES an injected client to be well-shaped;\n// embed quietly falls through to the SDK (clients often omit it).\nconst loadSdkFn = async <T>(\n config: OpenAICompatibleConfig,\n path: readonly string[],\n missing: { message: string; code: ErrorCode },\n strictClient: boolean,\n): Promise<T> => {\n if (config.client) {\n const fn = bindAt<T>(config.client, path);\n if (fn) return fn;\n if (strictClient) {\n throw new SignalError(`Invalid client: expected client.${path.join('.')} to be a function`, ErrorCode.PROVIDER_ERROR);\n }\n }\n const fn = bindAt<T>(await createSdkInstance(config), path);\n if (!fn) throw new SignalError(missing.message, missing.code);\n return fn;\n};\n\nconst loadChatCreateFn = (config: OpenAICompatibleConfig): Promise<ChatCreateFn> =>\n loadSdkFn(config, ['chat', 'completions', 'create'], { message: 'Failed to initialize OpenAI SDK', code: ErrorCode.MISSING_SDK }, true);\n\nconst loadEmbedCreateFn = (config: OpenAICompatibleConfig): Promise<EmbedCreateFn> =>\n loadSdkFn(\n config,\n ['embeddings', 'create'],\n { message: 'Embedding is not supported by this provider or SDK', code: ErrorCode.PROVIDER_ERROR },\n false,\n );\n\n// ═══════════════════════════════════════════════════════════\n// Adapter Factory\n// ═══════════════════════════════════════════════════════════\n\nexport type OpenAICompatibleConfig = {\n apiKey: string;\n baseUrl: string;\n client?: unknown;\n // Params that ask this provider to stream its reasoning, applied only on a\n // streaming call the caller set `reasoningEffort` on (registry.ts).\n reasoningRequest?: Record<string, unknown>;\n};\n\nexport const createOpenAICompatibleAdapter = async (\n config: OpenAICompatibleConfig,\n): Promise<ChatAdapter> => {\n const chatCreate = await loadChatCreateFn(config);\n\n const buildParams = (request: ProviderRequest): Record<string, unknown> => {\n const params: Record<string, unknown> = {\n model: request.model,\n messages: request.messages.map(translateMessage),\n };\n if (request.responseFormat) {\n params['response_format'] = request.responseFormat.type === 'json_schema'\n ? { type: 'json_schema', json_schema: request.responseFormat.jsonSchema }\n : { type: 'json_object' };\n }\n if (request.tools?.length) params['tools'] = request.tools;\n if (request.toolChoice !== undefined) {\n params['tool_choice'] = typeof request.toolChoice === 'string'\n ? request.toolChoice\n : { type: 'function', function: { name: request.toolChoice.name } };\n }\n if (request.options?.temperature !== undefined) params['temperature'] = request.options.temperature;\n if (request.options?.maxTokens !== undefined) params['max_completion_tokens'] = request.options.maxTokens;\n if (request.options?.topP !== undefined) params['top_p'] = request.options.topP;\n if (request.options?.stopSequences) params['stop'] = request.options.stopSequences;\n if (request.options?.seed !== undefined) params['seed'] = request.options.seed;\n if (request.options?.reasoningEffort !== undefined)\n params['reasoning_effort'] = request.options.reasoningEffort;\n return params;\n };\n\n const chat = async (request: ProviderRequest): Promise<ProviderResponse> => {\n const params = buildParams(request);\n\n let completion: OpenAICompletion;\n try {\n completion = await chatCreate(params);\n } catch (error) {\n // Adapters are dumb: wrap and throw, ORIGINAL error under raw.\n // Recovery (Groq failed_generation etc.) is signal's wire layer.\n throw new SignalError(\n `Provider error: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.PROVIDER_ERROR,\n { raw: error },\n );\n }\n\n const choice = completion.choices?.[0];\n return {\n content: choice?.message?.content ?? '',\n toolCalls: choice?.message?.tool_calls?.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n usage: {\n inputTokens: completion.usage?.prompt_tokens ?? 0,\n outputTokens: completion.usage?.completion_tokens ?? 0,\n totalTokens: completion.usage?.total_tokens ?? 0,\n },\n finishReason: choice?.finish_reason ?? 'unknown',\n raw: completion,\n };\n };\n\n async function* chatStream(request: ProviderRequest, options?: RequestOptions): AsyncIterable<ProviderStreamDelta> {\n const streamParams = {\n ...buildParams(request),\n // Ask for the reasoning trace only when the caller wants reasoning — the\n // opt-in that keeps `reasoning_format` off a plain Groq call. Stream-only:\n // the non-stream `chat` path never sees these, so its content is unmoved.\n ...(request.options?.reasoningEffort !== undefined && config.reasoningRequest !== undefined ? config.reasoningRequest : {}),\n stream: true as const,\n stream_options: { include_usage: true },\n };\n\n let sseStream: OpenAIStream;\n try {\n // The signal reaches the SDK's fetch here: an abort tears the HTTP request\n // down at once, rather than waiting for the next delta to notice it.\n sseStream = await chatCreate(streamParams, options);\n } catch (error) {\n throw new SignalError(\n `Provider stream error: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.PROVIDER_ERROR,\n { raw: error },\n );\n }\n\n try {\n for await (const chunk of sseStream) {\n const choice = chunk.choices?.[0];\n if (choice?.delta?.content) {\n yield { type: 'text', text: choice.delta.content };\n }\n // Whichever spelling the provider sent — never both on one delta.\n const reasoning = choice?.delta?.reasoning ?? choice?.delta?.reasoning_content;\n if (reasoning) {\n yield { type: 'reasoning', text: reasoning };\n }\n if (choice?.delta?.tool_calls) {\n for (const tc of choice.delta.tool_calls) {\n yield {\n type: 'tool_call',\n index: tc.index,\n id: tc.id,\n name: tc.function?.name,\n argsFragment: tc.function?.arguments,\n };\n }\n }\n if (chunk.usage) {\n yield {\n type: 'usage',\n inputTokens: chunk.usage.prompt_tokens ?? 0,\n outputTokens: chunk.usage.completion_tokens ?? 0,\n totalTokens: chunk.usage.total_tokens ?? 0,\n };\n }\n if (choice?.finish_reason) {\n yield { type: 'finish', finishReason: choice.finish_reason };\n }\n }\n } catch (error) {\n // Errors can land DURING iteration too (the 400 surfaces on the\n // first chunk read, not only at stream creation) — same wrap.\n if (error instanceof SignalError) throw error;\n throw new SignalError(\n `Provider stream error: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.PROVIDER_ERROR,\n { raw: error },\n );\n }\n }\n\n let cachedEmbedCreate: EmbedCreateFn | undefined;\n\n const embed = async (request: EmbedRequest): Promise<EmbedResponse> => {\n if (!cachedEmbedCreate) cachedEmbedCreate = await loadEmbedCreateFn(config);\n\n const params: Record<string, unknown> = {\n model: request.model,\n input: request.input,\n };\n if (request.dimensions !== undefined) params['dimensions'] = request.dimensions;\n\n let response: OpenAIEmbeddingResponse;\n try {\n response = await cachedEmbedCreate(params);\n } catch (error) {\n throw new SignalError(\n `Embedding error: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.PROVIDER_ERROR,\n { raw: error },\n );\n }\n\n const embeddings = (response.data ?? [])\n .sort((a, b) => a.index - b.index)\n .map(d => d.embedding);\n\n return {\n embeddings,\n usage: {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n },\n };\n };\n\n return { kind: 'chat', id: 'openai-compatible', chat, chatStream, embed };\n};\n","import type { ProviderAdapter } from '../types';\nimport { SignalError, ErrorCode } from '../errors';\n\nexport type AnthropicConfig = {\n apiKey: string;\n client?: unknown;\n};\n\nexport const createAnthropicAdapter = async (\n _config: AnthropicConfig,\n): Promise<ProviderAdapter> => {\n // Stub — Anthropic adapter to be implemented\n throw new SignalError(\n 'Anthropic adapter is not yet implemented. Use openai-compatible with OpenRouter for Anthropic models.',\n ErrorCode.PROVIDER_ERROR,\n );\n};\n","import type { ProviderAdapter } from '../types';\nimport { SignalError, ErrorCode } from '../errors';\n\nexport type GoogleConfig = {\n apiKey: string;\n client?: unknown;\n};\n\nexport const createGoogleAdapter = async (\n _config: GoogleConfig,\n): Promise<ProviderAdapter> => {\n // Stub — Google adapter to be implemented\n throw new SignalError(\n 'Google adapter is not yet implemented. Use openai-compatible with OpenRouter for Google models.',\n ErrorCode.PROVIDER_ERROR,\n );\n};\n","import { z } from 'zod';\nimport type { DecisionAdapter, DecisionRequest, DecisionResponse } from '../types';\nimport { SignalError, ErrorCode } from '../errors';\n\n// ═══════════════════════════════════════════════════════════\n// The System One wire — state and typed questions in, answers out\n// ═══════════════════════════════════════════════════════════\n//\n// One POST, one JSON body back: `{ model, answers, usage }`. TypeSafe's Jev is\n// the first provider to speak it; like every adapter this one exists per wire\n// protocol, and the vendor is a registry row over it. There is no SDK to load —\n// the protocol is a single fetch — so the injected client is just a `fetch`,\n// which is also how a check points it at a fake provider.\n\nexport type SystemOneConfig = {\n apiKey: string;\n baseUrl: string;\n client?: unknown;\n};\n\nconst InjectedClientSchema = z.object({\n fetch: z.custom<typeof fetch>((value) => typeof value === 'function'),\n});\n\nconst BodySchema = z.object({\n model: z.string().optional(),\n answers: z.unknown(),\n usage: z.object({ input_tokens: z.number(), output_tokens: z.number() }).optional(),\n});\n\nconst sendOf = (client: unknown): typeof fetch => {\n if (client === undefined) return fetch;\n const injected = InjectedClientSchema.safeParse(client);\n if (!injected.success) {\n throw new SignalError('Invalid client: expected client.fetch to be a function', ErrorCode.PROVIDER_ERROR);\n }\n return injected.data.fetch;\n};\n\nconst jsonOrText = (text: string): unknown => {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\nconst providerError = (message: string, raw: unknown): SignalError =>\n new SignalError(`Provider error: ${message}`, ErrorCode.PROVIDER_ERROR, { raw });\n\nexport const createSystemOneAdapter = async (config: SystemOneConfig): Promise<DecisionAdapter> => {\n const send = sendOf(config.client);\n const url = `${config.baseUrl.replace(/\\/+$/, '')}/systemone`;\n\n const decide = async (request: DecisionRequest, options?: { signal?: AbortSignal }): Promise<DecisionResponse> => {\n let status: number;\n let body: unknown;\n try {\n const response = await send(url, {\n method: 'POST',\n headers: { authorization: `Bearer ${config.apiKey}`, 'content-type': 'application/json' },\n body: JSON.stringify({ model: request.model, state: request.state, questions: request.questions }),\n ...(options?.signal !== undefined && { signal: options.signal }),\n });\n status = response.status;\n body = jsonOrText(await response.text());\n } catch (error) {\n // Adapters are dumb: wrap and throw, ORIGINAL error under raw. An abort\n // lands here too — the caller holds the signal and knows it fired.\n throw providerError(error instanceof Error ? error.message : String(error), error);\n }\n if (status < 200 || status >= 300) throw providerError(`HTTP ${status}`, { status, body });\n\n // A body that is not the protocol's shape still goes back as it arrived:\n // the gate rejects it, with these bytes as the evidence.\n const parsed = BodySchema.safeParse(body);\n if (!parsed.success) return { answers: undefined, raw: body };\n return {\n ...(parsed.data.model !== undefined && { model: parsed.data.model }),\n answers: parsed.data.answers,\n ...(parsed.data.usage !== undefined && {\n usage: { inputTokens: parsed.data.usage.input_tokens, outputTokens: parsed.data.usage.output_tokens },\n }),\n raw: body,\n };\n };\n\n return { kind: 'decisions', id: 'systemone', decide };\n};\n","import type { OutputTransport, ResponseMode } from './resolve';\nimport type { Question } from '../types';\n\n// ═══════════════════════════════════════════════════════════\n// Protocol text — EVERY word signal ever puts in a prompt\n// ═══════════════════════════════════════════════════════════\n//\n// Signal is a wire library, not a prompt author. The one exception is\n// transport knowledge — how the run ENDS on the resolved transport —\n// because only signal knows which transport resolved. All of that\n// prose lives HERE and nowhere else; prompt text in any other signal\n// file is a review failure. Each template below is one full sentence\n// block: read it top to bottom and you read what the model sees.\n\n// ─── The exit tool (respond transport) ──────────────────────\n\nexport const RESPOND_DESCRIPTION =\n 'Finish the task. Call this EXACTLY ONCE, ALONE in its own turn, with your final envelope: ' +\n '{ response?: string (human-facing text), data (the payload), reasoning?: string (why) }. ' +\n 'Calling this ends the run.';\n\n// ─── The finish protocol chunk ──────────────────────────────\n\nexport type ProtocolSpec = {\n transport: OutputTransport;\n responseMode: ResponseMode;\n hasData: boolean;\n hasTools: boolean;\n injectSchemaDoc: boolean;\n};\n\n// {shape} = the envelope shape line; {note} = schema pointer or ''.\n\nconst EMIT_WITH_TOOLS = (shape: string, note: string): string =>\n `FINISH PROTOCOL: Use your tools as needed. To finish, your ENTIRE final message must be ONLY the JSON envelope ${shape} — raw JSON, no prose around it, no code fences.${note} A message without tool calls is treated as your final envelope.`;\n\nconst EMIT_TOOLLESS = (shape: string, note: string): string =>\n `FINISH PROTOCOL: Your ENTIRE final message must be ONLY the JSON envelope ${shape} — raw JSON, no prose around it, no code fences.${note}`;\n\nconst NATIVE = (shape: string, note: string): string =>\n `FINISH PROTOCOL: To finish, reply with no tool calls; your reply is the JSON envelope ${shape}.${note}`;\n\nconst RESPOND = (shape: string, note: string): string =>\n `FINISH PROTOCOL: To finish, call the \\`respond\\` tool ALONE in its own turn with the envelope ${shape} as its arguments — or reply with ONLY that JSON envelope as your entire message.${note}`;\n\n// KEY ORDER IS LOAD-BEARING. A model emits JSON in the order it is shown, so a\n// field declared after `data` is written after the answer it is supposed to\n// explain — post-hoc justification, and pure latency. `reasoning` therefore\n// comes FIRST, where writing it conditions everything that follows.\n//\n// Consumers read by key and do not care; only generation order changes.\nconst envelopeShape = (spec: ProtocolSpec): string => {\n if (!spec.hasData) return '{ \"reasoning\"?: string, \"response\": string }';\n return spec.responseMode === 'required'\n ? '{ \"reasoning\"?: string, \"response\": string, \"data\": <the payload> }'\n : '{ \"reasoning\"?: string, \"response\"?: string, \"data\": <the payload> }';\n};\n\nexport const finishProtocol = (spec: ProtocolSpec): string => {\n const shape = envelopeShape(spec);\n const note = spec.hasData && spec.injectSchemaDoc ? ' `data` must match the OUTPUT SCHEMA above.' : '';\n switch (spec.transport) {\n case 'emit':\n return spec.hasTools ? EMIT_WITH_TOOLS(shape, note) : EMIT_TOOLLESS(shape, note);\n case 'native':\n return NATIVE(shape, note);\n case 'respond':\n return RESPOND(shape, note);\n }\n};\n\n// ─── Corrections ────────────────────────────────────────────\n// {issues} is replaced by the caller with the concrete evidence.\n\nconst RESPOND_TERMINATION =\n 'You did not finish. Either call the `respond` tool with your final envelope ({ response?, data, reasoning? }), or reply with ONLY that JSON envelope as your entire message — no surrounding prose.';\n\nconst RESPOND_INVALID =\n 'Your output was invalid: {issues}. Either call `respond`, or reply with ONLY the corrected JSON envelope — no prose.';\n\nconst CONTENT_TERMINATION =\n 'You did not finish. Reply with ONLY the JSON envelope ({ response?, data, reasoning? }) as your entire message — no surrounding prose, no code fences.';\n\nconst CONTENT_INVALID =\n 'Your output was invalid: {issues}. Reply with ONLY the corrected JSON envelope as your entire message.';\n\nexport const corrections = (transport: OutputTransport): { termination: string; invalidOutput: string } =>\n transport === 'respond'\n ? { termination: RESPOND_TERMINATION, invalidOutput: RESPOND_INVALID }\n : { termination: CONTENT_TERMINATION, invalidOutput: CONTENT_INVALID };\n\n// ─── Bare-schema output (the high-level complete()/stream() API) ───\n// Used when the caller's schema cannot ride a native response_format:\n// the contract goes into the prompt and the wire ladder gates arrivals.\n\nexport const bareSchemaPrompt = (jsonSchema: string): string =>\n `OUTPUT SCHEMA: your final reply must be ONLY a JSON value matching this schema — raw JSON, no prose, no code fences:\\n${jsonSchema}`;\n\nexport const bareSchemaCorrection = (issues: string): string =>\n `Your output was invalid: ${issues}. Reply with ONLY the corrected JSON value matching the OUTPUT SCHEMA.`;\n\n// ─── Decision emulation (decide() on a text model) ──────────\n// A text model standing in for a decision model is asked the same questions\n// through structured output. Each question rides its field's description, so\n// the schema stays the contract; the only prose is what frames the state.\n\nexport const decisionEmulationPrompt = (state: string): string =>\n `Answer every field of the OUTPUT SCHEMA about the STATE below. Each field's description is the question and lists everything you may answer with.\\nSTATE:\\n${state}`;\n\nexport const decisionQuestionDescription = (question: Question): string => {\n if (question.type === 'choice') return `${question.instructions} Options: ${JSON.stringify(question.criteria)}`;\n if (question.type === 'score') {\n return `${question.instructions} Answer with the index of the level that fits. Levels, lowest first: ${JSON.stringify(question.criteria)}`;\n }\n return question.criteria === undefined\n ? question.instructions\n : `${question.instructions} Meaning: ${JSON.stringify(question.criteria)}`;\n};\n","import { z, type ZodType } from 'zod';\nimport { SignalError, ErrorCode } from '../errors';\nimport { decisionQuestionDescription } from '../transport/protocol';\nimport type { Questions, Question, CalibratedDecision, UncalibratedDecision } from '../types';\n\n// ═══════════════════════════════════════════════════════════\n// The acceptance gate for decisions\n// ═══════════════════════════════════════════════════════════\n//\n// Signal's rule is that what comes out conforms to the schema that went in. For\n// decide() the schema that went in is the questions object, so the gate is\n// DERIVED from it — one schema per question, built from that question's own\n// options — and an answer outside what was asked is a typed failure with the\n// provider's body as evidence.\n//\n// There is no repair and no correction retry here. A decision model writes no\n// bytes to repair and cannot be told what it got wrong; a failed gate fails the\n// call.\n\nexport type CalibratedDecisions<Qs extends Questions> = { [N in keyof Qs]: CalibratedDecision<Qs[N]> };\nexport type UncalibratedDecisions<Qs extends Questions> = { [N in keyof Qs]: UncalibratedDecision<Qs[N]> };\n\nconst probability = z.number().min(0).max(1);\n\nconst enumOf = (name: string, options: readonly string[]) => {\n const [first, ...rest] = options;\n if (first === undefined) {\n throw new SignalError(`Question \"${name}\" offers nothing to answer with`, ErrorCode.VALIDATION_FAILED, { question: name });\n }\n return z.enum([first, ...rest]);\n};\n\nconst levelKeysOf = (question: { criteria: readonly string[] }): string[] =>\n question.criteria.map((_, level) => String(level));\n\nconst mostProbable = (probabilities: readonly number[]): number =>\n probabilities.reduce((best, value, level) => (value > (probabilities[best] ?? 0) ? level : best), 0);\n\n// What a decision model's answer to ONE question must look like, and the public\n// decision it becomes. The wire keys a score's levels by index string; the\n// public shape is the array those indexes already describe.\nconst calibratedGate = (name: string, question: Question): ZodType => {\n if (question.type === 'choice') {\n const option = enumOf(name, Object.keys(question.criteria));\n return z.object({ choice: option, probabilities: z.record(option, probability), confidence: probability });\n }\n if (question.type === 'score') {\n const keys = levelKeysOf(question);\n const level = enumOf(name, keys);\n return z\n .object({\n score: z.number().min(0).max(keys.length - 1),\n probabilities: z.record(level, probability),\n confidence: probability,\n })\n .transform((answer) => {\n const probabilities = keys.map((key) => answer.probabilities[key] ?? 0);\n return { level: mostProbable(probabilities), score: answer.score, probabilities, confidence: answer.confidence };\n });\n }\n return z.object({ noul: probability }).transform((answer) => ({ answer: answer.noul >= 0.5, noul: answer.noul }));\n};\n\n// The same questions as a text model answers them: the pick and nothing else.\nconst uncalibratedField = (name: string, question: Question): ZodType => {\n const description = decisionQuestionDescription(question);\n if (question.type === 'choice') return enumOf(name, Object.keys(question.criteria)).describe(description);\n if (question.type === 'score') return z.number().int().min(0).max(question.criteria.length - 1).describe(description);\n return z.boolean().describe(description);\n};\n\nconst uncalibratedDecision = (question: Question, value: unknown): Record<string, unknown> => {\n if (question.type === 'choice') return { choice: value };\n if (question.type === 'score') return { level: value };\n return { answer: value };\n};\n\nconst assertAsked = (questions: Questions): void => {\n if (Object.keys(questions).length === 0) {\n throw new SignalError('decide() needs at least one question', ErrorCode.VALIDATION_FAILED);\n }\n};\n\n// True when every question has its decision. Each entry was written by that\n// question's own gate, so covering the names is covering the type.\nconst answersEvery = <Out extends object>(questions: Questions, decisions: object): decisions is Out =>\n Object.keys(questions).every((name) => name in decisions);\n\nconst rejected = (issues: readonly string[], raw: unknown): SignalError =>\n new SignalError(`Decision rejected: ${issues.join('; ')}`, ErrorCode.VALIDATION_FAILED, { issues, raw });\n\nconst issuesOf = (name: string, error: z.ZodError): string[] =>\n error.issues.map((issue) => `${[name, ...issue.path].join('.')}: ${issue.message}`);\n\n// Fails before the network when a question cannot be gated at all.\nexport const assertQuestions = (questions: Questions): void => {\n assertAsked(questions);\n for (const [name, question] of Object.entries(questions)) calibratedGate(name, question);\n};\n\nexport const acceptCalibrated = <Qs extends Questions>(\n questions: Qs,\n answers: unknown,\n raw: unknown,\n): CalibratedDecisions<Qs> => {\n const arrived = z.record(z.string(), z.unknown()).safeParse(answers);\n if (!arrived.success) throw rejected(['the provider returned no answers'], raw);\n\n const decisions: Record<string, unknown> = {};\n const issues: string[] = [];\n for (const [name, question] of Object.entries(questions)) {\n if (!(name in arrived.data)) {\n issues.push(`${name}: not answered`);\n continue;\n }\n const gated = calibratedGate(name, question).safeParse(arrived.data[name]);\n if (gated.success) decisions[name] = gated.data;\n else issues.push(...issuesOf(name, gated.error));\n }\n if (issues.length > 0 || !answersEvery<CalibratedDecisions<Qs>>(questions, decisions)) throw rejected(issues, raw);\n return decisions;\n};\n\n// The contract a text model is held to when it stands in for a decision model.\nexport const uncalibratedSchemaOf = (questions: Questions): ZodType<Record<string, unknown>> =>\n z.strictObject(\n Object.fromEntries(Object.entries(questions).map(([name, question]) => [name, uncalibratedField(name, question)])),\n );\n\nexport const acceptUncalibrated = <Qs extends Questions>(\n questions: Qs,\n value: unknown,\n raw: unknown,\n): UncalibratedDecisions<Qs> => {\n const gated = uncalibratedSchemaOf(questions).safeParse(value);\n if (!gated.success) throw rejected(issuesOf('decisions', gated.error), raw);\n\n const decisions: Record<string, unknown> = {};\n for (const [name, question] of Object.entries(questions)) decisions[name] = uncalibratedDecision(question, gated.data[name]);\n if (!answersEvery<UncalibratedDecisions<Qs>>(questions, decisions)) throw rejected(['a question went unanswered'], raw);\n return decisions;\n};\n","import type {\n Message, ChatAdapter, ProviderRequest, ProviderStreamDelta,\n StepRequest, StepResult, StepStreamEvent, StepToolCall, StreamOptions,\n} from '../types';\nimport { estimateUsage } from '../utils/estimate-usage';\n\n// ═══════════════════════════════════════════════════════════\n// executeStepStream — step-level streaming (one adapter call)\n// ═══════════════════════════════════════════════════════════\n//\n// Mirrors step() but streams. No schema validation, no retries,\n// no auto tool execution. The caller (typically @niscorp/cortex)\n// owns the tool loop and re-invokes for each iteration.\n\nexport type ExecuteStepStreamConfig = {\n adapter: ChatAdapter;\n model: string;\n request: StepRequest;\n streamOptions?: StreamOptions;\n};\n\ntype AssembledToolCall = { id: string; name: string; args: string };\n\n\nconst assembleToolCall = (\n map: Map<number, AssembledToolCall>,\n delta: Extract<ProviderStreamDelta, { type: 'tool_call' }>,\n): void => {\n let tc = map.get(delta.index);\n if (!tc) {\n tc = { id: delta.id ?? '', name: delta.name ?? '', args: '' };\n map.set(delta.index, tc);\n }\n if (delta.id) tc.id = delta.id;\n if (delta.name) tc.name = delta.name;\n if (delta.argsFragment) tc.args += delta.argsFragment;\n};\n\nconst buildProviderRequest = (\n model: string,\n request: StepRequest,\n): ProviderRequest => {\n const providerTools = request.tools && request.tools.length > 0\n ? request.tools.map((tool) => ({\n type: 'function' as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }))\n : undefined;\n return {\n model,\n messages: request.messages.slice() as Message[],\n ...(providerTools && { tools: providerTools }),\n ...(request.toolChoice !== undefined && { toolChoice: request.toolChoice }),\n ...(request.responseFormat !== undefined && { responseFormat: request.responseFormat }),\n ...(request.options !== undefined && { options: request.options }),\n };\n};\n\nexport async function* executeStepStream(\n config: ExecuteStepStreamConfig,\n): AsyncGenerator<StepStreamEvent> {\n const providerRequest = buildProviderRequest(config.model, config.request);\n const abortSignal = config.streamOptions?.signal;\n\n let contentBuffer = '';\n let finishReason = 'unknown';\n const assembledToolCalls = new Map<number, AssembledToolCall>();\n // REPLACED, not accumulated. Each usage frame is the running total for this\n // call, not an increment — Groq sends the same frame twice on some calls, and\n // adding them reports double what was spent.\n let totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, reported: false };\n\n try {\n for await (const delta of config.adapter.chatStream(providerRequest, abortSignal ? { signal: abortSignal } : undefined)) {\n if (abortSignal?.aborted) return;\n\n switch (delta.type) {\n case 'text':\n contentBuffer += delta.text;\n yield { type: 'text', text: delta.text };\n break;\n // Reasoning is passed straight through and deliberately NOT added to\n // contentBuffer: it is the model thinking, not its answer.\n case 'reasoning':\n yield { type: 'reasoning', text: delta.text };\n break;\n case 'tool_call':\n assembleToolCall(assembledToolCalls, delta);\n // Surface the fragment so callers can parse function-call\n // payloads progressively (cortex feeds these into solid).\n yield {\n type: 'tool_call_delta',\n index: delta.index,\n ...(delta.id !== undefined && { id: delta.id }),\n ...(delta.name !== undefined && { name: delta.name }),\n argsText: delta.argsFragment ?? '',\n };\n break;\n case 'usage':\n totalUsage = {\n inputTokens: delta.inputTokens,\n outputTokens: delta.outputTokens,\n totalTokens: delta.totalTokens,\n reported: true,\n };\n break;\n case 'finish':\n finishReason = delta.finishReason;\n break;\n }\n }\n } catch (error) {\n // An aborted fetch rejects the iterator. Discriminate on the SIGNAL's state,\n // not the error type: the adapter re-wraps every iteration error as a\n // SignalError, so there is no AbortError to match on here. A caller who\n // asked to stop gets the same clean early return as a between-delta abort —\n // never a provider error surfaced up to cortex.\n if (abortSignal?.aborted) return;\n throw error;\n }\n\n const toolCalls: StepToolCall[] = [...assembledToolCalls.values()].map((tc) => {\n let parsed: unknown = tc.args;\n if (typeof tc.args === 'string' && tc.args.length > 0) {\n try {\n parsed = JSON.parse(tc.args);\n } catch {\n parsed = tc.args;\n }\n }\n return { id: tc.id, name: tc.name, args: parsed };\n });\n\n const result: StepResult = {\n content: contentBuffer,\n toolCalls,\n usage: totalUsage.reported ? totalUsage : estimateUsage(providerRequest.messages, contentBuffer, toolCalls),\n finishReason,\n raw: null,\n };\n\n yield { type: 'done', result };\n}\n","// ═══════════════════════════════════════════════════════════\n// asOutput — the single trust boundary for Signal's output type\n// ═══════════════════════════════════════════════════════════\n//\n// When a request carries no Zod schema, the builder's type parameter\n// `T` is `string` by construction: `createSignal()` starts as\n// `Signal<string>` and `T` only widens when you call `.schema()`. In\n// that no-schema branch the model's raw content already IS the output\n// (a string) — but the generic function bodies can't prove `T = string`\n// from a runtime `!schema` check.\n//\n// So this is the ONE place that coercion lives: named and explained,\n// instead of scattered `as unknown as T` at every no-schema return.\n// (Mirrors @niscorp/cortex's `trustAgentReturn`.) Any path reachable\n// only WITH a schema returns validated `result.data` and never touches\n// this helper.\nexport const asOutput = <T>(content: string): T => content as unknown as T;\n","import type { ZodType } from 'zod';\nimport { SignalError, ErrorCode } from './errors';\nimport { bareSchemaPrompt, bareSchemaCorrection } from './transport/protocol';\nimport { asOutput } from './output-trust';\nimport type {\n Capabilities,\n Message,\n SignalMeta,\n SignalOptions,\n SignalResult,\n StepRequest,\n StepResult,\n StepStreamEvent,\n StreamEvent,\n StreamOptions,\n Tool,\n ToolCallRecord,\n} from './types';\n\n// ═══════════════════════════════════════════════════════════\n// The high-level loop — complete()/stream() as wrappers over step\n// ═══════════════════════════════════════════════════════════\n//\n// ONE pipeline: the same step/stepStream seam cortex uses, so the wire\n// layer (repairs, routing, recovery) and the same acceptance gating\n// serve both. The schema here is the caller's BARE schema — it rides\n// `output.accept` for routing and, when no native grammar exists, the\n// prompt (transport/protocol.ts). runStream is the core; runComplete\n// drains it. Request shape is immutable for the life of a run.\n\nexport type RunDeps = {\n stepStream: (request: StepRequest, options?: StreamOptions) => AsyncIterable<StepStreamEvent>;\n model: string;\n capabilities: Capabilities;\n};\n\nexport type RunSpec = {\n messages: Message[];\n schema?: ZodType | undefined;\n tools?: Tool[] | undefined;\n retries: number;\n options?: SignalOptions | undefined;\n streamOptions?: StreamOptions | undefined;\n onRetry?: ((error: Error, attempt: number) => void) | undefined;\n onToolCall?: ((name: string, args: unknown) => void) | undefined;\n};\n\nconst MAX_TOOL_TURNS = 10;\n\nconst ZERO = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n\nconst stringify = (value: unknown): string => {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\n// Converted by the schema's OWN zod (Standard JSON Schema), never by ours: the\n// caller's schema may come from another zod copy, and converting it here would\n// read that copy's metadata through our registry. `output` matches the\n// z.toJSONSchema default.\nconst toJsonSchema = (schema: ZodType): Record<string, unknown> =>\n schema['~standard'].jsonSchema.output({ target: 'draft-07' });\n\n// The one request shape for the whole run.\nconst buildRequest = (spec: RunSpec, caps: Capabilities): Omit<StepRequest, 'messages'> => {\n const tools = spec.tools ?? [];\n if (tools.length > 0 && !caps.nativeTools) {\n throw new SignalError(\n 'This provider has no native tool calling (capabilities.nativeTools) — tools are unavailable here.',\n ErrorCode.PROVIDER_ERROR,\n );\n }\n const descriptors = tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toJsonSchema(tool.inputSchema),\n }));\n const grammarViable =\n spec.schema !== undefined &&\n caps.nativeJsonSchema &&\n (tools.length === 0 || caps.toolsWithStructuredOutput);\n return {\n ...(descriptors.length > 0 && { tools: descriptors }),\n ...(spec.schema && { output: { accept: spec.schema } }),\n ...(grammarViable && spec.schema\n ? {\n responseFormat: {\n type: 'json_schema' as const,\n jsonSchema: { name: 'output', strict: false, schema: toJsonSchema(spec.schema) },\n },\n }\n : spec.schema !== undefined && caps.nativeJsonMode && tools.length === 0\n ? { responseFormat: { type: 'json_object' as const } }\n : {}),\n ...(spec.options && { options: spec.options }),\n };\n};\n\nconst buildMeta = (\n model: string,\n usage: typeof ZERO,\n start: number,\n retries: number,\n toolCalls: ToolCallRecord[],\n raws: unknown[],\n): SignalMeta => ({\n model,\n usage,\n durationMs: Date.now() - start,\n retries,\n toolCalls,\n provider: { raw: raws.length === 1 ? raws[0] : raws, errors: [] },\n});\n\n// ───────────────────────────────────────────────────────────\n// runStream — the core; every other entry point drains it\n// ───────────────────────────────────────────────────────────\n\nexport async function* runStream<T>(spec: RunSpec, deps: RunDeps): AsyncGenerator<StreamEvent<T>> {\n const start = Date.now();\n const requestBase = buildRequest(spec, deps.capabilities);\n const toolMap = new Map((spec.tools ?? []).map((tool) => [tool.name, tool]));\n\n const messages: Message[] = [...spec.messages];\n // No grammar carries the contract → the prompt does (protocol.ts).\n if (spec.schema && requestBase.responseFormat?.type !== 'json_schema') {\n messages.push({ role: 'system', content: bareSchemaPrompt(JSON.stringify(toJsonSchema(spec.schema))) });\n }\n\n let usage = ZERO;\n let retries = 0;\n const records: ToolCallRecord[] = [];\n const raws: unknown[] = [];\n\n for (let turn = 0; turn < MAX_TOOL_TURNS + spec.retries; turn += 1) {\n let result: StepResult | undefined;\n for await (const event of deps.stepStream({ ...requestBase, messages }, spec.streamOptions)) {\n if (event.type === 'text') yield { type: 'text', text: event.text };\n if (event.type === 'done') result = event.result;\n }\n if (!result) throw new SignalError('stream ended without a done event', ErrorCode.PROVIDER_ERROR);\n usage = {\n inputTokens: usage.inputTokens + result.usage.inputTokens,\n outputTokens: usage.outputTokens + result.usage.outputTokens,\n totalTokens: usage.totalTokens + result.usage.totalTokens,\n };\n raws.push(result.raw);\n\n // Tool turn — execute locally, feed results back, go again.\n const calls = result.outcome?.kind === 'tool_calls' ? result.outcome.calls : spec.schema ? [] : result.toolCalls;\n if (calls.length > 0) {\n messages.push({\n role: 'assistant',\n content: result.content,\n toolCalls: calls.map((call) => ({ id: call.id, name: call.name, args: stringify(call.args) })),\n });\n for (const call of calls) {\n spec.onToolCall?.(call.name, call.args);\n yield { type: 'tool_start', name: call.name, args: call.args };\n const tool = toolMap.get(call.name);\n const parsed = tool?.inputSchema.safeParse(call.args);\n const started = Date.now();\n let output: unknown;\n if (!tool) output = `error: unknown tool \"${call.name}\"`;\n else if (parsed && !parsed.success) {\n output = `error: input_invalid: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`;\n } else {\n try {\n output = await tool.execute(parsed?.data);\n } catch (cause) {\n output = `error: ${cause instanceof Error ? cause.message : String(cause)}`;\n }\n }\n records.push({ name: call.name, args: call.args, result: output, durationMs: Date.now() - started });\n yield { type: 'tool_end', name: call.name, result: output };\n messages.push({ role: 'tool', toolCallId: call.id, name: call.name, content: stringify(output) });\n }\n continue;\n }\n\n // Final turn.\n if (!spec.schema) {\n const history: Message[] = [...messages, { role: 'assistant', content: result.content }];\n yield {\n type: 'done',\n response: asOutput<T>(result.content),\n history,\n meta: buildMeta(deps.model, usage, start, retries, records, raws),\n };\n return;\n }\n if (result.outcome?.kind === 'output') {\n const parsed = spec.schema.safeParse(result.outcome.value);\n if (parsed.success) {\n const history: Message[] = [...messages, { role: 'assistant', content: result.content }];\n yield {\n type: 'done',\n response: parsed.data as T,\n history,\n meta: buildMeta(deps.model, usage, start, retries, records, raws),\n };\n return;\n }\n }\n\n // Invalid output — correct in-run, bounded by spec.retries.\n const evidence = result.outcome?.kind === 'failed' ? result.outcome.evidence : 'output failed schema validation';\n retries += 1;\n const error = new SignalError(`Response failed schema validation: ${evidence}`, ErrorCode.VALIDATION_FAILED);\n spec.onRetry?.(error, retries);\n if (retries > spec.retries) {\n yield { type: 'error', error, recovered: false };\n return;\n }\n yield { type: 'retry', reason: evidence, attempt: retries };\n if (result.content.length > 0) messages.push({ role: 'assistant', content: result.content });\n messages.push({ role: 'system', content: bareSchemaCorrection(evidence) });\n }\n throw new SignalError('Max tool iterations reached', ErrorCode.MAX_ITERATIONS);\n}\n\n// ───────────────────────────────────────────────────────────\n// runComplete — drain the stream, return the result\n// ───────────────────────────────────────────────────────────\n\nexport const runComplete = async <T>(spec: RunSpec, deps: RunDeps): Promise<SignalResult<T>> => {\n for await (const event of runStream<T>(spec, deps)) {\n if (event.type === 'done') return { response: event.response, history: event.history, meta: event.meta };\n if (event.type === 'error') throw event.error;\n }\n throw new SignalError('run ended without a result', ErrorCode.PROVIDER_ERROR);\n};\n","// ═══════════════════════════════════════════════════════════\n// JSON wire repair — pure mechanisms over model-emitted bytes\n// ═══════════════════════════════════════════════════════════\n//\n// \"Models mangle JSON on the wire\" is PROVIDER knowledge, so the\n// mechanisms live in signal, next to the wire layer that composes\n// them. Each does one thing, none validates against a schema, none\n// knows a specific provider. Policy (which mechanism runs when, and\n// whether a candidate is accepted) belongs to the caller; the house\n// rule is rescue-only: a repaired candidate counts ONLY if it passes\n// the caller's own validation, otherwise the original bytes and the\n// original error stand. Mechanisms can therefore be aggressive\n// without being able to invent truth.\n//\n// extractJson — find the JSON value buried in noise\n// repairEscapeDamage — candidate texts with common escape damage undone\n// decodeJsonish — one string that should have been a value\n// deepDecodeJsonish — stringified values anywhere in a tree\n// closeTruncated — a cut-off container, closed at the last\n// complete boundary (drops the torn tail —\n// never fabricates clipped content)\n// isTruncatedJson — does the text end mid-structure?\n\n// ───────────────────────────────────────────────────────────\n// extractJson — the JSON value buried in noise\n// ───────────────────────────────────────────────────────────\n//\n// Handles, in order: clean JSON; invisible characters (BOM,\n// zero-width); markdown fences; prose around the value (the longest\n// {...} or [...] span that parses). Returns the PARSED value — parse\n// success is what makes an extraction an extraction.\n\nexport type ExtractResult = { ok: true; value: unknown } | { ok: false };\n\n// BOM, zero-width space/joiner/non-joiner, word joiner — characters\n// models occasionally leak around JSON that break JSON.parse.\nconst INVISIBLES = /[]/g;\n\nconst tryParse = (text: string): ExtractResult => {\n try {\n return { ok: true, value: JSON.parse(text) };\n } catch {\n return { ok: false };\n }\n};\n\nconst spanCandidates = (text: string, open: string, close: string): string[] => {\n const first = text.indexOf(open);\n if (first < 0) return [];\n const candidates: string[] = [];\n // Longest span first, shrinking from the right: prose after the value\n // (\"} — done!\") is more common than braces inside trailing prose.\n for (let last = text.lastIndexOf(close); last > first; last = text.lastIndexOf(close, last - 1)) {\n candidates.push(text.slice(first, last + 1));\n if (candidates.length >= 8) break; // bounded — noise, not a search space\n }\n return candidates;\n};\n\nexport const extractJson = (content: string): ExtractResult => {\n const cleaned = content.replace(INVISIBLES, '').trim();\n if (cleaned.length === 0) return { ok: false };\n\n const direct = tryParse(cleaned);\n if (direct.ok) return direct;\n\n const fence = cleaned.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n const body = fence?.[1] !== undefined ? fence[1].trim() : cleaned;\n if (body !== cleaned) {\n const fenced = tryParse(body);\n if (fenced.ok) return fenced;\n }\n\n for (const candidate of [...spanCandidates(body, '{', '}'), ...spanCandidates(body, '[', ']')]) {\n const parsed = tryParse(candidate);\n if (parsed.ok) return parsed;\n }\n return { ok: false };\n};\n\n// ───────────────────────────────────────────────────────────\n// repairEscapeDamage — common over-escaping, as candidate texts\n// ───────────────────────────────────────────────────────────\n//\n// Reasoning models sometimes emit `\\'` (not a legal JSON escape) or an\n// extra escaping layer over the whole payload (`\\\"` where `\"` was\n// meant). Returns candidate TEXTS (only those that differ) — the\n// caller parses and validates; this never parses.\n\nexport const repairEscapeDamage = (text: string): string[] => {\n const candidates: string[] = [];\n const noQuoteEscapes = text.replace(/\\\\'/g, \"'\");\n if (noQuoteEscapes !== text) candidates.push(noQuoteEscapes);\n const unescaped = text.replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\');\n if (unescaped !== text) candidates.push(unescaped);\n return candidates;\n};\n\n// ───────────────────────────────────────────────────────────\n// decodeJsonish — one string that should have been a value\n// ───────────────────────────────────────────────────────────\n\nexport const decodeJsonish = (value: unknown): unknown => {\n if (typeof value !== 'string') return value;\n const trimmed = value.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return value;\n const direct = tryParse(trimmed);\n if (direct.ok) return direct.value;\n for (const repaired of repairEscapeDamage(trimmed)) {\n const parsed = tryParse(repaired);\n if (parsed.ok) return parsed.value;\n }\n return value;\n};\n\n// Deep variant: decode every JSON-looking string INSIDE a tree. The\n// corruption this rescues (observed: Groq gpt-oss tool-call args)\n// stringifies NESTED arrays/objects inside an otherwise well-formed\n// payload (\"children\": \"[{\\\"component\\\":...\"). Strings that do not\n// decode stay untouched; prose survives.\n\nexport const deepDecodeJsonish = (value: unknown): unknown => {\n if (typeof value === 'string') {\n const decoded = decodeJsonish(value);\n return decoded === value ? value : deepDecodeJsonish(decoded);\n }\n if (Array.isArray(value)) return value.map(deepDecodeJsonish);\n if (typeof value === 'object' && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) out[key] = deepDecodeJsonish(entry);\n return out;\n }\n return value;\n};\n\n// ───────────────────────────────────────────────────────────\n// Structural scan — shared by closeTruncated / isTruncatedJson\n// ───────────────────────────────────────────────────────────\n//\n// One pass tracking the open-container stack, string/escape state and\n// object phases (a closing quote ends a KEY or a VALUE — only values\n// mark boundaries). A \"boundary\" is a position where cutting the text\n// and appending the closers of everything still open yields valid\n// JSON: right after a completed value or a closed container.\n\ntype Frame = { type: 'obj' | 'arr'; expectingValue: boolean };\n\ntype Scan = {\n // Open containers at end of text (empty = balanced).\n openAtEnd: number;\n // Last boundary: cut index (exclusive) + the closers to append.\n boundary?: { end: number; closers: string };\n};\n\nconst LITERAL_CHARS = /[0-9a-zA-Z.+\\-]/;\n\nconst isCompleteLiteral = (buf: string): boolean => {\n if (buf === 'true' || buf === 'false' || buf === 'null') return true;\n return buf.length > 0 && !Number.isNaN(Number(buf));\n};\n\nconst scan = (text: string): Scan | undefined => {\n const stack: Frame[] = [];\n let inString = false;\n let escape = false;\n let stringIsValue = false;\n let literal = '';\n let boundary: Scan['boundary'];\n let started = false;\n\n const closers = (): string =>\n [...stack].reverse().map((frame) => (frame.type === 'obj' ? '}' : ']')).join('');\n\n const markBoundary = (end: number): void => {\n boundary = { end, closers: closers() };\n };\n\n const valueDone = (end: number): void => {\n const top = stack[stack.length - 1];\n if (top) top.expectingValue = false;\n markBoundary(end);\n };\n\n const endLiteral = (end: number): void => {\n if (literal.length === 0) return;\n if (isCompleteLiteral(literal)) valueDone(end);\n literal = '';\n };\n\n for (let i = 0; i < text.length; i += 1) {\n const ch = text[i] as string;\n\n if (inString) {\n if (escape) {\n escape = false;\n continue;\n }\n if (ch === '\\\\') {\n escape = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n if (stringIsValue) valueDone(i + 1);\n }\n continue;\n }\n\n if (literal.length > 0 && !LITERAL_CHARS.test(ch)) endLiteral(i);\n\n switch (ch) {\n case '{': {\n started = true;\n stack.push({ type: 'obj', expectingValue: false });\n break;\n }\n case '[': {\n started = true;\n stack.push({ type: 'arr', expectingValue: true });\n break;\n }\n case '}':\n case ']': {\n if (stack.length === 0) return undefined; // not JSON-shaped\n stack.pop();\n valueDone(i + 1);\n break;\n }\n case '\"': {\n const top = stack[stack.length - 1];\n inString = true;\n escape = false;\n // In an object a string is a KEY unless a value is expected;\n // at root or in an array it is always a value.\n stringIsValue = top === undefined || top.type === 'arr' || top.expectingValue;\n break;\n }\n case ':': {\n const top = stack[stack.length - 1];\n if (top?.type === 'obj') top.expectingValue = true;\n break;\n }\n case ',':\n break;\n default: {\n if (LITERAL_CHARS.test(ch)) {\n started = true;\n literal += ch;\n }\n break;\n }\n }\n }\n if (!inString) endLiteral(text.length);\n if (!started) return undefined;\n return { openAtEnd: stack.length + (inString ? 1 : 0), ...(boundary && { boundary }) };\n};\n\n// ───────────────────────────────────────────────────────────\n// closeTruncated / isTruncatedJson\n// ───────────────────────────────────────────────────────────\n//\n// closeTruncated cuts at the LAST complete boundary and appends the\n// closers — the torn tail (a half-written key, a clipped string value)\n// is DROPPED, never patched into plausible-looking content: a clipped\n// string that validates would be fabricated data, a dropped member is\n// an honest absence the caller's schema can catch.\n\nexport const closeTruncated = (content: string): string | undefined => {\n const cleaned = content.replace(INVISIBLES, '').trim();\n if (!cleaned.startsWith('{') && !cleaned.startsWith('[')) return undefined;\n if (tryParse(cleaned).ok) return undefined; // nothing to close\n const result = scan(cleaned);\n if (!result?.boundary || result.openAtEnd === 0) return undefined;\n const candidate = cleaned.slice(0, result.boundary.end) + result.boundary.closers;\n return tryParse(candidate).ok ? candidate : undefined;\n};\n\nexport const isTruncatedJson = (content: string): boolean => {\n const cleaned = content.replace(INVISIBLES, '').trim();\n if (!cleaned.startsWith('{') && !cleaned.startsWith('[')) return false;\n if (tryParse(cleaned).ok) return false;\n return (scan(cleaned)?.openAtEnd ?? 0) > 0;\n};\n","import { closeTruncated, isTruncatedJson } from '../repair';\nimport { SignalError } from '../../errors';\nimport type { Rejection } from '../../types';\nimport type { ErrorWireStrategy } from './index';\n\n// Groq validates tool args / response_format SERVER-SIDE and 400s the\n// whole request (tool_use_failed / json_validate_failed) with the\n// model's attempt in `error.failed_generation`. Both observed shapes\n// normalize here and ONLY here:\n// - parseable `{ name, arguments }` — the attempt was a call;\n// - truncated bytes (Groq caps the body) — close the structure to\n// recover the call shape, or hand the raw bytes to the ladder.\n\nconst RECOVERABLE_CODES = new Set(['tool_use_failed', 'json_validate_failed']);\n\nconst prop = (obj: unknown, key: string): unknown =>\n obj !== null && typeof obj === 'object' ? (obj as Record<string, unknown>)[key] : undefined;\n\n// Adapters wrap provider errors in SignalError with the ORIGINAL error\n// under context.raw — the strategy reads the original.\nconst unwrap = (error: unknown): unknown =>\n error instanceof SignalError ? (error.context?.['raw'] ?? error) : error;\n\nconst errorCode = (error: unknown): string | undefined => {\n const direct = prop(error, 'code');\n if (typeof direct === 'string') return direct;\n const nested = prop(prop(error, 'error'), 'code');\n return typeof nested === 'string' ? nested : undefined;\n};\n\nconst failedGenerationOf = (error: unknown): string | undefined => {\n const gen = prop(prop(error, 'error'), 'failed_generation');\n return typeof gen === 'string' && gen.trim().length > 0 ? gen : undefined;\n};\n\n// When `arguments` is itself a string (double-encoded), args stays\n// unset so the router's ladder runs over the text instead.\ntype CallShape = { name: string; args?: unknown; argsText: string };\n\nconst asCallShape = (value: unknown): CallShape | undefined => {\n const name = prop(value, 'name');\n if (typeof name !== 'string' || name.length === 0) return undefined;\n const args = prop(value, 'arguments');\n if (args === undefined) return undefined;\n if (typeof args === 'string') return { name, argsText: args };\n return { name, args, argsText: JSON.stringify(args) };\n};\n\nconst recover = (error: unknown): Rejection | undefined => {\n const raw = failedGenerationOf(unwrap(error));\n // Not every rejection carries an attempt (gpt-oss commentary-channel\n // emissions rejected as unknown-tool calls, message only). The FACT\n // of the rejection is still worth a typed result.\n if (raw === undefined) return { argsText: '', truncated: false };\n\n try {\n const parsed: unknown = JSON.parse(raw);\n const call = asCallShape(parsed);\n if (call) return { name: call.name, ...(call.args !== undefined && { args: call.args }), argsText: call.argsText, truncated: false };\n // Parseable but not call-shaped: the attempt itself is the payload.\n return { args: parsed, argsText: raw, truncated: false };\n } catch {\n // Truncated or malformed. Closing the structure can recover the\n // call SHAPE — the torn tail is dropped, downstream schemas judge\n // what remains.\n const truncated = isTruncatedJson(raw);\n const closed = closeTruncated(raw);\n if (closed !== undefined) {\n try {\n const call = asCallShape(JSON.parse(closed));\n if (call) return { name: call.name, ...(call.args !== undefined && { args: call.args }), argsText: call.argsText, truncated };\n } catch {\n // fall through to raw bytes\n }\n }\n return { argsText: raw, truncated };\n }\n};\n\nexport const failedGeneration: ErrorWireStrategy = {\n id: 'failed-generation',\n hook: 'error',\n matches: (error) => {\n const code = errorCode(unwrap(error));\n return code !== undefined && RECOVERABLE_CODES.has(code);\n },\n recover,\n};\n","import type { ResponseWireStrategy } from './index';\n\n// 4o-era OpenAI models occasionally emit one JSON object per line\n// (JSONL) where one value was asked for. Contribute each JSON-looking\n// line as a candidate, last line first — the final line is usually the\n// final answer. The acceptance gate decides; on providers that never\n// do this the strategy simply never wins.\n\nexport const jsonlLines: ResponseWireStrategy = {\n id: 'jsonl-lines',\n hook: 'response',\n candidates: (content) => {\n const lines = content\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.startsWith('{') || line.startsWith('['));\n return lines.length > 1 ? lines.reverse() : [];\n },\n};\n","import type { Rejection } from '../../types';\nimport { failedGeneration } from './failed-generation';\nimport { jsonlLines } from './jsonl-lines';\n\n// ═══════════════════════════════════════════════════════════\n// Wire strategies — provider pathologies, one FILE per pathology\n// ═══════════════════════════════════════════════════════════\n//\n// The one strategy pattern in signal. Selection is registry DATA\n// (ProviderEntry.wire lists ids); adding a provider quirk = one file\n// here + one id on the provider entry + fixtures from the real\n// error/response body. Nothing else changes. Two hooks:\n// 'error' — turn a provider ERROR into a Rejection.\n// 'response' — contribute candidate TEXTS from response content.\n\nexport type ErrorWireStrategy = {\n id: string;\n hook: 'error';\n matches: (error: unknown) => boolean;\n recover: (error: unknown) => Rejection | undefined;\n};\n\nexport type ResponseWireStrategy = {\n id: string;\n hook: 'response';\n candidates: (content: string) => string[];\n};\n\nexport type WireStrategy = ErrorWireStrategy | ResponseWireStrategy;\n\nconst REGISTRY: Record<string, WireStrategy> = {\n [failedGeneration.id]: failedGeneration,\n [jsonlLines.id]: jsonlLines,\n};\n\nexport const resolveWireStrategies = (ids: ReadonlyArray<string>): WireStrategy[] =>\n ids.map((id) => {\n const strategy = REGISTRY[id];\n if (!strategy) throw new Error(`Unknown wire strategy \"${id}\" — known: ${Object.keys(REGISTRY).join(', ')}`);\n return strategy;\n });\n\nexport const errorStrategies = (strategies: ReadonlyArray<WireStrategy>): ErrorWireStrategy[] =>\n strategies.filter((strategy): strategy is ErrorWireStrategy => strategy.hook === 'error');\n\nexport const responseStrategies = (strategies: ReadonlyArray<WireStrategy>): ResponseWireStrategy[] =>\n strategies.filter((strategy): strategy is ResponseWireStrategy => strategy.hook === 'response');\n\n// Run the error-hook strategies; the first that claims the error wins.\nexport const recoverRejection = (\n strategies: ReadonlyArray<WireStrategy>,\n error: unknown,\n): { strategy: string; rejection: Rejection } | undefined => {\n for (const strategy of errorStrategies(strategies)) {\n if (!strategy.matches(error)) continue;\n const rejection = strategy.recover(error);\n if (rejection) return { strategy: strategy.id, rejection };\n }\n return undefined;\n};\n\nexport { failedGeneration, jsonlLines };\n","import type { ZodType } from 'zod';\nimport { decodeJsonish, deepDecodeJsonish, extractJson, repairEscapeDamage, closeTruncated, isTruncatedJson } from './repair';\nimport type { Rejection, StepOutcome, StepToolCall, WireReport } from '../types';\nimport type { ResponseWireStrategy } from './strategies';\n\n// ═══════════════════════════════════════════════════════════\n// The router — normalize one response, decide what it IS\n// ═══════════════════════════════════════════════════════════\n//\n// One rule, no name games:\n// - a call matching a DECLARED tool is a tool call;\n// - anything else whose repaired value validates against the\n// acceptance schema is OUTPUT;\n// - what survives neither is a typed failure with evidence.\n//\n// Repairs are rescue-only: a candidate counts ONLY when it passes the\n// acceptance gate; a clean response wins at the first rung untouched.\n\nexport type RouteRequest = {\n content: string;\n toolCalls: ReadonlyArray<StepToolCall>;\n declared: ReadonlySet<string>;\n // The synthetic EXIT tool (respond transport): declared to the\n // provider so its calls are wire-legal, but semantically OUTPUT.\n outputTool?: string | undefined;\n accept?: ZodType | undefined;\n responseStrategies: ReadonlyArray<ResponseWireStrategy>;\n};\n\nexport type Routed = { outcome: StepOutcome; wire: WireReport };\n\n// ─── Result constructors — every return site goes through these ───\n\nconst toolTurn = (calls: StepToolCall[], notes: string[]): Routed => ({\n outcome: { kind: 'tool_calls', calls },\n wire: notes.length > 0 ? { notes } : {},\n});\n\nconst output = (value: unknown, rung: string, note?: string): Routed => ({\n outcome: { kind: 'output', value },\n wire: note === undefined ? { rung } : { rung, notes: [note] },\n});\n\nconst failed = (evidence: string, flags: { truncated?: boolean } = {}): Routed => ({\n outcome: {\n kind: 'failed',\n evidence,\n ...(flags.truncated === true && { truncated: true }),\n },\n wire: {},\n});\n\n// ─── Candidates — the default repair ladder, least-invasive first ───\n\ntype Candidate = { value: unknown; rung: string };\n\n// The parser's own complaint, kept rather than swallowed. When nothing on the\n// ladder parses, this is the only description of what the model actually got\n// wrong, and a correction that cannot name the defect gets the same output back.\nconst tryParse = (text: string): { ok: true; value: unknown } | { ok: false; why: string } => {\n try {\n return { ok: true, value: JSON.parse(text) };\n } catch (error) {\n return { ok: false, why: error instanceof Error ? error.message : String(error) };\n }\n};\n\n// Why the UNTOUCHED text failed, asked only when the whole ladder came up\n// empty. It re-parses rather than remembering: a module-level note would be\n// shared by every route in flight, and two runs answering at once would report\n// each other's defect.\n//\n// The FIRST rung is the only one worth reporting. Every later rung parses text\n// this file has already altered, so its complaint describes a repair rather\n// than what the model wrote.\nconst whyNotJson = (text: string): string | undefined => {\n const direct = tryParse(text.trim());\n return direct.ok ? undefined : direct.why;\n};\n\nfunction* ladder(text: string, strategies: ReadonlyArray<ResponseWireStrategy>): Generator<Candidate> {\n const trimmed = text.trim();\n if (trimmed.length === 0) return;\n\n const direct = tryParse(trimmed);\n if (direct.ok) yield { value: direct.value, rung: 'parse' };\n\n const extracted = extractJson(trimmed);\n if (extracted.ok) yield { value: extracted.value, rung: 'extract' };\n\n for (const repaired of repairEscapeDamage(trimmed)) {\n const parsed = tryParse(repaired);\n if (parsed.ok) yield { value: parsed.value, rung: 'repair-escapes' };\n }\n\n for (const strategy of strategies) {\n for (const candidateText of strategy.candidates(trimmed)) {\n const parsed = tryParse(candidateText);\n if (parsed.ok) yield { value: parsed.value, rung: strategy.id };\n }\n }\n\n const closed = closeTruncated(trimmed);\n if (closed !== undefined) {\n const parsed = tryParse(closed);\n if (parsed.ok) yield { value: parsed.value, rung: 'close-truncated' };\n }\n}\n\n// Gate candidates (and their deep-decoded variants). Returns the RAW\n// winning candidate — the schema is a gate, not a transform. The gate\n// is a TRANSPORT concern; near-miss evidence here is deliberately\n// plain (semantic evidence belongs to the caller's own validation).\nconst firstAccepted = (\n candidates: Iterable<Candidate>,\n accept: ZodType,\n): { winner?: Candidate; nearMiss?: string } => {\n let nearMiss: string | undefined;\n for (const candidate of candidates) {\n const direct = accept.safeParse(candidate.value);\n if (direct.success) return { winner: candidate };\n const deep = deepDecodeJsonish(candidate.value);\n if (deep !== candidate.value && accept.safeParse(deep).success) {\n return { winner: { value: deep, rung: `${candidate.rung}+deep-decode` } };\n }\n nearMiss ??= direct.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('; ');\n }\n return { ...(nearMiss !== undefined && { nearMiss }) };\n};\n\nconst decodedCall = (call: StepToolCall): StepToolCall => ({ ...call, args: decodeJsonish(call.args) });\n\n// ─── The three turn shapes ──────────────────────────────────\n\n// A call that is NOT a domain tool call delivers output through its\n// args (the exit tool, or pseudo-tool fixation). undefined = nothing\n// salvageable and nothing near — the caller picks the fallback.\nconst finishAttempt = (call: StepToolCall, request: RouteRequest): Routed | undefined => {\n if (!request.accept) return undefined;\n const source: Iterable<Candidate> =\n typeof call.args === 'string'\n ? ladder(call.args, request.responseStrategies)\n : [{ value: call.args, rung: 'call-args' }];\n const { winner, nearMiss } = firstAccepted(source, request.accept);\n if (winner) {\n const note = call.name === request.outputTool ? undefined : `output arrived as a call to undeclared tool \"${call.name}\"`;\n return output(winner.value, winner.rung, note);\n }\n if (nearMiss !== undefined) {\n return failed(`the call to \"${call.name}\" carried an invalid output: ${nearMiss}`);\n }\n return undefined;\n};\n\nconst contentEvidence = (content: string, nearMiss: string | undefined): string => {\n if (nearMiss !== undefined) return nearMiss;\n const snippet = content.trim().slice(0, 160);\n if (snippet.length === 0) return 'the turn produced no output';\n // The parser's reason first: \"Expected ',' or ']' after array element at\n // position 2057\" is something a model can act on. The opening characters are\n // not, and on their own they buy a near-identical retry.\n const why = whyNotJson(content);\n return why === undefined\n ? `output is not valid JSON — it began: ${snippet}`\n : `output is not valid JSON: ${why}. It began: ${snippet}`;\n};\n\nconst contentTurn = (request: RouteRequest): Routed => {\n if (!request.accept) return failed('no acceptance schema for a content turn');\n const { winner, nearMiss } = firstAccepted(ladder(request.content, request.responseStrategies), request.accept);\n if (winner) return output(winner.value, winner.rung);\n return failed(contentEvidence(request.content, nearMiss), {\n truncated: isTruncatedJson(request.content),\n });\n};\n\n// ─── routeResponse — a response the provider ACCEPTED ───────\n\nexport const routeResponse = (request: RouteRequest): Routed => {\n const isExit = (call: StepToolCall): boolean => call.name === request.outputTool;\n const domainCalls = request.toolCalls.filter((call) => request.declared.has(call.name) && !isExit(call));\n const attempts = request.toolCalls.filter((call) => !request.declared.has(call.name) || isExit(call));\n\n if (domainCalls.length > 0) {\n const dropped = attempts.map((call) => `dropped call to \"${call.name}\" in a mixed turn — finish attempts must come alone`);\n return toolTurn(domainCalls.map(decodedCall), dropped);\n }\n for (const call of attempts) {\n const routed = finishAttempt(call, request);\n if (routed) return routed;\n }\n if (attempts.length > 0) {\n return failed(`called unknown tool(s) ${attempts.map((call) => `\"${call.name}\"`).join(', ')}`);\n }\n return contentTurn(request);\n};\n\n// ─── routeRejection — the 400 carried the payload ───────────\n//\n// The routing rule is identical. A recovered call to a DECLARED tool\n// becomes a normal tool call (its args are judged by the tool's own\n// schema downstream); anything else is a finish attempt.\n\nlet recoveredCallCounter = 0;\n\nexport const routeRejection = (rejection: Rejection, request: Omit<RouteRequest, 'content' | 'toolCalls'>): Routed => {\n const name = rejection.name;\n if (name !== undefined && request.declared.has(name) && name !== request.outputTool) {\n recoveredCallCounter += 1;\n const args = rejection.args ?? decodeJsonish(rejection.argsText);\n return toolTurn([{ id: `recovered_${recoveredCallCounter}`, name, args }], []);\n }\n\n const call: StepToolCall = { id: '', name: name ?? '', args: rejection.args ?? rejection.argsText };\n const routed = finishAttempt(call, { ...request, content: '', toolCalls: [] });\n if (routed) {\n if (routed.outcome.kind === 'failed' && rejection.truncated) {\n return { ...routed, outcome: { ...routed.outcome, truncated: true } };\n }\n return routed;\n }\n return failed(\n rejection.argsText.length > 0\n ? `provider rejected the attempt${name !== undefined ? ` (call to unknown tool \"${name}\")` : ''} and nothing salvageable remained`\n : 'provider rejected the attempt; nothing was recovered',\n { truncated: rejection.truncated },\n );\n};\n","import { type ZodType } from 'zod';\nimport type {\n Message, ContentPart, Tool, SignalOptions, Capabilities, ReasoningEffort,\n SignalResult, StreamEvent, StepStreamEvent, StreamOptions,\n ProviderAdapter, ChatAdapter, DecisionAdapter, ProviderRequest, ProviderResponse, Rejection,\n StepRequest, StepResult, StepToolCall, CountInput,\n EmbedOptions, Questions, DecideRequest, DecideResult,\n} from './types';\nimport type { SignalConfig, CustomProviderConfig } from './config';\nimport { estimateUsage } from './utils/estimate-usage';\nimport { SignalError, ErrorCode } from './errors';\nimport { providerRegistry, modelEntry, resolveApiKey, UNMEASURED_MODEL, type ModelEntry, type ProviderEntry } from './registry';\nimport { createOpenAICompatibleAdapter } from './adapters/openai-compatible.adapter';\nimport { createAnthropicAdapter } from './adapters/anthropic.adapter';\nimport { createGoogleAdapter } from './adapters/google.adapter';\nimport { createSystemOneAdapter } from './adapters/systemone.adapter';\nimport { assertQuestions, acceptCalibrated, acceptUncalibrated, uncalibratedSchemaOf } from './decide/gate';\nimport { decisionEmulationPrompt } from './transport/protocol';\nimport { executeStepStream } from './stream/execute-step-stream';\nimport { runComplete, runStream } from './run';\nimport { resolveWireStrategies, responseStrategies, recoverRejection, type WireStrategy } from './wire/strategies';\nimport { routeResponse, routeRejection } from './wire/router';\n\n// ═══════════════════════════════════════════════════════════\n// Signal Type (public interface)\n// ═══════════════════════════════════════════════════════════\n\nexport type Signal<T = string> = {\n // Builder methods — each returns a new Signal\n apiKey: (key: string) => Signal<T>;\n model: (model: string) => Signal<T>;\n systemPrompt: (prompt: string) => Signal<T>;\n history: (messages: Message[]) => Signal<T>;\n schema: <U>(schema: ZodType<U>) => Signal<U>;\n tools: (tools: Tool[]) => Signal<T>;\n retries: (count: number) => Signal<T>;\n options: (opts: SignalOptions) => Signal<T>;\n onRetry: (handler: (error: Error, attempt: number) => void) => Signal<T>;\n onToolCall: (handler: (name: string, args: unknown) => void) => Signal<T>;\n\n // Execution\n complete: (input: string | ContentPart[]) => Promise<SignalResult<T>>;\n stream: (input: string | ContentPart[], options?: StreamOptions) => AsyncIterable<StreamEvent<T>>;\n\n // describe(): what this client resolves to — provider, model,\n // effective capabilities. Never hits the network and never throws\n // for missing API keys. Orchestrators (cortex) use it to pick\n // output strategies; previews use it to explain themselves.\n describe: () => SignalDescription;\n\n // ─── Low-level primitives ─────────────────────────────────\n // step(): one model call, no auto tool execution. The caller\n // owns the loop. Used by @niscorp/cortex which runs its own\n // tool loop with policy gating, ledger attribution, and\n // observation per call.\n step: (request: StepRequest) => Promise<StepResult>;\n // stepStream(): the streaming variant of step(). Same single-call\n // semantics — no schema validation, no auto tool execution, no\n // retries — but yields text deltas incrementally and a final `done`\n // event carrying the aggregated StepResult. The caller still owns\n // the tool loop. Used by @niscorp/cortex when streaming is opted in.\n stepStream: (request: StepRequest, options?: StreamOptions) => AsyncIterable<StepStreamEvent>;\n // count(): rough token count for an input. Currently a heuristic;\n // will become provider-aware once tokenizer integration lands.\n count: (input: CountInput) => Promise<number>;\n\n // ─── Embedding ────────────────────────────────────────────\n embed: {\n (input: string, options?: EmbedOptions): Promise<number[]>;\n (input: string[], options?: EmbedOptions): Promise<number[][]>;\n };\n\n // ─── Decisions ────────────────────────────────────────────\n // decide(): typed questions about a state, each answered with a pick. One\n // request, one response — no history, no tools, no loop. The questions are\n // the schema: the result type and the acceptance gate both derive from them.\n // On a decision provider the picks come with probabilities\n // (`calibrated: true`); on a chat provider the same questions run through\n // structured output and come back as picks alone, one to two orders of\n // magnitude slower — a caller on a latency budget reads `describe().kind`.\n decide: <const Qs extends Questions>(request: DecideRequest<Qs>) => Promise<DecideResult<Qs>>;\n};\n\n// What a Signal client resolves to, without touching the network.\nexport type SignalDescription = {\n provider: string; // registry name, or the custom baseUrl\n model: string | undefined; // undefined only for custom providers with no model set\n // Which verbs exist here. A decision provider has decide() and nothing else;\n // a chat provider has every verb, decide() included, by emulation.\n kind: ProviderAdapter['kind'];\n capabilities: Capabilities;\n // Is (provider, model) a row in the model registry? False means the model\n // half of `capabilities` is UNMEASURED_MODEL — assumed, not measured. Always\n // false for a custom provider, which declares its own.\n modelKnown: boolean;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Internal: resolve provider config\n// ═══════════════════════════════════════════════════════════\n\ntype ResolvedProvider = {\n model: string;\n apiKey: string;\n baseUrl: string;\n adapterType: ProviderEntry['adapter'];\n // Per-provider params that ask for streamed reasoning (registry.ts). Carried\n // to the adapter, which applies them only on a streaming call the caller\n // asked reasoning of.\n reasoningRequest?: Record<string, unknown>;\n};\n\nconst resolveProvider = (config: SignalConfig): ResolvedProvider => {\n if (typeof config.provider === 'string') {\n const entry = providerRegistry[config.provider];\n if (!entry) throw new SignalError(`Unknown provider: ${config.provider}`, ErrorCode.PROVIDER_NOT_FOUND);\n const apiKey = resolveApiKey(entry.envKey, config.apiKey);\n if (!apiKey) throw new SignalError(`Missing API key for ${config.provider}. Set ${entry.envKey} or pass apiKey.`, ErrorCode.MISSING_API_KEY);\n return {\n model: config.model ?? entry.defaultModel,\n apiKey,\n baseUrl: entry.baseUrl,\n adapterType: entry.adapter,\n ...(entry.adapter !== 'systemone' && entry.reasoningRequest !== undefined && { reasoningRequest: entry.reasoningRequest }),\n };\n }\n\n const custom = config.provider;\n const apiKey = custom.apiKey ?? config.apiKey;\n if (!apiKey) throw new SignalError('Missing API key for custom provider', ErrorCode.MISSING_API_KEY);\n const model = config.model ?? custom.model;\n if (!model) throw new SignalError('Missing model for custom provider', ErrorCode.MISSING_MODEL);\n return { model, apiKey, baseUrl: custom.baseUrl, adapterType: custom.adapter ?? 'openai-compatible' };\n};\n\nconst FALLBACK_CAPABILITIES: Capabilities = {\n nativeTools: false,\n nativeJsonSchema: false,\n nativeJsonMode: false,\n toolsWithStructuredOutput: false,\n validatesToolArgs: false,\n manglesNestedToolArgs: false,\n multimodal: false,\n supportsEmbedding: false,\n};\n\n// The adapter a config names, without resolving a key — describe() and the\n// capability lookup both need it and neither may throw for a missing one.\nconst adapterTypeOf = (config: SignalConfig): ProviderEntry['adapter'] | undefined =>\n typeof config.provider === 'string'\n ? providerRegistry[config.provider]?.adapter\n : config.provider.adapter ?? 'openai-compatible';\n\nconst kindOf = (adapterType: ProviderEntry['adapter'] | undefined): ProviderAdapter['kind'] =>\n adapterType === 'systemone' ? 'decisions' : 'chat';\n\n// The model a registered provider's client runs, and its row if it has one.\nconst modelRowOf = (config: SignalConfig): { provider: string; model: string; row: ModelEntry | undefined } | undefined => {\n if (typeof config.provider !== 'string') return undefined;\n const entry = providerRegistry[config.provider];\n if (entry === undefined) return undefined;\n const model = config.model ?? entry.defaultModel;\n return { provider: config.provider, model, row: modelEntry(config.provider, model) };\n};\n\n// Chat capabilities: the provider's endpoint row JOINED with the model's row —\n// no field is on both, so nothing overrides anything. A model with no row gets\n// UNMEASURED_MODEL. A decision provider declares none because it has none, so\n// it resolves to the all-false floor.\nconst resolveCapabilities = (config: SignalConfig): Capabilities => {\n if (typeof config.provider === 'string') {\n const entry = providerRegistry[config.provider];\n if (entry === undefined || entry.adapter === 'systemone') return FALLBACK_CAPABILITIES;\n return { ...entry.endpoint, ...(modelRowOf(config)?.row?.capabilities ?? UNMEASURED_MODEL) };\n }\n const declared = config.provider.adapter === 'systemone' ? {} : config.provider.capabilities;\n return { ...FALLBACK_CAPABILITIES, ...declared };\n};\n\n// A reasoning effort the model's row does not list is refused HERE, when the\n// client is built — not by a provider 400 in the middle of a run. An unmeasured\n// model is not checked: nobody knows what it takes, and the provider will say.\nconst assertEffort = (config: SignalConfig, effort: ReasoningEffort | undefined): void => {\n if (effort === undefined) return;\n const resolved = modelRowOf(config);\n const row = resolved?.row;\n if (resolved === undefined || row === undefined || row.reasoningEfforts.includes(effort)) return;\n const accepted = row.reasoningEfforts.length === 0 ? 'nothing — it takes no reasoning effort' : row.reasoningEfforts.join(', ');\n throw new SignalError(\n `reasoningEffort \"${effort}\" is not accepted by ${resolved.provider} ${resolved.model} (accepts: ${accepted}; measured ${row.verified})`,\n ErrorCode.VALIDATION_FAILED,\n );\n};\n\nconst wireIdsOf = (config: SignalConfig): string[] => {\n const source = typeof config.provider === 'string' ? providerRegistry[config.provider] : config.provider;\n return source === undefined || source.adapter === 'systemone' ? [] : source.wire ?? [];\n};\n\nconst createAdapter = async (resolved: ResolvedProvider, client: unknown): Promise<ProviderAdapter> => {\n switch (resolved.adapterType) {\n case 'openai-compatible':\n return createOpenAICompatibleAdapter({ apiKey: resolved.apiKey, baseUrl: resolved.baseUrl, client, ...(resolved.reasoningRequest !== undefined && { reasoningRequest: resolved.reasoningRequest }) });\n case 'anthropic':\n return createAnthropicAdapter({ apiKey: resolved.apiKey, client });\n case 'google':\n return createGoogleAdapter({ apiKey: resolved.apiKey, client });\n case 'systemone':\n return createSystemOneAdapter({ apiKey: resolved.apiKey, baseUrl: resolved.baseUrl, client });\n }\n};\n\n// ═══════════════════════════════════════════════════════════\n// Internal: build message array from config + input\n// ═══════════════════════════════════════════════════════════\n\nconst buildMessages = (config: SignalConfig, input: string | ContentPart[]): Message[] => {\n const messages: Message[] = [];\n if (config.systemPrompt) messages.push({ role: 'system', content: config.systemPrompt });\n if (config.history) messages.push(...config.history);\n messages.push({ role: 'user', content: input });\n return messages;\n};\n\n// ═══════════════════════════════════════════════════════════\n// createSignal — factory function\n// ═══════════════════════════════════════════════════════════\n\n// Build a recovered StepResult from a provider rejection: the routed\n// view of the attempt the 400 carried. toolCalls is populated when the\n// rejection routes back to a declared tool, so transcripts pair the\n// call with its eventual tool message exactly like an accepted turn.\nconst recoveredStepResult = (\n recovered: { strategy: string; rejection: Rejection },\n routed: ReturnType<typeof routeRejection>,\n raw: unknown,\n sent: readonly Message[],\n): StepResult => ({\n content: '',\n toolCalls: routed.outcome.kind === 'tool_calls' ? routed.outcome.calls : [],\n // A rejected generation costs tokens — the provider processed the request and\n // billed for it — and the 400 body carries none. The prompt is known exactly\n // and the model's attempt is in the rejection, so this is countable rather\n // than lost. Marked unreported, because it is a reckoning.\n usage: estimateUsage(sent, recovered.rejection.argsText, routed.outcome.kind === 'tool_calls' ? routed.outcome.calls : []),\n finishReason: 'error_recovered',\n raw,\n outcome: routed.outcome,\n wire: {\n ...routed.wire,\n recovered: {\n strategy: recovered.strategy,\n ...(recovered.rejection.name !== undefined && { name: recovered.rejection.name }),\n truncated: recovered.rejection.truncated,\n },\n },\n});\n\nconst createSignalFromConfig = <T = string>(config: SignalConfig): Signal<T> => {\n // Adapter is lazily created and cached per provider config\n let cachedAdapter: ProviderAdapter | undefined;\n let cachedAdapterKey: string | undefined;\n\n // Provider wire strategies — data from the registry entry (or the\n // custom provider config), resolved once. Unknown ids throw here,\n // at construction, not mid-run.\n const wireStrategies: WireStrategy[] = resolveWireStrategies(wireIdsOf(config));\n\n // So is an effort the model does not take — every builder call re-runs this,\n // so `.model()` after `.options()` is checked against the model it lands on.\n assertEffort(config, config.options?.reasoningEffort);\n\n const getAdapter = async (): Promise<ProviderAdapter> => {\n const resolved = resolveProvider(config);\n const key = `${resolved.adapterType}:${resolved.baseUrl}:${resolved.apiKey}`;\n if (cachedAdapter && cachedAdapterKey === key) return cachedAdapter;\n cachedAdapter = await createAdapter(resolved, config.client);\n cachedAdapterKey = key;\n return cachedAdapter;\n };\n\n // The chat verbs on a decision provider fail HERE, by name, before any\n // request is built — the provider has no endpoint that could answer them.\n const getChatAdapter = async (verb: string): Promise<ChatAdapter> => {\n const adapter = await getAdapter();\n if (adapter.kind === 'chat') return adapter;\n throw new SignalError(\n `${verb}() is not available on a decision provider — it answers decide() and generates no text`,\n ErrorCode.VERB_NOT_SUPPORTED,\n { verb, adapter: adapter.id },\n );\n };\n\n const fork = <U = T>(override: Partial<SignalConfig>): Signal<U> =>\n createSignalFromConfig<U>({ ...config, ...override });\n\n // ─── step / stepStream — the ONE execution core ────────────\n // Everything above (complete/stream) is a wrapper over these, so the\n // wire layer serves every entry point identically.\n\n const step = async (request: StepRequest): Promise<StepResult> => {\n const adapter = await getChatAdapter('step');\n const resolved = resolveProvider(config);\n const messages = request.messages.slice() as Message[];\n const providerTools = request.tools && request.tools.length > 0\n ? request.tools.map((tool) => ({\n type: 'function' as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }))\n : undefined;\n const providerRequest: ProviderRequest = {\n model: resolved.model,\n messages,\n ...(providerTools && { tools: providerTools }),\n ...(request.toolChoice !== undefined && { toolChoice: request.toolChoice }),\n ...(request.responseFormat !== undefined && { responseFormat: request.responseFormat }),\n // The client's own options are the floor; a request may override them\n // field by field. `complete`/`stream` already run on config.options —\n // step used to drop them, so a configured client behaved differently\n // depending on which door the caller came through.\n ...((config.options !== undefined || request.options !== undefined) && {\n options: { ...config.options, ...request.options },\n }),\n };\n assertEffort(config, providerRequest.options?.reasoningEffort);\n const declared = new Set((request.tools ?? []).map((tool) => tool.name));\n let response: ProviderResponse;\n try {\n response = await adapter.chat(providerRequest);\n } catch (error) {\n // The wire layer: provider rejections that carry the model's\n // attempt are recovered by a registry-selected strategy and\n // ROUTED like any response. No strategy claims it → rethrow.\n const recovered = recoverRejection(wireStrategies, error);\n if (!recovered) throw error;\n const routed = routeRejection(recovered.rejection, {\n declared,\n ...(request.output && { accept: request.output.accept }),\n ...(request.output?.outputTool !== undefined && { outputTool: request.output.outputTool }),\n responseStrategies: responseStrategies(wireStrategies),\n });\n return recoveredStepResult(recovered, routed, error, providerRequest.messages);\n }\n const toolCalls: StepToolCall[] = (response.toolCalls ?? []).map((call) => {\n let parsed: unknown = call.args;\n if (typeof call.args === 'string') {\n try {\n parsed = JSON.parse(call.args);\n } catch {\n // Leave args as the raw string if it isn't valid JSON.\n parsed = call.args;\n }\n }\n return { id: call.id, name: call.name, args: parsed };\n });\n const result: StepResult = {\n content: response.content,\n toolCalls,\n // The non-streaming body always carries usage, so a zero here is a real\n // zero rather than a missing frame.\n usage: { ...response.usage, reported: true },\n finishReason: response.finishReason,\n raw: response.raw,\n };\n if (!request.output) return result;\n const routed = routeResponse({\n content: result.content,\n toolCalls: result.toolCalls,\n declared,\n accept: request.output.accept,\n ...(request.output.outputTool !== undefined && { outputTool: request.output.outputTool }),\n responseStrategies: responseStrategies(wireStrategies),\n });\n return { ...result, outcome: routed.outcome, wire: routed.wire };\n };\n\n const stepStream = (request: StepRequest, streamOptions?: StreamOptions): AsyncIterable<StepStreamEvent> => {\n const run = async function* (): AsyncGenerator<StepStreamEvent> {\n const adapter = await getChatAdapter('stepStream');\n const resolved = resolveProvider(config);\n const declared = new Set((request.tools ?? []).map((tool) => tool.name));\n // The client's own options are the floor here too — step() merges them and\n // stepStream must not diverge, or a configured client (reasoningEffort,\n // temperature, …) behaves differently depending on which door it came\n // through. This is the merge that carries reasoning_effort to the wire on\n // the streaming path cortex actually runs every turn through.\n const merged: StepRequest =\n config.options !== undefined || request.options !== undefined\n ? { ...request, options: { ...config.options, ...request.options } }\n : request;\n assertEffort(config, merged.options?.reasoningEffort);\n try {\n for await (const event of executeStepStream({\n adapter,\n model: resolved.model,\n request: merged,\n ...(streamOptions && { streamOptions }),\n })) {\n if (event.type === 'done' && request.output) {\n const routed = routeResponse({\n content: event.result.content,\n toolCalls: event.result.toolCalls,\n declared,\n accept: request.output.accept,\n ...(request.output.outputTool !== undefined && { outputTool: request.output.outputTool }),\n responseStrategies: responseStrategies(wireStrategies),\n });\n yield { type: 'done', result: { ...event.result, outcome: routed.outcome, wire: routed.wire } };\n continue;\n }\n yield event;\n }\n } catch (error) {\n // Rejections surface at stream creation OR mid-iteration (the\n // 400 lands on the first chunk read) — recover both here.\n const recovered = recoverRejection(wireStrategies, error);\n if (!recovered) throw error;\n const routed = routeRejection(recovered.rejection, {\n declared,\n ...(request.output && { accept: request.output.accept }),\n ...(request.output?.outputTool !== undefined && { outputTool: request.output.outputTool }),\n responseStrategies: responseStrategies(wireStrategies),\n });\n yield { type: 'done', result: recoveredStepResult(recovered, routed, error, request.messages) };\n }\n };\n return run();\n };\n\n // ─── decide — beside the execution core, not through it ────\n // A decision provider answers the questions itself and the gate checks the\n // answers against them. No wire strategy, repair or retry applies: there are\n // no bytes to repair and the model cannot be told what it got wrong.\n const decideCalibrated = async <Qs extends Questions>(\n adapter: DecisionAdapter,\n model: string,\n request: DecideRequest<Qs>,\n started: number,\n ): Promise<DecideResult<Qs>> => {\n const response = await adapter.decide(\n { model, state: request.state, questions: request.questions },\n request.options?.signal !== undefined ? { signal: request.options.signal } : undefined,\n );\n const decisions = acceptCalibrated(request.questions, response.answers, response.raw);\n const inputTokens = response.usage?.inputTokens ?? 0;\n const outputTokens = response.usage?.outputTokens ?? 0;\n return {\n calibrated: true,\n decisions,\n meta: {\n model: response.model ?? model,\n usage: { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens, reported: response.usage !== undefined },\n durationMs: Date.now() - started,\n provider: { raw: response.raw },\n },\n };\n };\n\n // A chat provider is asked the same questions through structured output: the\n // derived schema is the contract, so the whole complete() pipeline — native\n // grammar where it exists, the repair ladder, correction retries — serves it.\n // It returns picks and no probabilities; see DecideResult.\n const decideEmulated = async <Qs extends Questions>(\n model: string,\n request: DecideRequest<Qs>,\n started: number,\n ): Promise<DecideResult<Qs>> => {\n const state = typeof request.state === 'string' ? request.state : JSON.stringify(request.state);\n const result = await runComplete<unknown>(\n {\n messages: [{ role: 'user', content: decisionEmulationPrompt(state) }],\n schema: uncalibratedSchemaOf(request.questions),\n tools: undefined,\n retries: config.retries ?? 2,\n options: config.options,\n ...(request.options?.signal !== undefined && { streamOptions: { signal: request.options.signal } }),\n },\n { stepStream, model, capabilities: resolveCapabilities(config) },\n );\n return {\n calibrated: false,\n decisions: acceptUncalibrated(request.questions, result.response, result.meta.provider.raw),\n meta: {\n model: result.meta.model,\n // complete() sums what providers reported with what it had to estimate\n // and does not say which, so this total cannot be vouched for as measured.\n usage: { ...result.meta.usage, reported: false },\n durationMs: Date.now() - started,\n provider: { raw: result.meta.provider.raw },\n },\n };\n };\n\n return {\n // Builder methods\n apiKey: (key) => fork({ apiKey: key }),\n model: (m) => fork({ model: m }),\n systemPrompt: (prompt) => fork({ systemPrompt: prompt }),\n history: (msgs) => fork({ history: msgs }),\n schema: <U>(s: ZodType<U>) => fork<U>({ schema: s }),\n tools: (t) => fork({ tools: t }),\n retries: (count) => fork({ retries: count }),\n options: (opts) => fork({ options: { ...config.options, ...opts } }),\n onRetry: (handler) => fork({ onRetry: handler }),\n onToolCall: (handler) => fork({ onToolCall: handler }),\n\n describe: (): SignalDescription => {\n if (typeof config.provider === 'string') {\n const entry = providerRegistry[config.provider];\n return {\n provider: config.provider,\n model: config.model ?? entry?.defaultModel,\n kind: kindOf(adapterTypeOf(config)),\n capabilities: resolveCapabilities(config),\n modelKnown: modelRowOf(config)?.row !== undefined,\n };\n }\n return {\n provider: config.provider.baseUrl,\n model: config.model ?? config.provider.model,\n kind: kindOf(adapterTypeOf(config)),\n capabilities: resolveCapabilities(config),\n modelKnown: false,\n };\n },\n\n // Execution — thin wrappers over the step core (src/complete.ts).\n complete: async (input): Promise<SignalResult<T>> =>\n runComplete<T>(\n {\n messages: buildMessages(config, input),\n schema: config.schema,\n tools: config.tools,\n retries: config.retries ?? 2,\n options: config.options,\n onRetry: config.onRetry,\n onToolCall: config.onToolCall,\n },\n { stepStream, model: resolveProvider(config).model, capabilities: resolveCapabilities(config) },\n ),\n\n stream: (input, streamOptions) =>\n runStream<T>(\n {\n messages: buildMessages(config, input),\n schema: config.schema,\n tools: config.tools,\n retries: config.retries ?? 2,\n options: config.options,\n streamOptions,\n onRetry: config.onRetry,\n onToolCall: config.onToolCall,\n },\n { stepStream, model: resolveProvider(config).model, capabilities: resolveCapabilities(config) },\n ),\n\n // ─── Low-level primitives — the execution core itself ────\n step,\n stepStream,\n\n // ─── Embedding ────────────────────────────────────────────\n embed: (async (input: string | string[], options?: EmbedOptions): Promise<number[] | number[][]> => {\n const adapter = await getChatAdapter('embed');\n if (!adapter.embed) {\n throw new SignalError('This provider does not support embedding', ErrorCode.PROVIDER_ERROR);\n }\n const resolved = resolveProvider(config);\n const response = await adapter.embed({\n model: resolved.model,\n input,\n dimensions: options?.dimensions,\n });\n // The usage the adapter already parsed, handed back before the vector\n // return narrows it away. After success only — a throw above never reaches\n // here — and once for both the string and array shapes.\n options?.onUsage?.(response.usage, resolved.model);\n if (typeof input === 'string') {\n const vector = response.embeddings[0];\n if (!vector) throw new SignalError('No embedding returned', ErrorCode.PROVIDER_ERROR);\n return vector;\n }\n return response.embeddings;\n }) as Signal<T>['embed'],\n\n // ─── Decisions ────────────────────────────────────────────\n decide: async <const Qs extends Questions>(request: DecideRequest<Qs>): Promise<DecideResult<Qs>> => {\n assertQuestions(request.questions);\n const started = Date.now();\n const adapter = await getAdapter();\n const model = resolveProvider(config).model;\n return adapter.kind === 'decisions'\n ? decideCalibrated(adapter, model, request, started)\n : decideEmulated(model, request, started);\n },\n\n // ─── Low-level: token counting (heuristic) ───────────────\n count: async (input: CountInput): Promise<number> => {\n // Heuristic: ~4 characters per token, plus a small per-message\n // overhead for structured inputs. This will be replaced with a\n // provider-aware tokenizer in a follow-up.\n const CHARS_PER_TOKEN = 4;\n if (typeof input === 'string') {\n return Math.ceil(input.length / CHARS_PER_TOKEN);\n }\n let total = 0;\n for (const msg of input) {\n total += 4; // per-message overhead\n if (typeof msg.content === 'string') {\n total += Math.ceil(msg.content.length / CHARS_PER_TOKEN);\n continue;\n }\n for (const part of msg.content) {\n if (part.type === 'text') {\n total += Math.ceil(part.text.length / CHARS_PER_TOKEN);\n } else {\n // Image: rough placeholder.\n total += 256;\n }\n }\n }\n return total;\n },\n };\n};\n\nexport const createSignal = (\n provider: string | CustomProviderConfig,\n options?: Partial<Omit<SignalConfig, 'provider'>>,\n): Signal<string> =>\n createSignalFromConfig<string>({ provider, ...options });\n","import type { z } from 'zod';\nimport type { Tool, ToolConfig } from '../types';\n\nexport const defineTool = <TInput>(config: ToolConfig<TInput>): Tool => ({\n name: config.name,\n description: config.description,\n inputSchema: config.input as z.ZodType,\n execute: config.execute as (input: unknown) => Promise<unknown> | unknown,\n});\n","import type { ZodType } from 'zod';\nimport type { Capabilities, ResponseFormat, StepToolDescriptor } from '../types';\nimport { SignalError, ErrorCode } from '../errors';\nimport { RESPOND_DESCRIPTION, corrections, finishProtocol, type ProtocolSpec } from './protocol';\n\n// ═══════════════════════════════════════════════════════════\n// Transport resolution — which channel carries the caller's output\n// ═══════════════════════════════════════════════════════════\n//\n// Signal's contract is \"what comes out conforms to the schema that\n// went in\"; the transport is HOW signal keeps that promise on this\n// provider. Callers (cortex) describe their output contract once and\n// stay provider-blind — they never learn which transport ran except\n// as reporting.\n//\n// respond — a synthetic exit tool; the output rides its arguments.\n// native — provider grammar (response_format: json_schema).\n// emit — the content channel; the completion IS the output.\n// The floor: every model can do it, so `auto` lands here\n// whenever neither of the others ENFORCES anything.\n//\n// Resolution is a PURE function of the spec and the capabilities:\n// no client, no network — previews resolve exactly like runs.\n\nexport type OutputTransport = 'respond' | 'native' | 'emit';\n\nexport type ResponseMode = 'required' | 'optional';\n\nexport type TransportSpec = {\n // The full wire schema of the output contract (what the model must\n // produce). Used for grammar / tool params when viable; NEVER sent\n // to hard-validating providers.\n wire: ZodType;\n // Loose variant (payload fields untyped) for large or recursive\n // contracts whose real schema rides prompt documentation.\n looseWire: ZodType;\n responseMode: ResponseMode;\n // Does the contract carry a typed payload (a `data` field)?\n hasData: boolean;\n hasTools: boolean;\n // Explicit transport override; 'auto' resolves from capabilities.\n choice?: 'auto' | OutputTransport;\n // Force every turn to be a tool call ('respond' transport only).\n forceTool?: boolean;\n};\n\nexport type ResolvedTransport = {\n transport: OutputTransport;\n responseMode: ResponseMode;\n // respond: how much of the contract went into the tool params.\n // 'permissive' = the provider validates tool args server-side; the\n // wire params constrain nothing and the contract rides prompt docs.\n respondDetail?: 'full' | 'loose' | 'permissive';\n // respond: the synthetic exit tool to append to the request. NOT a\n // domain tool — the router treats its calls as output attempts.\n respondDescriptor?: StepToolDescriptor;\n // The exit tool's name when one exists (delta attribution: callers\n // stream its argument fragments as output partials).\n outputToolName?: string;\n // native: sent on every request.\n responseFormat?: ResponseFormat;\n // 'required' when forceTool hardening is on.\n toolChoice?: 'required';\n // Should the caller inject its own schema documentation as prompt\n // context? (True whenever the wire contract is not fully carried by\n // the transport itself.)\n injectSchemaDoc: boolean;\n // ONE transport-owned system chunk stating how the run ends. Callers\n // inject it verbatim as the last prompt chunk — they never author\n // finish instructions (they cannot know which transport resolved).\n finishProtocol: string;\n // Correction texts, phrased for this transport. {issues} is replaced\n // by the caller with the concrete evidence.\n corrections: { termination: string; invalidOutput: string };\n};\n\nexport const RESPOND_TOOL_NAME = 'respond';\n\n// Serialized-schema analysis for the full-vs-loose decision. `full`\n// requires: serializes cleanly, no $ref (recursion / shared defs),\n// and small enough not to bloat every request.\nconst FULL_PARAMS_MAX_CHARS = 8_192;\n\ntype SchemaAnalysis = { serialized: Record<string, unknown> | null; hasRef: boolean; size: number };\n\nconst analyzeWireSchema = (schema: ZodType): SchemaAnalysis => {\n try {\n const serialized = schema['~standard'].jsonSchema.output({ target: 'draft-07' });\n const text = JSON.stringify(serialized);\n return { serialized, hasRef: text.includes('\"$ref\"'), size: text.length };\n } catch {\n return { serialized: null, hasRef: false, size: Number.POSITIVE_INFINITY };\n }\n};\n\n// Converted by the schema's OWN zod (Standard JSON Schema), never by ours: the\n// caller's schema may come from another zod copy, and converting it here would\n// read that copy's metadata through our registry. `output` matches the\n// z.toJSONSchema default.\nconst toJsonSchemaRecord = (schema: ZodType): Record<string, unknown> => {\n const convert = schema['~standard'].jsonSchema.output;\n try {\n return convert({ target: 'draft-07' });\n } catch {\n return convert({ target: 'draft-07', libraryOptions: { unrepresentable: 'any' } });\n }\n};\n\n// ───────────────────────────────────────────────────────────\n// resolveTransport\n// ───────────────────────────────────────────────────────────\n\n// The exit tool's params by provider temperament. Hard-validating\n// providers (validatesToolArgs) 400 the WHOLE request when args miss\n// the declared schema — killing exactly the attempts the wire layer's\n// repair ladder saves. There the params name the envelope fields but\n// constrain nothing (never advertising a field the contract doesn't\n// accept); the contract rides prompt docs, validation is client-side.\nconst respondParams = (\n spec: TransportSpec,\n caps: Capabilities,\n analysis: SchemaAnalysis,\n fullIsViable: boolean,\n): { detail: 'full' | 'loose' | 'permissive'; parameters: Record<string, unknown> } => {\n if (caps.validatesToolArgs) {\n return {\n detail: 'permissive',\n parameters: {\n type: 'object',\n properties: spec.hasData ? { response: {}, data: {}, reasoning: {} } : { response: {}, reasoning: {} },\n },\n };\n }\n if (!spec.hasData || fullIsViable) {\n return { detail: 'full', parameters: analysis.serialized ?? toJsonSchemaRecord(spec.wire) };\n }\n return { detail: 'loose', parameters: toJsonSchemaRecord(spec.looseWire) };\n};\n\nconst protocolSpec = (transport: OutputTransport, spec: TransportSpec, injectSchemaDoc: boolean): ProtocolSpec => ({\n transport,\n responseMode: spec.responseMode,\n hasData: spec.hasData,\n hasTools: spec.hasTools,\n injectSchemaDoc,\n});\n\nexport const resolveTransport = (spec: TransportSpec, caps: Capabilities): ResolvedTransport => {\n const analysis = analyzeWireSchema(spec.wire);\n const fullIsViable = analysis.serialized !== null && !analysis.hasRef && analysis.size <= FULL_PARAMS_MAX_CHARS;\n\n const nativeIsViable = caps.nativeJsonSchema && fullIsViable && (!spec.hasTools || caps.toolsWithStructuredOutput);\n\n const choice = spec.choice ?? 'auto';\n if (choice === 'native' && !nativeIsViable) {\n throw new SignalError(\n spec.hasTools && !caps.toolsWithStructuredOutput\n ? 'transport \"native\" needs a provider that combines tools with response_format (capabilities.toolsWithStructuredOutput)'\n : 'transport \"native\" needs capabilities.nativeJsonSchema and a wire schema that serializes small and non-recursive',\n ErrorCode.VALIDATION_FAILED,\n );\n }\n\n // `respond` EARNS ITS PLACE ONLY WHEN ITS TOOL PARAMS ENFORCE THE CONTRACT.\n // That takes three things: the provider does not validate tool args itself\n // (if it does, the params are sent permissive and enforce nothing), the full\n // schema fits in the params (loose params enforce nothing either), and the\n // model carries nested payloads on the tool channel intact. Anywhere else\n // `respond` would add a synthetic tool and a tool-call ending for no\n // enforcement at all — the contract would ride the prompt exactly as it does\n // under `emit`, which every model can do.\n //\n // auto: native (grammar) → respond (enforcing params) → emit\n //\n // Explicit respond/native choices are still honored, and `forceTool` —\n // \"every turn is a tool call, `respond` is the only exit\" — is a choice of\n // `respond` in all but name.\n const respondEnforces = !caps.validatesToolArgs && !caps.manglesNestedToolArgs && (!spec.hasData || fullIsViable);\n\n let transport: OutputTransport;\n if (choice !== 'auto') transport = choice;\n else if (nativeIsViable && spec.hasData) transport = 'native';\n else if (respondEnforces || spec.forceTool) transport = 'respond';\n else transport = 'emit';\n\n if (transport === 'emit' && spec.forceTool) {\n throw new SignalError(\n 'output.forceTool cannot combine with the emit transport — the final turn must be a content-only message',\n ErrorCode.VALIDATION_FAILED,\n );\n }\n\n if (transport === 'native') {\n const serialized = analysis.serialized ?? toJsonSchemaRecord(spec.wire);\n const injectSchemaDoc = false;\n return {\n transport,\n responseMode: spec.responseMode,\n responseFormat: {\n type: 'json_schema',\n // strict:false — strict mode rejects open records and several\n // keywords; non-strict still constrains and never hard-fails.\n jsonSchema: { name: 'envelope', strict: false, schema: serialized },\n },\n injectSchemaDoc,\n finishProtocol: finishProtocol(protocolSpec(transport, spec, injectSchemaDoc)),\n corrections: corrections(transport),\n };\n }\n\n if (transport === 'emit') {\n const injectSchemaDoc = spec.hasData;\n return {\n transport,\n responseMode: spec.responseMode,\n injectSchemaDoc,\n finishProtocol: finishProtocol(protocolSpec(transport, spec, injectSchemaDoc)),\n corrections: corrections(transport),\n };\n }\n\n const { detail: respondDetail, parameters } = respondParams(spec, caps, analysis, fullIsViable);\n const injectSchemaDoc = spec.hasData && respondDetail !== 'full';\n return {\n transport,\n responseMode: spec.responseMode,\n respondDetail,\n respondDescriptor: { name: RESPOND_TOOL_NAME, description: RESPOND_DESCRIPTION, parameters },\n outputToolName: RESPOND_TOOL_NAME,\n ...(spec.forceTool && { toolChoice: 'required' as const }),\n injectSchemaDoc,\n finishProtocol: finishProtocol(protocolSpec(transport, spec, injectSchemaDoc)),\n corrections: corrections(transport),\n };\n};\n","import type { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════\n// Messages\n// ═══════════════════════════════════════════════════════════\n\nexport type ImageSource =\n | { type: 'url'; url: string }\n | { type: 'base64'; mediaType: string; data: string };\n\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; source: ImageSource };\n\n// A tool call attached to an assistant message. Mirrors the OpenAI\n// chat-completion `tool_calls` shape: each call has an id (used to\n// reference back from a later 'tool' message), the function name,\n// and a JSON-stringified arguments payload.\nexport type AssistantToolCall = {\n id: string;\n name: string;\n // OpenAI-format tool calls carry arguments as a JSON string. We\n // keep that contract so adapters can pass them straight through\n // without re-stringifying.\n args: string;\n};\n\nexport type Message =\n | { role: 'system'; content: string }\n | { role: 'user'; content: string | ContentPart[] }\n // Assistant messages may carry tool calls when the model wants to\n // invoke tools. Both `content` and `toolCalls` are present together\n // when the model returns text alongside tool calls; tool-call-only\n // turns have empty content but a non-empty toolCalls array.\n | { role: 'assistant'; content: string; toolCalls?: AssistantToolCall[] }\n | { role: 'tool'; toolCallId: string; name: string; content: string };\n\n// ═══════════════════════════════════════════════════════════\n// Tool Types\n// ═══════════════════════════════════════════════════════════\n\nexport type ToolConfig<TInput = unknown> = {\n name: string;\n description: string;\n input: z.ZodType<TInput>;\n execute: (input: TInput) => Promise<unknown> | unknown;\n};\n\nexport type Tool = {\n name: string;\n description: string;\n inputSchema: z.ZodType;\n execute: (input: unknown) => Promise<unknown> | unknown;\n};\n\nexport type ToolCallRecord = {\n name: string;\n args: unknown;\n result: unknown;\n durationMs: number;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Capabilities\n// ═══════════════════════════════════════════════════════════\n\n// Two owners, two types. What the ENDPOINT does holds for every model behind\n// it and lives on the provider's registry row; what the MODEL does is measured\n// per model (scripts/probe-model.ts) and lives on the model's row. A client's\n// `Capabilities` is the two joined — they share no field, so neither overrides\n// the other.\n\nexport type EndpointCapabilities = {\n nativeTools: boolean;\n nativeJsonMode: boolean;\n // Does the provider validate tool-call arguments SERVER-SIDE against\n // the declared `parameters` schema and 400 the whole request on a\n // mismatch (Groq's tool_use_failed)? When true, tool params cannot\n // enforce a contract — they are sent permissive and validation is\n // client-side — so the `respond` transport has nothing to offer there.\n validatesToolArgs: boolean;\n supportsEmbedding: boolean;\n};\n\nexport type ModelCapabilities = {\n // Does the model answer `response_format: json_schema` (strict:false, as\n // signal's `native` sends it) with content that fits the schema?\n nativeJsonSchema: boolean;\n // Is `response_format` accepted with `tools` in ONE request for this model?\n // Per model: Groq refuses it outright, OpenRouter depends on the route.\n toolsWithStructuredOutput: boolean;\n // Does the model corrupt STRUCTURED tool-call arguments? Measured on\n // Groq gpt-oss-120b: nested arrays inside function args arrive\n // JSON-STRINGIFIED (`\"children\": \"[{\\\"component\\\":...\"`). A model that\n // mangles never carries its output on the tool channel (`respond`).\n manglesNestedToolArgs: boolean;\n multimodal: boolean;\n};\n\nexport type Capabilities = EndpointCapabilities & ModelCapabilities;\n\n// Every `reasoning_effort` value a provider has been seen to accept. `none` and\n// `default` are Qwen's on Groq; `minimal`…`max` are OpenAI's and OpenRouter's.\n// WHICH of these a given model takes is its registry row's `reasoningEfforts`.\nexport const REASONING_EFFORTS = ['none', 'default', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type ReasoningEffort = (typeof REASONING_EFFORTS)[number];\n\n// ═══════════════════════════════════════════════════════════\n// Options (rarely set)\n// ═══════════════════════════════════════════════════════════\n\nexport type SignalOptions = {\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n stopSequences?: string[];\n seed?: number;\n signal?: AbortSignal;\n // How hard a REASONING model thinks before it answers — sent as-is as\n // `reasoning_effort`. The scale is the provider's, not ours, so the union is\n // the union of what providers accept. For a model in the registry, a value its\n // row does not list is refused when the client is built, not by a 400 mid-run;\n // for an unmeasured model it is sent unchecked.\n reasoningEffort?: ReasoningEffort;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Result\n// ═══════════════════════════════════════════════════════════\n\nexport type ProviderError = {\n code: string;\n message: string;\n recovered: boolean;\n raw?: unknown;\n};\n\nexport type SignalMeta = {\n model: string;\n usage: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n };\n durationMs: number;\n retries: number;\n toolCalls: ToolCallRecord[];\n provider: {\n raw: unknown;\n errors: ProviderError[];\n };\n};\n\nexport type SignalResult<T> = {\n response: T;\n history: Message[];\n meta: SignalMeta;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Step API — single model call, no auto tool execution\n// ═══════════════════════════════════════════════════════════\n//\n// Used by callers (notably @niscorp/cortex) that want to own the\n// tool loop themselves. signal.step() runs ONE adapter call and\n// returns the model's raw output, including any tool calls the\n// model wants to make. The caller is responsible for executing\n// tool calls and feeding results back via subsequent step() calls.\n\nexport type StepToolCall = {\n id: string;\n name: string;\n // Parsed JSON object — Signal converts the provider's stringified\n // arguments into a typed value before returning. Callers should\n // still validate against their tool's input schema.\n args: unknown;\n};\n\nexport type StepInputMessage =\n | Message\n | {\n role: 'tool';\n toolCallId: string;\n name: string;\n content: string;\n };\n\n// ═══════════════════════════════════════════════════════════\n// Wire contract — the routed view of one model response\n// ═══════════════════════════════════════════════════════════\n//\n// Signal's contract is \"what comes out conforms to the schema that\n// went in\". Every response (and every recovered provider rejection)\n// is normalized by the wire layer (src/wire) and ROUTED: a call\n// matching a declared tool is a tool call; anything else whose\n// repaired value validates against the acceptance schema is output;\n// what survives neither is a typed failure with evidence.\n\n// A provider rejected the model's emission; a recovery entry pulled\n// what it could from the error body.\nexport type Rejection = {\n // Tool name, when the attempt parsed (possibly after closing a\n // truncated body) as a { name, arguments } call.\n name?: string;\n // Parsed arguments, when parseable.\n args?: unknown;\n // The raw recovered bytes — always present, may be ''.\n argsText: string;\n // The recovered bytes ended mid-structure.\n truncated: boolean;\n};\n\nexport type StepOutcome =\n | { kind: 'tool_calls'; calls: StepToolCall[] }\n // value is the RAW accepted candidate, not the schema-transformed\n // parse: the acceptance schema is a GATE (a transport concern —\n // \"is this a real attempt\"), semantics stay the caller's.\n | { kind: 'output'; value: unknown }\n | { kind: 'failed'; evidence: string; truncated?: boolean };\n\n// How the outcome came to be — evidence for events/telemetry, and how\n// dead-weight recovery entries get found.\nexport type WireReport = {\n // The ladder rung or recovery entry that produced the accepted\n // candidate ('parse' when nothing had to be repaired).\n rung?: string;\n // An error-hook recovery entry recovered a provider rejection.\n recovered?: { strategy: string; name?: string; truncated: boolean };\n notes?: string[];\n};\n\n// A tool descriptor for step(). Note: NO `execute` field — step() never\n// runs tools, it only describes them to the model. The caller owns the\n// loop and is responsible for executing whatever the model asks for.\nexport type StepToolDescriptor = {\n name: string;\n description: string;\n // JSON Schema for the tool's input. Use z.toJSONSchema() if you have\n // a Zod schema; pass any draft-07-compatible object otherwise.\n parameters: Record<string, unknown>;\n};\n\n// Response-format constraint passed through to the provider. Shared by\n// StepRequest (caller-facing) and ProviderRequest (adapter-facing).\nexport type ResponseFormat =\n | {\n type: 'json_schema';\n jsonSchema: { name: string; strict: boolean; schema: Record<string, unknown> };\n }\n | { type: 'json_object' };\n\nexport type StepRequest = {\n messages: ReadonlyArray<StepInputMessage>;\n tools?: ReadonlyArray<StepToolDescriptor>;\n // Force tool selection. 'auto' (default), 'none', 'required' (the model\n // MUST call some tool this turn), or a specific tool name.\n toolChoice?: 'auto' | 'none' | 'required' | { name: string };\n // Routing acceptance. When set, signal NORMALIZES the response\n // (solid's repair ladder, provider wire strategies — all rescue-only\n // and gated by this schema) and ROUTES it: StepResult.outcome says\n // whether the turn is tool calls, a final output that validates, or\n // a typed failure with evidence. The schema is a GATE, not a\n // transform — outcome.value is the raw accepted candidate. Provider\n // rejections that carry the attempt (Groq failed_generation) are\n // recovered and routed the same way: a rejected call to a DECLARED\n // tool comes back as a normal tool call. `outputTool` names the\n // synthetic exit tool (respond transport) whose calls are OUTPUT,\n // never tool calls.\n output?: { accept: z.ZodType; outputTool?: string };\n // Provider-native response format (json_schema / json_object), passed\n // through verbatim. Check Capabilities.toolsWithStructuredOutput before\n // combining with `tools` — providers that can't combine reject the request.\n responseFormat?: ResponseFormat;\n options?: SignalOptions;\n};\n\nexport type StepResult = {\n content: string;\n toolCalls: StepToolCall[];\n // What the call cost, AS THE PROVIDER REPORTED IT. Zero means the provider\n // said zero; `reported: false` means it said nothing at all, which is a\n // different fact and must not be summed as if it were free.\n //\n // OpenAI-compatible streams send the usage frame after the last content\n // chunk and are not reliable about it — the same provider that emits it\n // twice on one call omits it on the next. A consumer that cannot tell the\n // two apart reports an agent as costing nothing.\n usage: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n reported: boolean;\n };\n finishReason: string;\n raw: unknown;\n // The routed view (present when the request carried output.accept,\n // and always on recovered provider rejections). Consumers should\n // switch on this instead of parsing content/toolCalls themselves.\n outcome?: StepOutcome;\n // How the outcome came to be (repair rung, recovery entry).\n wire?: WireReport;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Token counting\n// ═══════════════════════════════════════════════════════════\n\nexport type CountInput = string | ReadonlyArray<StepInputMessage>;\n\n// ═══════════════════════════════════════════════════════════\n// Embedding\n// ═══════════════════════════════════════════════════════════\n\nexport type EmbedOptions = {\n dimensions?: number;\n // Per-call usage sink — a sibling of `dimensions`, not one of the builder's\n // persistent handlers (onRetry/onToolCall). The provider reports embedding\n // usage on every call and the adapter parses it (EmbedResponse.usage), but\n // `embed`'s whole ergonomic is vector-in/vector-out, so the number has\n // nowhere to ride the return without breaking every caller. This hands it\n // back instead: invoked after a successful call with the adapter's usage and\n // the model that actually resolved (registry defaults mean the caller may not\n // know which). A caller that meters model spend measures the embed exactly\n // rather than re-counting it as a ~4-char/token guess. Not called when the\n // adapter throws — there was no usage.\n onUsage?: (usage: { inputTokens: number; totalTokens: number }, model: string) => void;\n};\n\nexport type EmbedRequest = {\n model: string;\n input: string | string[];\n dimensions?: number;\n};\n\nexport type EmbedResponse = {\n embeddings: number[][];\n usage: {\n inputTokens: number;\n totalTokens: number;\n };\n};\n\n// ═══════════════════════════════════════════════════════════\n// Decisions\n// ═══════════════════════════════════════════════════════════\n//\n// A decision model takes a state and typed questions and answers each with a\n// value and a probability distribution. It generates no text, so none of the\n// chat contract applies: no messages, no history, no tools, no finish reason,\n// no repair. The questions ARE the schema — the result type and the runtime\n// acceptance gate are both derived from them, and the caller never writes an\n// output type.\n\n// One of the listed options. `criteria` maps each option to what it means.\nexport type ChoiceQuestion<K extends string = string> = {\n type: 'choice';\n instructions: string;\n criteria: Record<K, string>;\n};\n\n// A level on an ordered rubric. `criteria` describes each level, lowest first;\n// level 0 is the first entry.\nexport type ScoreQuestion = {\n type: 'score';\n instructions: string;\n criteria: readonly string[];\n};\n\n// A yes/no, answered as the probability of yes.\nexport type NoulQuestion = {\n type: 'noul';\n instructions: string;\n criteria?: { true: string; false: string };\n};\n\nexport type Question = ChoiceQuestion | ScoreQuestion | NoulQuestion;\nexport type Questions = Record<string, Question>;\n\nexport type DecideState = string | Record<string, unknown> | readonly unknown[];\n\n// What every answer carries, whoever gave it: the pick itself.\nexport type UncalibratedDecision<Q extends Question> =\n Q extends ChoiceQuestion<infer K> ? { choice: K }\n : Q extends ScoreQuestion ? { level: number }\n : { answer: boolean };\n\n// What only a decision model adds: how sure it is. `level` is the most probable\n// level and `score` the probability-weighted one (1.05 sits just above level 1);\n// `answer` is `noul >= 0.5`.\nexport type CalibratedDecision<Q extends Question> =\n Q extends ChoiceQuestion<infer K> ? { choice: K; probabilities: Record<K, number>; confidence: number }\n : Q extends ScoreQuestion ? { level: number; score: number; probabilities: number[]; confidence: number }\n : { answer: boolean; noul: number };\n\nexport type DecideRequest<Qs extends Questions> = {\n state: DecideState;\n questions: Qs;\n options?: { signal?: AbortSignal };\n};\n\nexport type DecideMeta = {\n model: string;\n usage: { inputTokens: number; outputTokens: number; totalTokens: number; reported: boolean };\n durationMs: number;\n provider: { raw: unknown };\n};\n\n// `calibrated` is the discriminant, not a note in `meta`: a text model asked the\n// same questions returns picks and no probabilities, and a fabricated 1.0 would\n// clear every caller's threshold. The probabilities exist in the type only on\n// the branch where a model actually produced them.\nexport type DecideResult<Qs extends Questions> =\n | { calibrated: true; decisions: { [N in keyof Qs]: CalibratedDecision<Qs[N]> }; meta: DecideMeta }\n | { calibrated: false; decisions: { [N in keyof Qs]: UncalibratedDecision<Qs[N]> }; meta: DecideMeta };\n\n// ═══════════════════════════════════════════════════════════\n// Stream Events (emitted by signal.stream())\n// ═══════════════════════════════════════════════════════════\n\nexport type StreamEvent<T> =\n | { type: 'text'; text: string }\n | { type: 'tool_start'; name: string; args: unknown }\n | { type: 'tool_end'; name: string; result: unknown }\n | { type: 'retry'; reason: string; attempt: number }\n | { type: 'error'; error: Error; recovered: boolean }\n | { type: 'done'; response: T; history: Message[]; meta: SignalMeta };\n\n// Step-stream events — emitted by signal.stepStream(). Narrower than\n// StreamEvent because step-level streaming does one adapter call and\n// does not execute tools or handle schema retries. Text deltas and\n// tool-call argument fragments are emitted incrementally; tool calls\n// are ALSO delivered fully assembled on the final `done` event as part\n// of the StepResult. `tool_call_delta` is what makes progressive\n// parsing of function-call payloads possible (cortex → solid).\nexport type StepStreamEvent =\n | { type: 'text'; text: string }\n // The model's THINKING, streamed separately from its answer. Passed through\n // untouched — never folded into StepResult.content — so a caller can show the\n // reasoning in flight and keep it out of the output. Only providers that\n // stream it (and are asked, where asking is needed) produce these.\n | { type: 'reasoning'; text: string }\n | { type: 'tool_call_delta'; index: number; id?: string; name?: string; argsText: string }\n | { type: 'done'; result: StepResult };\n\n// ═══════════════════════════════════════════════════════════\n// Stream options\n// ═══════════════════════════════════════════════════════════\n\nexport type StreamOptions = {\n signal?: AbortSignal;\n};\n\n// ═══════════════════════════════════════════════════════════\n// Provider Stream Deltas (normalized adapter output)\n// ═══════════════════════════════════════════════════════════\n\nexport type ProviderStreamDelta =\n | { type: 'text'; text: string }\n // Reasoning tokens, from `choice.delta.reasoning` or `.reasoning_content`\n // depending on the provider. Normalized to one shape here.\n | { type: 'reasoning'; text: string }\n | { type: 'tool_call'; index: number; id?: string; name?: string; argsFragment?: string }\n | { type: 'usage'; inputTokens: number; outputTokens: number; totalTokens: number }\n | { type: 'finish'; finishReason: string };\n\n// ═══════════════════════════════════════════════════════════\n// Provider Adapter Interface\n// ═══════════════════════════════════════════════════════════\n\nexport type ProviderRequest = {\n model: string;\n messages: Message[];\n responseFormat?: ResponseFormat;\n tools?: Array<{\n type: 'function';\n function: { name: string; description: string; parameters: Record<string, unknown> };\n }>;\n toolChoice?: 'auto' | 'none' | 'required' | { name: string };\n options?: SignalOptions;\n};\n\nexport type ProviderResponse = {\n content: string;\n toolCalls?: Array<{\n id: string;\n name: string;\n args: string;\n }>;\n usage: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n };\n finishReason: string;\n raw: unknown;\n};\n\n// An adapter is one of two KINDS, and the kind is the whole truth about which\n// verbs a provider has. A chat provider generates text; a decision provider\n// answers typed questions and generates none. They share no method, so they\n// share no shape: a decision adapter carrying a `chat` that throws would be an\n// adapter lying about what it is, and every caller would find out at run time.\nexport type ChatAdapter = {\n kind: 'chat';\n id: string;\n chat: (request: ProviderRequest) => Promise<ProviderResponse>;\n // `options.signal`, when given, is handed to the underlying fetch so an abort\n // tears down the HTTP request itself — not just the delta loop above it. An\n // adapter that does not forward it simply keeps aborting between deltas.\n chatStream: (request: ProviderRequest, options?: { signal?: AbortSignal }) => AsyncIterable<ProviderStreamDelta>;\n embed?: (request: EmbedRequest) => Promise<EmbedResponse>;\n};\n\nexport type DecisionAdapter = {\n kind: 'decisions';\n id: string;\n decide: (request: DecisionRequest, options?: { signal?: AbortSignal }) => Promise<DecisionResponse>;\n};\n\nexport type ProviderAdapter = ChatAdapter | DecisionAdapter;\n\n// What a decision adapter is handed and what it hands back. The adapter moves\n// bytes: `answers` is the provider's body as it arrived, unvalidated — the\n// acceptance gate (decide/gate.ts) is what decides whether it counts.\nexport type DecisionRequest = {\n model: string;\n state: DecideState;\n questions: Questions;\n};\n\nexport type DecisionResponse = {\n model?: string;\n answers: unknown;\n usage?: { inputTokens: number; outputTokens: number };\n raw: unknown;\n};\n"]}
|