Artifact 101188067231503eb75a858b1ede1e11c0cac00b3368d57f7c2e73cd6e0c8887:
- File
docs/provider-contracts.md
— part of check-in
[11f47eadde]
at
2026-11-18 11:58:22
on branch trunk
— Record S0/S1 qualification groundwork before product code
Contract maps and pinned Pi reference, local C qualification fixtures, MC/DC and Fil-C remote lifecycle tooling, and the context transaction substrate probe. No product harness code yet. (user: dmestas, size: 9462) [annotate] [blame] [check-ins using]
# Provider and message contracts First-pass reference map at Pi commit `cead615b48b80d1c61eecab2f0b576d16eeaf4c5`. This maps observed Pi behavior, not a promise that every provider supports every capability. Evidence labels: **T** = exported types/comments, **I** = implementation read, **R** = test assertions read. No upstream tests were executed. C consequences are proposals, not implemented behavior. ## Message and streaming boundary | ID | Observed contract | Evidence | Consequence for a native C harness | |---|---|---|---| | P01 | Messages distinguish system, user, assistant, and tool result; assistant blocks preserve text, reasoning, and tool calls. | T: [message types](../reference/pi/packages/ai/src/types.ts#L424), [message union](../reference/pi/packages/ai/src/types.ts#L667). | Tagged records, not flattened text. Persist original structured blocks separately from the redacted context archive. | | P02 | Reasoning signatures, redaction markers, tool-call thought signatures, text signatures, namespaces, and response IDs carry provider-specific continuation information. | T: [block metadata](../reference/pi/packages/ai/src/types.ts#L430), [assistant metadata](../reference/pi/packages/ai/src/types.ts#L593). | Preserve opaque fields without interpreting or rewriting them; version their encoding. Do not equate search snippets with replayable history. | | P03 | Successful streams start before updates and finish with `done`; setup failures can emit `error` without a start. Post-start failures also finish with error. | T: [event protocol](../reference/pi/packages/ai/src/types.ts#L815). | Explicit stream states; handle failure before admission of any response block and failure after partial content. | | P04 | `partial` is a shared live helper, not an event-time snapshot. Text/thinking starts are normally empty; end events are authoritative; redacted reasoning may be complete at start. | T: [partial ownership and ordering](../reference/pi/packages/ai/src/types.ts#L824). | Define buffer lifetimes explicitly. Consumers must not retain borrowed pointers after mutation/reallocation. Durable clients need committed deltas or owned snapshots, not borrowed parser state. | | P05 | The event queue drains FIFO, ignores pushes after completion, drains buffered events after end, and wakes waiting consumers on end. Multiple iterators compete for events; this is not a broadcast subscription API. | I: [queue and stream](../reference/pi/packages/ai/src/utils/event-stream.ts#L25). R: [ordering and termination](../reference/pi/packages/ai/test/event-stream.test.ts#L6). | Separate single-consumer provider parsing from multi-client durable observation. Define backpressure and memory limits explicitly; do not assume Pi's queue is bounded. | | P06 | Partial tool arguments grow during streaming; final arguments must match the complete call. Upstream guards allocation growth and release of parser/partial state. | R: [streaming, allocation, and lifetime assertions](../reference/pi/packages/ai/test/streaming-tool-arguments.test.ts#L340). | Incremental parsing with bounded growth; no full reparse/copy on every byte. Fuzz all chunk boundaries and truncated calls. Measure allocations separately from correctness. | | P07 | Malformed complete argument text sets `argumentsError`; validation rejects it rather than executing an empty argument object. Schema validation can coerce values and validates a copy rather than mutating the transcript. | T: [argument error](../reference/pi/packages/ai/src/types.ts#L452). I: [validation](../reference/pi/packages/ai/src/utils/validation.ts#L45). R: [coercion examples](../reference/pi/packages/ai/test/validation.test.ts#L35). | Keep original arguments immutable and reject incomplete/invalid calls. Decide and test whether coercion is part of compatibility; strict rejection would be an intentional difference. | | P08 | Normalized stop reasons include pending, normal stop, output length, tool use, error, abort, and deferred. Raw provider stop reason is retained separately. | T: [stop reasons](../reference/pi/packages/ai/src/types.ts#L497), [response fields](../reference/pi/packages/ai/src/types.ts#L593). | Never infer tool execution eligibility from visible text. Persist normalized and raw outcomes; a length-limited response is not ordinary success. | | P09 | Deferred work has a provider/model/API-bound handle, optional expiry, poll delay, and conversion data. | T: [deferred handle](../reference/pi/packages/ai/src/types.ts#L547), [deferred fetch](../reference/pi/packages/ai/src/types.ts#L282). | Persist the handle before polling; separate poll from creation to avoid resubmission on restart. Provider support and expiry behavior need individual follow-up mapping. | ## Replay and request construction | ID | Observed contract | Evidence | Consequence for a native C harness | |---|---|---|---| | P10 | Prompt and tools normalize into transcript system messages. Later messages append instructions, patch named sections, and add/remove tools. Unsupported transports collapse the effective system state into a leading message. | T: [system message semantics](../reference/pi/packages/ai/src/types.ts#L559). I: [normalization](../reference/pi/packages/ai/src/utils/transcript.ts#L25), [replay and collapse](../reference/pi/packages/ai/src/utils/transcript.ts#L57). | Persist prompt/tool changes in order. Treat provider serialization as a projection of canonical history, not an edit to stored records. Pin effective context versions for each request. | | P11 | This Pi revision keeps reasoning for the same provider/API/model, drops other models' reasoning, removes foreign signatures, and can remap tool IDs consistently into corresponding results. | I: [cross-model transformation](../reference/pi/packages/ai/src/api/transform-messages.ts#L86). R: [foreign reasoning tests](../reference/pi/packages/ai/test/transform-messages-cross-model-thinking.test.ts#L38). | Preserve canonical originals; transform only outbound requests. This is Pi's policy, not a universal provider rule. Validate actual provider continuity rules before adopting it. | | P12 | Replay omits error/aborted assistant messages and synthesizes error results for unanswered calls. Intervening system messages are held until tool accounting closes. | I: [tool-result repair and interrupted-turn filtering](../reference/pi/packages/ai/src/api/transform-messages.ts#L179). | A synthetic protocol result does not prove a tool did or did not execute. Recover execution state first; build valid outbound history second. Inject synthetic timestamps through a controlled clock in DST. | | P13 | Unsupported images become explicit placeholders; some APIs require images from error results moved after the tool results. | I: [error-image splitting](../reference/pi/packages/ai/src/api/transform-messages.ts#L25), [non-vision downgrade](../reference/pi/packages/ai/src/api/transform-messages.ts#L62). | Image capability and placement are adapter contracts, not generic text concatenation. Archive attachments independently of provider-specific request shaping. | | P14 | Provider retry helper honors `x-should-retry`, retries selected HTTP/network failures within its configured budget, respects excluded statuses, parses retry hints, caps server delays, and aborts backoff. Its own retry count defaults to zero. | I: [classification and delays](../reference/pi/packages/ai/src/utils/provider-retry.ts#L24), [budget and cancellation](../reference/pi/packages/ai/src/utils/provider-retry.ts#L99). R: [retry tests](../reference/pi/packages/ai/test/provider-retry.test.ts#L11). | Keep HTTP retries distinct from persisted generation attempts. Prevent multiplicative retry loops. Inject clock/randomness and persist runtime-level retry deadlines. | | P15 | Usage separates input/output/cache read/cache write; reasoning is a subset of output. Total cost can be provider-billed or catalog-estimated, with an explicit flag. | T: [usage](../reference/pi/packages/ai/src/types.ts#L467). | Do not double-count reasoning; distinguish estimated and billed spend. Interrupted/retried requests need durable accounting independent of displayed successful answers. | | P16 | Transport, cache retention, session identity, and continuation suppression are explicit optional request settings. Provider support varies. | T: [stream options](../reference/pi/packages/ai/src/types.ts#L221). | Stable provider session identity is separate from request deduplication. Cache warming/replay must not overwrite live continuation state. | | P17 | Model metadata declares modality, limits, thinking-level mappings, cache capabilities, and adapter-specific compatibility. | T: [model contract](../reference/pi/packages/ai/src/types.ts#L849). | Version capability/config data; reject unsupported requests clearly. Do not hardcode a single universal provider feature set. | ## Deliberately incomplete This pass does not establish wire compatibility for every provider. OAuth flows, credential refresh, endpoint selection, SSE/WebSocket grammar, structured outputs, overflow recovery, exact refusal handling, provider thread recovery, and image/classifier APIs require adapter-specific passes. Source tests that require live endpoints are not evidence of behavior on this machine. Pi's shared normalization policy is guidance, not a substitute for current provider specifications. No credentials or provider requests were used for this mapping.