@janole/ai-sdk-provider-codex-asp
v0.6.0
Published
Vercel AI SDK custom provider for the Codex App Server Protocol. Works with AI SDK v6 and v7.
Maintainers
Readme
@janole/ai-sdk-provider-codex-asp
@janole/ai-sdk-provider-codex-asp is a Vercel AI SDK custom provider for the Codex App Server Protocol, supporting both AI SDK v6 and v7 from one package.
Status: POC feature-complete for language model usage. Currently tested with codex-cli 0.169.0.
LanguageModelV3provider implementation — used natively byai@6, and accepted byai@7through its built-in v3→v4 model proxy- Streaming (
streamText) and non-streaming (generateText) - Standard AI SDK
tool()support via Codex dynamic tools injection - Provider-executed tool protocol for Codex command executions
- Generated images surfaced as AI SDK
fileparts (image/png) stdioandwebsockettransports- Persistent worker pool with thread management
Installation
npm install @janole/ai-sdk-provider-codex-asp aiAI SDK version support
| AI SDK | Supported | Node.js |
| --- | --- | --- |
| ai@6 | yes, natively | 20+ |
| ai@7 | yes, via the SDK's v3→v4 proxy | 22+ |
One package covers both: the provider implements LanguageModelV3, which ai@7
accepts at runtime and proxies forward to LanguageModelV4. Nothing needs to be
configured differently.
The Node.js 22 floor on the ai@7 row is the AI SDK's own requirement, not ours —
this package still supports Node 20 for ai@6 consumers.
Quick Start
1. Non-streaming (generateText)
import { generateText } from 'ai';
import { createCodexAppServer } from '@janole/ai-sdk-provider-codex-asp';
const codex = createCodexAppServer({
defaultModel: 'gpt-5.6-sol',
clientInfo: { name: 'my-app', version: '0.1.0' },
});
const result = await generateText({
model: codex.languageModel('gpt-5.6-sol'),
prompt: 'Write a short release note title for websocket support.',
});
console.log(result.text);2. Streaming (streamText)
import { streamText } from 'ai';
import { createCodexAppServer } from '@janole/ai-sdk-provider-codex-asp';
const codex = createCodexAppServer({
defaultModel: 'gpt-5.6-sol',
clientInfo: { name: 'my-app', version: '0.1.0' },
});
const result = streamText({
model: codex('gpt-5.6-sol'),
prompt: 'Explain JSON-RPC in one paragraph.',
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}Tools
Use standard AI SDK tool() definitions — the provider automatically injects them into Codex as dynamic tools and routes results back. No Codex-specific API needed.
Requires a persistent transport so tool results can be fed back within the same session:
import { stepCountIs, streamText, tool } from 'ai';
import { z } from 'zod';
import { createCodexAppServer } from '@janole/ai-sdk-provider-codex-asp';
const codex = createCodexAppServer({
persistent: { scope: 'global', poolSize: 1, idleTimeoutMs: 60_000 },
});
const result = streamText({
model: codex('gpt-5.6-sol'),
prompt: 'Can you check ticket 15 and also the weather in Berlin?',
tools: {
lookup_ticket: tool({
description: 'Look up the current status of a support ticket by its ID.',
inputSchema: z.object({
id: z.string().describe('The ticket ID, e.g. "TICK-42".'),
}),
execute: async ({ id }) => `Ticket ${id} is open and assigned to team Alpha.`,
}),
check_weather: tool({
description: 'Get the current weather for a given location.',
inputSchema: z.object({
location: z.string().describe('City name or coordinates.'),
}),
execute: async ({ location }) => `Weather in ${location}: 22°C, sunny`,
}),
},
stopWhen: stepCountIs(5),
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
await codex.shutdown();Moving a running session to another directory
CodexSession.moveExecutionContext() moves a running session to a new working directory, together with its runtime workspace roots and sandbox settings, and resolves once Codex has acknowledged the move. From the model's next step on, native commands run there by default, the model is shown the new directory, and its AGENTS.md applies. Later turns of the thread stay there. A sandboxPolicy or permissions you pass applies from the next turn: Codex cannot change a running turn's sandbox mode, so the running turn keeps its mode, and only its writable roots follow runtimeWorkspaceRoots from the next step. Requires Codex ≥ 0.169 and the experimentalApi capability, which is enabled whenever tools are configured.
Call it from the tool that requests the move, before the tool returns. With AI SDK tools (cross-call), take the session from onSessionCreated. With provider-executed tools, the handler's context carries it:
let session: CodexSession | undefined;
const codex = createCodexAppServer({
persistent: { scope: 'global', poolSize: 1, idleTimeoutMs: 60_000 },
onSessionCreated: (created) => { session = created; },
});
const switchWorkspace = tool({
description: 'Move this session to another workspace.',
inputSchema: z.object({ path: z.string() }),
execute: async ({ path }) => {
const result = await session!.moveExecutionContext({
cwd: path,
runtimeWorkspaceRoots: [path], // the complete writable set; nothing is kept from the old context
sandboxPolicy: { type: 'workspaceWrite', writableRoots: [], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false },
});
return result.status === 'moved' ? `Now working in ${path}.` : `Could not switch: ${result.message}`;
},
});The result is either { status: "moved", effective: "nextStep", threadId, turnId, context, noop } or { status: "failed", reason, message, turnApplied }. It never throws.
targetUnavailable: the session's turn has ended, orexpectedTurnIdnames another turn. Nothing changed.invalidRequest: a relative path, or bothsandboxPolicyandpermissions. Nothing was sent.aborted:signalfired before anything was sent.turnUpdateFailed: Codex rejectedturn/settings/update, e.g. withoutexperimentalApi. Nothing changed.threadUpdateFailed: the running turn moved but future turns did not (turnApplied: true). Move again before relying on either context.
How it works and what it does not guarantee:
- It sends
turn/settings/updatefor the running turn, thenthread/settings/updatefor the thread's future turns. Moves on one session are serialized. A move that repeats the context already in force for this turn sends nothing and reportsnoop: true. - The tool response is held until every move requested so far is acknowledged, even if the handler did not await it. Codex's next step is therefore the first to run in the new context.
- Actions the model emitted in the same response as the move may still run in the old directory. Codex has no ordering barrier for them.
- Running terminals and background processes stay where they are.
- The adapter applies exactly the roots and sandbox you pass and never widens them. With
runtimeWorkspaceRoots: [newDir], writes to the old directory are denied. - A
cwdpassed in call options ordefaultThreadSettings/defaultTurnSettingsis sent again on the next call'sthread/resumeandturn/start, which moves the thread back. After a move, pass the new directory, or none.
Evidence: docs/planning/context-handoff/protocol-proof.md; run scripts/context-handoff-probe.ts adapter-crosscall adapter-dynamic against a real codex.
API Reference
const codex = createCodexAppServer({
defaultModel?: string,
clientInfo?: { name, version, title? }, // defaults to package.json
transport?: { type: 'stdio' | 'websocket', stdio?, websocket? },
persistent?: { poolSize?, idleTimeoutMs?, scope?, key? },
compaction?: { shouldCompactOnResume?, strict? }, // optional thread/compact/start before resumed turns
debug?: { logPackets?, logger? }, // packet-level JSON-RPC debug logging
defaultThreadSettings?: { cwd?, approvalPolicy?, approvalsReviewer?, sandbox?, ephemeral? },
defaultTurnSettings?: { cwd?, approvalPolicy?, approvalsReviewer?, sandboxPolicy?, model?, effort?, summary? },
approvals?: { onCommandApproval?, onFileChangeApproval?, onToolUserInput?, onElicitation? },
toolTimeoutMs?: number, // default: 30000
interruptTimeoutMs?: number, // default: 10000
});
codex(modelId) // returns a language model instance
codex.languageModel(modelId) // explicit alias
codex.chat(modelId) // explicit alias
codex.shutdown() // clean up persistent workersApproval callback notes:
approvals.onCommandApproval(request)— shell command approval. Payload:CommandExecutionRequestApprovalParams. Default:"decline". Checkrequest.kindbefore matchingrequest.commandagainst a policy:"writeStdin"means the payload is stdin for an already-running terminal, not a command to run.approvals.onFileChangeApproval(request)— file write approval. Payload:FileChangeRequestApprovalParams. Default:"decline".approvals.onElicitation(request)— MCP tool approval (the "Allow / Allow for this session / Always allow / Cancel" prompt). Payload:McpServerElicitationRequestParams. Default:accept. Return{ action, content, _meta }— use_meta: { persist: "session" }or_meta: { persist: "always" }to remember the choice.approvals.onToolUserInput(request)— legacy fallback for MCP tool approval when the elicitation feature flag is off. Payload:ToolRequestUserInputParams. Default: auto-selects the first option per question.
Rich sandbox policy example (turn-level):
const codex = createCodexAppServer({
defaultTurnSettings: {
approvalPolicy: "on-request",
sandboxPolicy: {
type: "externalSandbox",
networkAccess: "enabled",
},
},
});Approval reviewer example:
approvalsReviewer supports:
"user": ask the human user directly"auto_review": use Codex's risk-based automatic reviewer flow"guardian_subagent": route review to Codex's reviewer subagent
const codex = createCodexAppServer({
defaultThreadSettings: {
approvalsReviewer: "auto_review",
},
});
await streamText({
model: codex("gpt-5.6-sol"),
prompt: "Delete the old generated protocol files under src/protocol/app-server-protocol if they are no longer referenced, then regenerate the current ones.",
providerOptions: codexCallOptions({
approvalsReviewer: "user",
approvals: {
onCommandApproval: async () => "decline",
},
}),
});See src/provider.ts for full type definitions.
Provider metadata
The provider attaches Codex state to AI SDK parts under CODEX_PROVIDER_ID, the
same namespace used for thread continuation:
import { CODEX_PROVIDER_ID, type RateLimitSnapshot } from "@janole/ai-sdk-provider-codex-asp";
for await (const part of result.fullStream)
{
const codexMetadata = part.providerMetadata?.[CODEX_PROVIDER_ID];
const rateLimits = codexMetadata?.["rateLimits"] as RateLimitSnapshot | undefined;
const revision = codexMetadata?.["rateLimitsRevision"] as number | undefined;
}Each model call reads the current account rate limits on a best-effort basis,
then merges sparse account/rateLimits/updated notifications into that snapshot.
The latest rateLimits value and its monotonically increasing
rateLimitsRevision are repeated on every metadata-capable part, alongside
threadId and turnId. Consumers can use the revision to avoid processing the
same snapshot repeatedly.
Rate-limit metadata is absent when the Codex account or app-server version does
not support account/rateLimits/read; that does not fail the model call.
Examples
See the examples/ directory:
generate-text.ts— Non-streaming text generationgenerate-object.ts— Structured output withgenerateText+Output.objectstream-text.ts— Streaming text generationcross-call-tools.ts— Standard AI SDK tools via Codexdynamic-tools.ts— Provider-level dynamic toolsthread-continuation.ts— Multi-turn thread resumptionmulti-step-thread.ts— Multi-step thread continuation with threadId verificationapprovals.ts— Command and file-change approval handlingimage-input.ts— Image input withgenerateTextinterrupt.ts— Mid-turn interrupt viaonSessionCreatedlist-models.ts— Discover available models via app-server protocolmid-turn-injection.ts— Mid-turn message injection viaonSessionCreatedprovider-executed-tools.ts— Provider-executed tool calls (server-side commands)
Run any example with:
npx tsx examples/stream-text.tsTroubleshooting
No such file or command: codex:- Install Codex CLI and ensure
codexis inPATH.
- Install Codex CLI and ensure
WebSocket is not available in this runtime:- Use Node.js 20+ with global WebSocket support, or use
stdiotransport.
- Use Node.js 20+ with global WebSocket support, or use
- Request timeouts:
- Increase
toolTimeoutMsfor long-running dynamic tools. - Increase
interruptTimeoutMsifturn/interruptacks are slow under heavy load.
- Increase
- Empty generated text:
- Verify Codex emits
item/agentMessage/deltaandturn/completednotifications.
- Verify Codex emits
- Compaction fails on resumed threads:
- Set
compaction.shouldCompactOnResume: trueto always compact resumed threads. - Or provide
compaction.shouldCompactOnResume: (ctx) => boolean | Promise<boolean>for dynamic decisions. - Leave
compaction.strictunset/false to continue the turn whenthread/compact/startfails. - Set
compaction.strict: trueif you want compaction failures to fail fast.
- Set
Development
npm install
npm run build # ESM + CJS + .d.ts via tsup
npm run qa # lint + typecheck + test (all-in-one)Generated Protocol Types
src/protocol/app-server-protocol/ is gitignored, but selected generated files are intentionally tracked with git add -f so protocol shape changes stay visible in PRs.
Important: for every tracked generated file, all imported generated type dependencies (direct + transitive) must also be tracked.
Use the local skill .codex/skills/codex-protocol-type-upgrade/SKILL.md for the exact workflow.
When protocol shapes change, clean and regenerate:
rm -rf src/protocol/app-server-protocol
npm run codex:generate-typesThen follow the skill workflow to:
- adapt runtime mappings if needed
- add missing generated dependencies with
git add -f - run
npm run typecheck(and focused tests)
License
MIT
