Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(llm): add provider-attempt wire contract

Alfredo Lopezd67f89e7b370
diff --git a/Makefile b/Makefile
index 4e367b802..af0d4ab01 100644
--- a/Makefile
+++ b/Makefile
@@ -47,7 +47,8 @@ SERVICES := \
mcp-servers \
packages/desktop-app-links \
packages/workflow-runtime-core \
- packages/workflow-sdk
+ packages/workflow-sdk \
+ packages/llm-provider-attempt-contract
# Services that have unit tests
TEST_SERVICES := \
@@ -68,7 +69,8 @@ TEST_SERVICES := \
packages/desktop-app-links \
packages/workflow-runtime-core \
packages/workflow-sdk \
- packages/network-policy-core
+ packages/network-policy-core \
+ packages/llm-provider-attempt-contract
# ── Optional private infra (gcp-*, promotion) ──────────────────────────────
-include Makefile.infra
diff --git a/packages/llm-provider-attempt-contract/fixtures/canonical-request-hashes.json b/packages/llm-provider-attempt-contract/fixtures/canonical-request-hashes.json
new file mode 100644
index 000000000..535c28d98
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/fixtures/canonical-request-hashes.json
@@ -0,0 +1,229 @@
+{
+ "schemaVersion": "codex-completion-request.v1",
+ "notes": "SHA-256 over the validated V1 projection using lexicographic stableStringify. Nested object key insertion order must not change the digest. Array order is significant. Omitted optional fields are absent from the projection. Non-finite numbers are rejected before hashing.",
+ "cases": [
+ {
+ "name": "minimal",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-001",
+ "idempotencyKey": "idem-001",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "hello" }]
+ },
+ "sha256": "d4223ad1422010cd31644e42181d83a07269f8d5740ae18c11cad3b56e5b4b97"
+ },
+ {
+ "name": "nested-tool-schema-key-ordering",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-tools",
+ "idempotencyKey": "idem-tools",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "use the tool" }],
+ "tools": [
+ {
+ "name": "lookup",
+ "description": "Look up a record",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "zebra": { "type": "string" },
+ "alpha": { "type": "number" }
+ },
+ "required": ["alpha"]
+ }
+ }
+ ]
+ },
+ "equivalentRequest": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-tools",
+ "idempotencyKey": "idem-tools",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "use the tool" }],
+ "tools": [
+ {
+ "description": "Look up a record",
+ "name": "lookup",
+ "parameters": {
+ "required": ["alpha"],
+ "type": "object",
+ "properties": {
+ "alpha": { "type": "number" },
+ "zebra": { "type": "string" }
+ }
+ }
+ }
+ ]
+ },
+ "sha256": "3c8b16dad6803bcc60afbfe1ba410f4cb23d10300834642fd39a24ffe6beac50"
+ },
+ {
+ "name": "unicode",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-unicode",
+ "idempotencyKey": "idem-unicode",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "café 漢字 🎵" }]
+ },
+ "sha256": "f1860990cf74a162bea4c9eff8e98a132003f4c2a2fe779925ceccfbc00c8afb"
+ },
+ {
+ "name": "omitted-optional-fields",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-omit",
+ "idempotencyKey": "idem-omit",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "omit" }],
+ "tools": [],
+ "generation": {},
+ "transportHints": {}
+ },
+ "equivalentRequest": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-omit",
+ "idempotencyKey": "idem-omit",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "omit" }]
+ },
+ "sha256": "71f6567f5f379fb3eb599d3f7a350517a99a679a11a6c56fc9ccce5606d2f10b"
+ },
+ {
+ "name": "arrays-are-order-significant",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-array",
+ "idempotencyKey": "idem-array",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ { "role": "user", "content": "first" },
+ { "role": "assistant", "content": "second" }
+ ]
+ },
+ "distinctRequest": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-array",
+ "idempotencyKey": "idem-array",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ { "role": "assistant", "content": "second" },
+ { "role": "user", "content": "first" }
+ ]
+ },
+ "sha256": "0279883698794791c7af625a9496d85e0245b664eed1c5d48e5febaaa75a07fe"
+ },
+ {
+ "name": "generation-and-deadline-and-hint",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-gen",
+ "idempotencyKey": "idem-gen",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "bounded" }],
+ "generation": {
+ "temperature": 0.2,
+ "maxOutputTokens": 256,
+ "toolChoice": "auto"
+ },
+ "deadlineMs": 15000,
+ "transportHints": { "promptCacheKey": "evenfire-owned-hint" }
+ },
+ "sha256": "61dbf3ac37f60f656990476511716bef19fc2c55acb3c8a5cd4d1779b217a420"
+ }
+ ],
+ "rejects": [
+ { "name": "unknown-header-field", "reason": "unknown-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-hdr",
+ "idempotencyKey": "idem-hdr",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "headers": { "Authorization": "Bearer nope" }
+ } },
+ { "name": "oauth-access-token", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-oauth",
+ "idempotencyKey": "idem-oauth",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "accessToken": "sk-forbidden"
+ } },
+ { "name": "account-selector", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-acct",
+ "idempotencyKey": "idem-acct",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "accountSelector": "acct-1"
+ } },
+ { "name": "arbitrary-url", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-url",
+ "idempotencyKey": "idem-url",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "url": "https://api.openai.com/v1/chat/completions"
+ } },
+ { "name": "mcp-capability", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-mcp",
+ "idempotencyKey": "idem-mcp",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "mcp": { "server": "filesystem" }
+ } },
+ { "name": "shell-capability", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-shell",
+ "idempotencyKey": "idem-shell",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "shell": true
+ } },
+ { "name": "browser-capability", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-browser",
+ "idempotencyKey": "idem-browser",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "browser": true
+ } },
+ { "name": "cookie-field", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-cookie",
+ "idempotencyKey": "idem-cookie",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "cookie": "sid=1"
+ } },
+ { "name": "filesystem-path", "reason": "forbidden-field", "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-path",
+ "idempotencyKey": "idem-path",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [{ "role": "user", "content": "x" }],
+ "path": "/etc/passwd"
+ } }
+ ]
+}
diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjs
new file mode 100644
index 000000000..1575e7c8f
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@ -0,0 +1,461 @@
+'use strict'
+
+/**
+ * @clerum/llm-provider-attempt-contract — see index.d.ts.
+ * Pure module: no network, credentials, or Kubernetes.
+ */
+
+const { createHash } = require('node:crypto')
+
+const SCHEMA_VERSION = 'codex-completion-request.v1'
+const RECEIPT_SCHEMA_VERSION = 'codex-attempt-receipt.v1'
+const PROVIDER_ID = 'codex-subscription'
+const TICKET_TYP = 'codex-execution-ticket'
+
+const LIMITS = Object.freeze({
+ maxRequestBodyBytes: 1048576,
+ maxMessages: 128,
+ maxTools: 32,
+ maxOutputTokens: 16384,
+ maxDeadlineMs: 300000,
+ maxIdLength: 128,
+})
+
+const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
+const SHA256_HEX = /^[a-f0-9]{64}$/
+const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
+const TOOL_CHOICES = new Set(['auto', 'none', 'required'])
+const RECEIPT_OUTCOMES = new Set(['success', 'canceled', 'error', 'unknown'])
+
+const ROOT_KEYS = new Set([
+ 'schemaVersion',
+ 'requestId',
+ 'idempotencyKey',
+ 'provider',
+ 'model',
+ 'messages',
+ 'tools',
+ 'generation',
+ 'deadlineMs',
+ 'transportHints',
+])
+const MESSAGE_KEYS = new Set(['role', 'content', 'name', 'toolCallId'])
+const TOOL_KEYS = new Set(['name', 'description', 'parameters'])
+const GENERATION_KEYS = new Set(['temperature', 'maxOutputTokens', 'toolChoice'])
+const HINT_KEYS = new Set(['promptCacheKey'])
+const CLAIMS_KEYS = new Set([
+ 'jti',
+ 'typ',
+ 'sub',
+ 'hostRef',
+ 'recipeNamespace',
+ 'recipeName',
+ 'invocationId',
+ 'attemptGeneration',
+ 'providerAttemptId',
+ 'providerAttemptIndex',
+ 'provider',
+ 'model',
+ 'requestHash',
+ 'policyRevision',
+ 'policyHash',
+ 'budgetReservationId',
+ 'connectionRevision',
+])
+const AUTHORIZE_KEYS = new Set([
+ 'providerAttemptId',
+ 'requestHash',
+ 'executionTicket',
+ 'expiresAt',
+])
+const RECEIPT_KEYS = new Set(['schemaVersion', 'providerAttemptId', 'requestHash', 'outcome', 'usage'])
+const USAGE_KEYS = new Set(['inputTokens', 'outputTokens'])
+
+function fail(code, message) {
+ return { ok: false, code, message }
+}
+
+function ok(value) {
+ return { ok: true, value }
+}
+
+/**
+ * Canonical JSON serialization for deterministic hashing.
+ * Copied to stay compatible with control-api/src/utils/stableStringify.ts.
+ * Validation rejects non-finite numbers before this runs.
+ */
+function stableStringify(value) {
+ if (value === null) return 'null'
+ if (value === undefined) return 'null'
+ const t = typeof value
+ if (t === 'number') {
+ return Number.isFinite(value) ? String(value) : 'null'
+ }
+ if (t === 'string' || t === 'boolean') {
+ return JSON.stringify(value)
+ }
+ if (Array.isArray(value)) {
+ const items = value.map(item => (item === undefined ? 'null' : stableStringify(item)))
+ return `[${items.join(',')}]`
+ }
+ if (t === 'object') {
+ const obj = value
+ const keys = Object.keys(obj)
+ .filter(k => obj[k] !== undefined)
+ .sort()
+ const body = keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')
+ return `{${body}}`
+ }
+ return 'null'
+}
+
+function isPlainObject(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function unknownKeys(obj, allowed) {
+ return Object.keys(obj).filter(k => !allowed.has(k))
+}
+
+function isBoundedId(value) {
+ return typeof value === 'string' && ID_PATTERN.test(value)
+}
+
+function rejectUnknown(obj, allowed, label) {
+ const extra = unknownKeys(obj, allowed)
+ if (extra.length === 0) return null
+ return fail('unknown-field', `${label} rejects field '${extra[0]}'`)
+}
+
+function assertFiniteTree(value, label) {
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) {
+ return fail('non-finite', `${label} must be finite`)
+ }
+ return null
+ }
+ if (value === null || value === undefined) return null
+ if (typeof value === 'string' || typeof value === 'boolean') return null
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
+ return fail('invalid', `${label} has an unsupported type`)
+ }
+ if (Array.isArray(value)) {
+ for (let i = 0; i < value.length; i++) {
+ const inner = assertFiniteTree(value[i], `${label}[${i}]`)
+ if (inner) return inner
+ }
+ return null
+ }
+ if (typeof value === 'object') {
+ for (const [k, v] of Object.entries(value)) {
+ if (v === undefined) continue
+ const inner = assertFiniteTree(v, `${label}.${k}`)
+ if (inner) return inner
+ }
+ }
+ return null
+}
+
+function parseMessages(raw) {
+ if (!Array.isArray(raw) || raw.length === 0) {
+ return fail('invalid', 'messages must be a non-empty array')
+ }
+ if (raw.length > LIMITS.maxMessages) {
+ return fail('limit', `messages exceed ${LIMITS.maxMessages}`)
+ }
+ const messages = []
+ for (let i = 0; i < raw.length; i++) {
+ const item = raw[i]
+ if (!isPlainObject(item)) return fail('invalid', `messages[${i}] must be an object`)
+ const extra = rejectUnknown(item, MESSAGE_KEYS, `messages[${i}]`)
+ if (extra) return extra
+ if (!MESSAGE_ROLES.has(item.role)) return fail('invalid', `messages[${i}].role is not allowed`)
+ if (typeof item.content !== 'string') return fail('invalid', `messages[${i}].content must be a string`)
+ const message = { role: item.role, content: item.content }
+ if (item.name !== undefined) {
+ if (!isBoundedId(item.name)) return fail('invalid', `messages[${i}].name is invalid`)
+ message.name = item.name
+ }
+ if (item.toolCallId !== undefined) {
+ if (!isBoundedId(item.toolCallId)) return fail('invalid', `messages[${i}].toolCallId is invalid`)
+ message.toolCallId = item.toolCallId
+ }
+ messages.push(message)
+ }
+ return ok(messages)
+}
+
+function parseTools(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!Array.isArray(raw)) return fail('invalid', 'tools must be an array')
+ if (raw.length === 0) return ok(undefined)
+ if (raw.length > LIMITS.maxTools) return fail('limit', `tools exceed ${LIMITS.maxTools}`)
+ const tools = []
+ for (let i = 0; i < raw.length; i++) {
+ const item = raw[i]
+ if (!isPlainObject(item)) return fail('invalid', `tools[${i}] must be an object`)
+ const extra = rejectUnknown(item, TOOL_KEYS, `tools[${i}]`)
+ if (extra) return extra
+ if (!isBoundedId(item.name)) return fail('invalid', `tools[${i}].name is invalid`)
+ if (typeof item.description !== 'string') {
+ return fail('invalid', `tools[${i}].description must be a string`)
+ }
+ if (!isPlainObject(item.parameters)) {
+ return fail('invalid', `tools[${i}].parameters must be an object`)
+ }
+ const finite = assertFiniteTree(item.parameters, `tools[${i}].parameters`)
+ if (finite) return finite
+ tools.push({
+ name: item.name,
+ description: item.description,
+ parameters: item.parameters,
+ })
+ }
+ return ok(tools)
+}
+
+function parseGeneration(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!isPlainObject(raw)) return fail('invalid', 'generation must be an object')
+ const extra = rejectUnknown(raw, GENERATION_KEYS, 'generation')
+ if (extra) return extra
+ const generation = {}
+ if (raw.temperature !== undefined) {
+ if (typeof raw.temperature !== 'number' || !Number.isFinite(raw.temperature)) {
+ return fail('non-finite', 'generation.temperature must be finite')
+ }
+ if (raw.temperature < 0 || raw.temperature > 2) {
+ return fail('invalid', 'generation.temperature is out of range')
+ }
+ generation.temperature = raw.temperature
+ }
+ if (raw.maxOutputTokens !== undefined) {
+ if (
+ typeof raw.maxOutputTokens !== 'number' ||
+ !Number.isFinite(raw.maxOutputTokens) ||
+ !Number.isInteger(raw.maxOutputTokens)
+ ) {
+ return fail('non-finite', 'generation.maxOutputTokens must be a finite integer')
+ }
+ if (raw.maxOutputTokens < 1 || raw.maxOutputTokens > LIMITS.maxOutputTokens) {
+ return fail('limit', 'generation.maxOutputTokens is out of range')
+ }
+ generation.maxOutputTokens = raw.maxOutputTokens
+ }
+ if (raw.toolChoice !== undefined) {
+ if (!TOOL_CHOICES.has(raw.toolChoice)) {
+ return fail('invalid', 'generation.toolChoice is not allowed')
+ }
+ generation.toolChoice = raw.toolChoice
+ }
+ return ok(Object.keys(generation).length > 0 ? generation : undefined)
+}
+
+function parseTransportHints(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!isPlainObject(raw)) return fail('invalid', 'transportHints must be an object')
+ const extra = rejectUnknown(raw, HINT_KEYS, 'transportHints')
+ if (extra) return extra
+ if (raw.promptCacheKey === undefined) return ok(undefined)
+ if (!isBoundedId(raw.promptCacheKey)) {
+ return fail('invalid', 'transportHints.promptCacheKey is invalid')
+ }
+ return ok({ promptCacheKey: raw.promptCacheKey })
+}
+
+function parseCodexCompletionRequestV1(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
+ const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ if (encoded > LIMITS.maxRequestBodyBytes) {
+ return fail('limit', 'request exceeds maxRequestBodyBytes')
+ }
+ const extra = rejectUnknown(input, ROOT_KEYS, 'request')
+ if (extra) return extra
+ if (input.schemaVersion !== SCHEMA_VERSION) {
+ return fail('invalid', 'schemaVersion is not codex-completion-request.v1')
+ }
+ if (!isBoundedId(input.requestId)) return fail('invalid', 'requestId is invalid')
+ if (!isBoundedId(input.idempotencyKey)) return fail('invalid', 'idempotencyKey is invalid')
+ if (input.provider !== PROVIDER_ID) return fail('invalid', 'provider must be codex-subscription')
+ if (!isBoundedId(input.model)) return fail('invalid', 'model is invalid')
+
+ const messages = parseMessages(input.messages)
+ if (!messages.ok) return messages
+ const tools = parseTools(input.tools)
+ if (!tools.ok) return tools
+ const generation = parseGeneration(input.generation)
+ if (!generation.ok) return generation
+ const transportHints = parseTransportHints(input.transportHints)
+ if (!transportHints.ok) return transportHints
+
+ let deadlineMs
+ if (input.deadlineMs !== undefined) {
+ if (
+ typeof input.deadlineMs !== 'number' ||
+ !Number.isFinite(input.deadlineMs) ||
+ !Number.isInteger(input.deadlineMs)
+ ) {
+ return fail('non-finite', 'deadlineMs must be a finite integer')
+ }
+ if (input.deadlineMs < 1 || input.deadlineMs > LIMITS.maxDeadlineMs) {
+ return fail('limit', 'deadlineMs is out of range')
+ }
+ deadlineMs = input.deadlineMs
+ }
+
+ const projected = {
+ schemaVersion: SCHEMA_VERSION,
+ requestId: input.requestId,
+ idempotencyKey: input.idempotencyKey,
+ provider: PROVIDER_ID,
+ model: input.model,
+ messages: messages.value,
+ }
+ if (tools.value) projected.tools = tools.value
+ if (generation.value) projected.generation = generation.value
+ if (deadlineMs !== undefined) projected.deadlineMs = deadlineMs
+ if (transportHints.value) projected.transportHints = transportHints.value
+ return ok(Object.freeze(projected))
+}
+
+function hashCodexCompletionRequestV1(request) {
+ return createHash('sha256').update(stableStringify(request)).digest('hex')
+}
+
+function requireId(obj, key) {
+ if (!isBoundedId(obj[key])) return fail('invalid', `${key} is invalid`)
+ return null
+}
+
+function requireHex64(obj, key) {
+ if (typeof obj[key] !== 'string' || !SHA256_HEX.test(obj[key])) {
+ return fail('invalid', `${key} must be a SHA-256 hex digest`)
+ }
+ return null
+}
+
+function requireInt(obj, key, min) {
+ const value = obj[key]
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < min) {
+ return fail('non-finite', `${key} must be a finite integer`)
+ }
+ return null
+}
+
+function parseCodexExecutionTicketClaims(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'ticket claims must be an object')
+ const extra = rejectUnknown(input, CLAIMS_KEYS, 'ticket claims')
+ if (extra) return extra
+ for (const key of ['jti', 'sub', 'hostRef', 'invocationId', 'providerAttemptId', 'budgetReservationId', 'model']) {
+ const bad = requireId(input, key)
+ if (bad) return bad
+ }
+ if (input.typ !== TICKET_TYP) return fail('invalid', 'typ must be codex-execution-ticket')
+ if (input.provider !== PROVIDER_ID) return fail('invalid', 'provider must be codex-subscription')
+ const hashErr = requireHex64(input, 'requestHash') || requireHex64(input, 'policyHash')
+ if (hashErr) return hashErr
+ const ints =
+ requireInt(input, 'attemptGeneration', 0) ||
+ requireInt(input, 'providerAttemptIndex', 0) ||
+ requireInt(input, 'policyRevision', 0) ||
+ requireInt(input, 'connectionRevision', 0)
+ if (ints) return ints
+ const claims = {
+ jti: input.jti,
+ typ: TICKET_TYP,
+ sub: input.sub,
+ hostRef: input.hostRef,
+ invocationId: input.invocationId,
+ attemptGeneration: input.attemptGeneration,
+ providerAttemptId: input.providerAttemptId,
+ providerAttemptIndex: input.providerAttemptIndex,
+ provider: PROVIDER_ID,
+ model: input.model,
+ requestHash: input.requestHash,
+ policyRevision: input.policyRevision,
+ policyHash: input.policyHash,
+ budgetReservationId: input.budgetReservationId,
+ connectionRevision: input.connectionRevision,
+ }
+ if (input.recipeNamespace !== undefined) {
+ if (!isBoundedId(input.recipeNamespace)) return fail('invalid', 'recipeNamespace is invalid')
+ claims.recipeNamespace = input.recipeNamespace
+ }
+ if (input.recipeName !== undefined) {
+ if (!isBoundedId(input.recipeName)) return fail('invalid', 'recipeName is invalid')
+ claims.recipeName = input.recipeName
+ }
+ return ok(Object.freeze(claims))
+}
+
+function parseAuthorizeAttemptResponse(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'authorize response must be an object')
+ const extra = rejectUnknown(input, AUTHORIZE_KEYS, 'authorize response')
+ if (extra) return extra
+ const idErr = requireId(input, 'providerAttemptId')
+ if (idErr) return idErr
+ const hashErr = requireHex64(input, 'requestHash')
+ if (hashErr) return hashErr
+ if (typeof input.executionTicket !== 'string' || input.executionTicket.length < 8) {
+ return fail('invalid', 'executionTicket is invalid')
+ }
+ if (typeof input.expiresAt !== 'string' || Number.isNaN(Date.parse(input.expiresAt))) {
+ return fail('invalid', 'expiresAt is invalid')
+ }
+ return ok(
+ Object.freeze({
+ providerAttemptId: input.providerAttemptId,
+ requestHash: input.requestHash,
+ executionTicket: input.executionTicket,
+ expiresAt: input.expiresAt,
+ })
+ )
+}
+
+function parseCodexAttemptReceiptV1(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'receipt must be an object')
+ const extra = rejectUnknown(input, RECEIPT_KEYS, 'receipt')
+ if (extra) return extra
+ if (input.schemaVersion !== RECEIPT_SCHEMA_VERSION) {
+ return fail('invalid', 'schemaVersion is not codex-attempt-receipt.v1')
+ }
+ const idErr = requireId(input, 'providerAttemptId')
+ if (idErr) return idErr
+ const hashErr = requireHex64(input, 'requestHash')
+ if (hashErr) return hashErr
+ if (!RECEIPT_OUTCOMES.has(input.outcome)) return fail('invalid', 'outcome is not allowed')
+ const receipt = {
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
+ providerAttemptId: input.providerAttemptId,
+ requestHash: input.requestHash,
+ outcome: input.outcome,
+ }
+ if (input.usage !== undefined) {
+ if (!isPlainObject(input.usage)) return fail('invalid', 'usage must be an object')
+ const usageExtra = rejectUnknown(input.usage, USAGE_KEYS, 'usage')
+ if (usageExtra) return usageExtra
+ const usage = {}
+ for (const key of USAGE_KEYS) {
+ if (input.usage[key] === undefined) continue
+ const bad = requireInt(input.usage, key, 0)
+ if (bad) return bad
+ usage[key] = input.usage[key]
+ }
+ if (Object.keys(usage).length > 0) receipt.usage = usage
+ }
+ return ok(Object.freeze(receipt))
+}
+
+module.exports = {
+ SCHEMA_VERSION,
+ RECEIPT_SCHEMA_VERSION,
+ PROVIDER_ID,
+ TICKET_TYP,
+ LIMITS,
+ stableStringify,
+ parseCodexCompletionRequestV1,
+ hashCodexCompletionRequestV1,
+ parseCodexExecutionTicketClaims,
+ parseAuthorizeAttemptResponse,
+ parseCodexAttemptReceiptV1,
+}
diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.ts
new file mode 100644
index 000000000..ee8e90fb4
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/index.d.ts
@@ -0,0 +1,141 @@
+/**
+ * @clerum/llm-provider-attempt-contract — bounded Codex completion request,
+ * canonical SHA-256 hashing, and safe ticket/receipt types.
+ *
+ * Pure module: no network clients, no credential material, no Kubernetes.
+ * Hashing uses the same lexicographic stableStringify semantics as
+ * control-api/src/utils/stableStringify.ts. Non-finite numbers are rejected
+ * before hashing (stringify would otherwise coerce them to null).
+ */
+
+export declare const SCHEMA_VERSION: 'codex-completion-request.v1'
+export declare const RECEIPT_SCHEMA_VERSION: 'codex-attempt-receipt.v1'
+export declare const PROVIDER_ID: 'codex-subscription'
+export declare const TICKET_TYP: 'codex-execution-ticket'
+
+export declare const LIMITS: {
+ readonly maxRequestBodyBytes: 1048576
+ readonly maxMessages: 128
+ readonly maxTools: 32
+ readonly maxOutputTokens: 16384
+ readonly maxDeadlineMs: 300000
+ readonly maxIdLength: 128
+}
+
+export type ContractResult<T> =
+ | { ok: true; value: T }
+ | { ok: false; code: string; message: string }
+
+export type CodexMessageRole = 'system' | 'user' | 'assistant' | 'tool'
+
+export interface CodexMessageV1 {
+ role: CodexMessageRole
+ content: string
+ name?: string
+ toolCallId?: string
+}
+
+export interface CodexToolDefinitionV1 {
+ name: string
+ description: string
+ parameters: Record<string, unknown>
+}
+
+export type CodexToolChoiceV1 = 'auto' | 'none' | 'required'
+
+export interface CodexGenerationOptionsV1 {
+ temperature?: number
+ maxOutputTokens?: number
+ toolChoice?: CodexToolChoiceV1
+}
+
+export interface CodexTransportHintsV1 {
+ promptCacheKey?: string
+}
+
+export interface CodexCompletionRequestV1 {
+ schemaVersion: 'codex-completion-request.v1'
+ requestId: string
+ idempotencyKey: string
+ provider: 'codex-subscription'
+ model: string
+ messages: CodexMessageV1[]
+ tools?: CodexToolDefinitionV1[]
+ generation?: CodexGenerationOptionsV1
+ deadlineMs?: number
+ transportHints?: CodexTransportHintsV1
+}
+
+export type CodexExecutionTicketClaims = {
+ jti: string
+ typ: 'codex-execution-ticket'
+ sub: string
+ hostRef: string
+ recipeNamespace?: string
+ recipeName?: string
+ invocationId: string
+ attemptGeneration: number
+ providerAttemptId: string
+ providerAttemptIndex: number
+ provider: 'codex-subscription'
+ model: string
+ requestHash: string
+ policyRevision: number
+ policyHash: string
+ budgetReservationId: string
+ connectionRevision: number
+}
+
+export type AuthorizeAttemptResponse = {
+ providerAttemptId: string
+ requestHash: string
+ executionTicket: string
+ expiresAt: string
+}
+
+/**
+ * Gateway→proxy only. Never log, persist, or return this object to mcp-host
+ * or the browser. The contract package does not parse it.
+ */
+export type RedeemAttemptResponse = {
+ accessToken: string
+ transport: CodexTransportMetadataV1
+ expiryClass: 'short_lived' | 'upstream_managed'
+ attemptReceipt: string
+}
+
+export type CodexTransportMetadataV1 = {
+ protocolVersion: 'codex-subscription-transport.v1'
+ completionsOrigin: 'https://chatgpt.com/backend-api/codex/responses'
+ catalogOrigin: 'https://chatgpt.com/backend-api/codex/models'
+ operation: 'completion_stream' | 'completion_cancel' | 'connection_test'
+ servedModel: string
+ maxStreamDurationMs: number
+}
+
+export type CodexAttemptOutcome = 'success' | 'canceled' | 'error' | 'unknown'
+
+export type CodexAttemptReceiptV1 = {
+ schemaVersion: 'codex-attempt-receipt.v1'
+ providerAttemptId: string
+ requestHash: string
+ outcome: CodexAttemptOutcome
+ usage?: { inputTokens?: number; outputTokens?: number }
+}
+
+export declare function stableStringify(value: unknown): string
+export declare function parseCodexCompletionRequestV1(
+ input: unknown
+): ContractResult<CodexCompletionRequestV1>
+export declare function hashCodexCompletionRequestV1(
+ request: CodexCompletionRequestV1
+): string
+export declare function parseCodexExecutionTicketClaims(
+ input: unknown
+): ContractResult<CodexExecutionTicketClaims>
+export declare function parseAuthorizeAttemptResponse(
+ input: unknown
+): ContractResult<AuthorizeAttemptResponse>
+export declare function parseCodexAttemptReceiptV1(
+ input: unknown
+): ContractResult<CodexAttemptReceiptV1>
diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjs
new file mode 100644
index 000000000..c3475ba80
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/index.test.cjs
@@ -0,0 +1,164 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const crypto = require('node:crypto')
+const fs = require('node:fs')
+const path = require('node:path')
+const test = require('node:test')
+const contract = require('./index.cjs')
+
+const FIXTURE = JSON.parse(
+ fs.readFileSync(path.join(__dirname, 'fixtures/canonical-request-hashes.json'), 'utf8')
+)
+
+const BASE = {
+ schemaVersion: 'codex-completion-request.v1',
+ requestId: 'req-001',
+ idempotencyKey: 'idem-001',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ messages: [{ role: 'user', content: 'hello' }],
+}
+
+test('runtime exports stay aligned with the declaration file', () => {
+ const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
+ const declared = Array.from(
+ declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),
+ m => m[1]
+ ).sort()
+ assert.deepEqual(Object.keys(contract).sort(), declared)
+})
+
+test('parses the bounded V1 request and hashes with SHA-256', () => {
+ const parsed = contract.parseCodexCompletionRequestV1(BASE)
+ assert.equal(parsed.ok, true)
+ const digest = contract.hashCodexCompletionRequestV1(parsed.value)
+ assert.match(digest, /^[a-f0-9]{64}$/)
+})
+
+test('fixture corpus: valid cases match frozen hashes and equivalent reorderings', () => {
+ for (const fixture of FIXTURE.cases) {
+ const parsed = contract.parseCodexCompletionRequestV1(fixture.request)
+ assert.equal(parsed.ok, true, fixture.name)
+ const digest = contract.hashCodexCompletionRequestV1(parsed.value)
+ assert.equal(digest, fixture.sha256, fixture.name)
+ if (fixture.equivalentRequest) {
+ const other = contract.parseCodexCompletionRequestV1(fixture.equivalentRequest)
+ assert.equal(other.ok, true, `${fixture.name} equivalent`)
+ assert.equal(contract.hashCodexCompletionRequestV1(other.value), digest, `${fixture.name} reorder`)
+ }
+ if (fixture.distinctRequest) {
+ const other = contract.parseCodexCompletionRequestV1(fixture.distinctRequest)
+ assert.equal(other.ok, true, `${fixture.name} distinct`)
+ assert.notEqual(contract.hashCodexCompletionRequestV1(other.value), digest, `${fixture.name} array order`)
+ }
+ }
+})
+
+test('fixture corpus: rejected payloads fail closed', () => {
+ for (const fixture of FIXTURE.rejects) {
+ const parsed = contract.parseCodexCompletionRequestV1(fixture.request)
+ assert.equal(parsed.ok, false, fixture.name)
+ assert.equal(typeof parsed.code, 'string')
+ }
+})
+
+test('rejects NaN and Infinity before hashing (stableStringify would coerce them to null)', () => {
+ const nanParsed = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ generation: { temperature: Number.NaN },
+ })
+ assert.equal(nanParsed.ok, false)
+ assert.match(nanParsed.code, /non-finite|invalid/)
+
+ const infParsed = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ generation: { maxOutputTokens: Number.POSITIVE_INFINITY },
+ })
+ assert.equal(infParsed.ok, false)
+ assert.match(infParsed.code, /non-finite|invalid/)
+})
+
+test('unknown fields, OAuth, account selector, URL/header/cookie/path and MCP/shell/browser are rejected', () => {
+ const extras = [
+ { headers: { Authorization: 'x' } },
+ { authorization: 'Bearer x' },
+ { accessToken: 'sk-x' },
+ { refreshToken: 'rt-x' },
+ { oauth: { code: 'x' } },
+ { accountSelector: 'acct' },
+ { accountId: 'acct' },
+ { url: 'https://example.com' },
+ { cookie: 'a=b' },
+ { path: '/tmp' },
+ { mcp: true },
+ { shell: true },
+ { browser: true },
+ ]
+ for (const extra of extras) {
+ const parsed = contract.parseCodexCompletionRequestV1({ ...BASE, ...extra })
+ assert.equal(parsed.ok, false, JSON.stringify(Object.keys(extra)))
+ }
+})
+
+test('hash is SHA-256 of lexicographic stableStringify of the projection', () => {
+ const parsed = contract.parseCodexCompletionRequestV1(BASE)
+ assert.equal(parsed.ok, true)
+ const expected = crypto
+ .createHash('sha256')
+ .update(contract.stableStringify(parsed.value))
+ .digest('hex')
+ assert.equal(contract.hashCodexCompletionRequestV1(parsed.value), expected)
+})
+
+test('stableStringify sorts object keys and drops undefined like control-api', () => {
+ assert.equal(contract.stableStringify({ b: 1, a: 2 }), '{"a":2,"b":1}')
+ assert.equal(contract.stableStringify({ a: undefined, b: 1 }), '{"b":1}')
+ assert.equal(contract.stableStringify([1, undefined, 2]), '[1,null,2]')
+})
+
+test('ticket and receipt types stay credential-free at the contract boundary', () => {
+ const claims = {
+ jti: 'jti-1',
+ typ: 'codex-execution-ticket',
+ sub: 'host-a',
+ hostRef: 'host-a',
+ invocationId: 'inv-1',
+ attemptGeneration: 1,
+ providerAttemptId: 'att-1',
+ providerAttemptIndex: 0,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ requestHash: 'a'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'b'.repeat(64),
+ budgetReservationId: 'bud-1',
+ connectionRevision: 1,
+ }
+ const parsed = contract.parseCodexExecutionTicketClaims(claims)
+ assert.equal(parsed.ok, true)
+ assert.equal('accessToken' in parsed.value, false)
+
+ const receipt = contract.parseCodexAttemptReceiptV1({
+ schemaVersion: 'codex-attempt-receipt.v1',
+ providerAttemptId: 'att-1',
+ requestHash: 'a'.repeat(64),
+ outcome: 'success',
+ usage: { inputTokens: 3, outputTokens: 5 },
+ })
+ assert.equal(receipt.ok, true)
+ assert.equal('accessToken' in receipt.value, false)
+})
+
+test('authorize response is metadata-only; redeem type is documented but not parsed here', () => {
+ const authorize = contract.parseAuthorizeAttemptResponse({
+ providerAttemptId: 'att-1',
+ requestHash: 'a'.repeat(64),
+ executionTicket: 'jwt.ticket',
+ expiresAt: '2026-08-20T10:00:00.000Z',
+ })
+ assert.equal(authorize.ok, true)
+ assert.equal('accessToken' in authorize.value, false)
+ assert.equal('accountId' in authorize.value, false)
+ assert.equal(typeof contract.RedeemAttemptResponseSensitive, 'undefined')
+})
diff --git a/packages/llm-provider-attempt-contract/package-lock.json b/packages/llm-provider-attempt-contract/package-lock.json
new file mode 100644
index 000000000..465774c75
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/package-lock.json
@@ -0,0 +1,13 @@
+{
+ "name": "@clerum/llm-provider-attempt-contract",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/llm-provider-attempt-contract",
+ "version": "0.1.0",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/packages/llm-provider-attempt-contract/package.json b/packages/llm-provider-attempt-contract/package.json
new file mode 100644
index 000000000..513dae455
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@clerum/llm-provider-attempt-contract",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Shared bounded Codex provider-attempt wire contract, canonical request hashing, and safe ticket/receipt types. No network clients or credentials.",
+ "main": "index.cjs",
+ "types": "index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "require": "./index.cjs",
+ "default": "./index.cjs"
+ }
+ },
+ "scripts": {
+ "build": "node --check index.cjs",
+ "test": "node --test index.test.cjs"
+ },
+ "license": "MIT"
+}