Serve the Droid SDK as an OpenAI-compatible API

Build a local Chat Completions endpoint on the Droid TypeScript SDK that accepts max_tokens and the other standard request fields, and see which ones it maps, ignores, or rejects.

This local Chat Completions adapter accepts max_tokens and max_completion_tokens for client compatibility. SDK 0.11.0 exposes no per-turn output limit, so neither field limits the response.

For a custom model, set maxOutputTokens in its model configuration. It limits each provider call, not the whole turn.

The adapter is a small server on the Droid TypeScript SDK. Everything on this page was run against Droid CLI 1.21.0, @factory/droid-sdk 0.11.0, and openai 7.64.0.

Request fields

Request fieldThis exampleDetail
modelMappedBecomes modelId. Must be an ID from GET /v1/models; any other value gets 404 model_not_found.
messages with text contentMappedsystem and developer messages are appended to Droid's system prompt. Of the other messages, the last must have the role user. Earlier ones are sent as text in the prompt, not as native session history.
reasoning_effortMappedBecomes reasoningEffort. Must be one of the model's supportedReasoningEfforts. null is treated as omitted.
streamMappedDroid's text deltas become chat.completion.chunk events, and a successful stream ends with data: [DONE]. A streamed reply carries every assistant message in the turn; a JSON reply carries only the last one.
max_tokens, max_completion_tokensIgnoredThe SDK has no per-turn output limit.
temperature, top_p, seed, stop, presence_penalty, frequency_penalty, logit_biasIgnoredThe SDK has no sampling options.
nIgnoredThe response always has one choice.
logprobs, top_logprobsIgnoredlogprobs is always null.
tools, tool_choice, parallel_tool_callsIgnoredThe client's tools are not offered to the model. Droid uses its own tools inside the turn.
user, metadata, store, service_tier, stream_optionsIgnoredThis proxy ignores these fields and omits usage, even if stream_options.include_usage is true.
Image, audio, and file content; assistant messages with a non-empty tool_calls, and tool messages; response_format other than textOutside this exampleRejected with 400 and an error code that names the limit, such as unsupported_content.

The proxy accepts and ignores any other top-level field. In HTTP 200 chat completion responses, x-droid-ignored-params lists ignored top-level field names made up of one or more ASCII letters, digits, _, or -. The header value is empty if no names qualify or if the comma-separated list exceeds 4,096 bytes.

Build the proxy

Use Node.js 22 or later. Install the CLI, both SDKs, and the TypeScript runner in the same project:

Bash
mkdir droid-openai-proxy && cd droid-openai-proxy
npm init -y
npm pkg set type=module
npm install --save-exact @factory/cli@1.21.0 @factory/droid-sdk@0.11.0 tsx@4.23.15 openai@7.64.0

Save the proxy as proxy.ts. It types the wire format with the openai package's request and response types, and checks each request against the subset it supports before starting Droid.

proxy.ts
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { randomUUID, timingSafeEqual } from 'node:crypto';
import { json } from 'node:stream/consumers';
import type OpenAI from 'openai';
import {
  AutonomyLevel,
  createSession,
  DroidMessageType,
  listModels,
  type DroidResult,
  type ReasoningEffort,
} from '@factory/droid-sdk/node';
 
type TextMessage = { role: 'system' | 'developer' | 'user' | 'assistant'; text: string };
 
const PORT = Number(process.env.PORT ?? 8787);
const DROID_CWD = process.env.DROID_CWD ?? process.cwd();
const PROXY_TOKEN = process.env.PROXY_TOKEN ?? '';
if (!PROXY_TOKEN) throw new Error('Set PROXY_TOKEN to the bearer token clients must send.');
 
// Top-level request fields this proxy reads.
const HANDLED: ReadonlySet<string> = new Set<keyof OpenAI.Chat.ChatCompletionCreateParams>([
  'model', 'messages', 'reasoning_effort', 'response_format', 'stream',
]);
const TEXT_ROLES: ReadonlySet<unknown> = new Set(['system', 'developer', 'user', 'assistant']);
const catalog = new Map((await listModels({ cwd: DROID_CWD })).map((model) => [model.id, model]));
 
class RequestError extends Error {
  constructor(readonly status: number, readonly code: string, message: string) {
    super(message);
  }
}
 
const isObject = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null && !Array.isArray(value);
const isTextPart = (part: unknown): part is OpenAI.Chat.ChatCompletionContentPartText =>
  isObject(part) && part.type === 'text' && typeof part.text === 'string';
// Replayed assistant replies can carry `tool_calls: null` or `[]` on a plain text turn.
const hasToolCalls = (value: unknown) => (Array.isArray(value) ? value.length > 0 : value != null);
 
function textMessage(message: unknown): TextMessage {
  if (!isObject(message) || !TEXT_ROLES.has(message.role) || hasToolCalls(message.tool_calls)) {
    throw new RequestError(400, 'unsupported_message', 'Tool calls and tool results are not supported.');
  }
  const role = message.role as TextMessage['role'];
  if (role === 'assistant' && message.content == null) return { role, text: '' };
  if (typeof message.content === 'string') return { role, text: message.content };
  if (Array.isArray(message.content) && message.content.every(isTextPart)) {
    return { role, text: message.content.map((part) => part.text).join('\n') };
  }
  throw new RequestError(400, 'unsupported_content', 'Only text content is supported, not images, audio, or files.');
}
 
function parseTurn(body: unknown) {
  if (!isObject(body) || typeof body.model !== 'string' || !Array.isArray(body.messages)) {
    throw new RequestError(400, 'invalid_request', 'Send a model string and a messages array.');
  }
  const model = catalog.get(body.model);
  if (!model) throw new RequestError(404, 'model_not_found', `GET /v1/models does not list '${body.model}'.`);
  const effort = (body.reasoning_effort ?? undefined) as ReasoningEffort | undefined;
  if (effort !== undefined && !model.supportedReasoningEfforts.includes(effort)) {
    const supported = model.supportedReasoningEfforts.join(', ');
    throw new RequestError(400, 'unsupported_reasoning_effort', `${model.id} supports ${supported}.`);
  }
  const format = body.response_format;
  if (format !== undefined && !(isObject(format) && format.type === 'text')) {
    throw new RequestError(400, 'unsupported_response_format', 'Only text responses are supported.');
  }
 
  const messages = body.messages.map(textMessage);
  const system = messages.filter((m) => m.role === 'system' || m.role === 'developer').map((m) => m.text);
  const turns = messages.filter((m) => m.role === 'user' || m.role === 'assistant');
  const last = turns.pop();
  if (last?.role !== 'user') {
    throw new RequestError(400, 'invalid_messages', 'The last user or assistant message must be from the user.');
  }
  // A new session has no history, so earlier turns travel as text in the prompt.
  const history = turns.map((m) => `${m.role}: ${m.text}`);
  const prompt = history.length
    ? ['Conversation so far:', ...history, 'Reply to this message from the user:', last.text].join('\n\n')
    : last.text;
  return {
    modelId: model.id,
    reasoningEffort: effort,
    system: system.join('\n\n'),
    prompt,
    stream: body.stream === true,
    ignored: Object.keys(body).filter((field) => !HANDLED.has(field) && /^[\w-]+$/.test(field)),
  };
}
 
// Runs one turn in a new session, passes streamed text to onText, and returns the last assistant message.
async function runTurn(turn: ReturnType<typeof parseTurn>, signal: AbortSignal, onText: (text: string) => void) {
  const session = await createSession({
    cwd: DROID_CWD,
    modelId: turn.modelId,
    reasoningEffort: turn.reasoningEffort,
    systemPrompt: turn.system ? { type: 'preset', preset: 'droid', append: turn.system } : undefined,
    autonomyLevel: AutonomyLevel.Off,
    abortSignal: signal,
  });
  try {
    let result: DroidResult | undefined;
    let messageId: string | undefined;
    for await (const event of session.stream(turn.prompt, { includePartialMessages: true, abortSignal: signal })) {
      if (event.type === DroidMessageType.AssistantTextDelta) {
        // One turn can hold several assistant messages, such as a line before a tool call and the answer.
        onText((messageId !== undefined && event.messageId !== messageId ? '\n\n' : '') + event.text);
        messageId = event.messageId;
      } else if (event.type === DroidMessageType.Result) {
        result = event;
      }
    }
    if (result?.subtype === 'interrupted') {
      throw new RequestError(502, 'turn_interrupted', 'The Droid turn was interrupted before it finished.');
    }
    if (!result?.success) {
      throw new RequestError(502, 'turn_failed', result?.error?.message ?? 'The Droid turn ended without a result.');
    }
    return result.text;
  } finally {
    await session.close();
  }
}
 
async function chatCompletions(req: IncomingMessage, res: ServerResponse) {
  const body = await json(req).catch(() => {
    throw new RequestError(400, 'invalid_json', 'The request body is not valid JSON.');
  });
  const turn = parseTurn(body);
  const clientGone = new AbortController();
  // 'close' also fires after a finished response; only an early close means the client left.
  res.on('close', () => {
    if (!res.writableEnded) clientGone.abort();
  });
  const head = { id: `chatcmpl-${randomUUID()}`, created: Math.floor(Date.now() / 1000), model: turn.modelId };
  const ignored = turn.ignored.join(',');
  const headers = { 'x-droid-ignored-params': ignored.length <= 4096 ? ignored : '' };
 
  if (!turn.stream) {
    const content = await runTurn(turn, clientGone.signal, () => {});
    const message = { role: 'assistant', content, refusal: null } as const;
    const completion: OpenAI.Chat.ChatCompletion = {
      ...head,
      object: 'chat.completion',
      choices: [{ index: 0, message, logprobs: null, finish_reason: 'stop' }],
    };
    return sendJson(res, 200, completion, headers);
  }
  res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
  const send = (delta: OpenAI.Chat.ChatCompletionChunk.Choice.Delta, finish_reason: 'stop' | null = null) => {
    const chunk: OpenAI.Chat.ChatCompletionChunk = {
      ...head,
      object: 'chat.completion.chunk',
      choices: [{ index: 0, delta, logprobs: null, finish_reason }],
    };
    res.write(`data: ${JSON.stringify(chunk)}\n\n`);
  };
  send({ role: 'assistant', content: '' });
  await runTurn(turn, clientGone.signal, (content) => send({ content }));
  send({}, 'stop');
  res.end('data: [DONE]\n\n');
}
 
function sendJson(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}) {
  res.writeHead(status, { ...headers, 'content-type': 'application/json' }).end(JSON.stringify(body));
}
 
function authorized(req: IncomingMessage): boolean {
  const sent = Buffer.from(req.headers.authorization ?? '');
  const expected = Buffer.from(`Bearer ${PROXY_TOKEN}`);
  return sent.length === expected.length && timingSafeEqual(sent, expected);
}
 
const server = createServer(async (req, res) => {
  try {
    if (!authorized(req)) throw new RequestError(401, 'invalid_api_key', 'Missing or wrong bearer token.');
    if (req.method === 'GET' && req.url === '/v1/models') {
      const toModel = (id: string): OpenAI.Models.Model => ({ id, object: 'model', created: 0, owned_by: 'factory' });
      sendJson(res, 200, { object: 'list', data: [...catalog.keys()].map(toModel) });
    } else if (req.method === 'POST' && req.url === '/v1/chat/completions') {
      await chatCompletions(req, res);
    } else {
      throw new RequestError(404, 'not_found', `${req.method} ${req.url} is not served here.`);
    }
  } catch (caught) {
    const failure = caught instanceof RequestError ? caught : new RequestError(500, 'internal_error', String(caught));
    const type = failure.status < 500 ? 'invalid_request_error' : 'server_error';
    const error: OpenAI.ErrorObject = { message: failure.message, type, code: failure.code, param: null };
    if (res.destroyed) return;
    // After the event stream has started, its 200 status is already sent, so the error goes out as an event.
    if (res.headersSent) res.end(`data: ${JSON.stringify({ error })}\n\n`);
    else sendJson(res, failure.status, { error });
  }
});
 
server.listen(PORT, '127.0.0.1', () => {
  console.log(`Listening on http://127.0.0.1:${PORT}/v1 with ${catalog.size} models`);
});

The proxy reads three environment variables. PROXY_TOKEN is the bearer token clients must send; the proxy refuses to start without it. PORT defaults to 8787; DROID_CWD defaults to the current directory. The proxy listens on 127.0.0.1 only.

Run the proxy

Use this loopback server only with trusted clients. They act under the server's Factory key. Autonomy Off declines actions that need approval; it does not prevent tools that need none. DROID_CWD is a starting directory, not a filesystem sandbox. Use an isolated OS identity or container with only the files clients may read.

The proxy does not reuse sessions. Closing a session does not erase its transcript; store: false does not control Droid storage.

Bash
export FACTORY_API_KEY="your-factory-api-key"
export PROXY_TOKEN="$(openssl rand -hex 32)"
mkdir -p workspace
DROID_CWD="$PWD/workspace" npx tsx proxy.ts

Send a request

Save this as client.ts and run it with npx tsx client.ts in a shell where PROXY_TOKEN is set to the proxy's token. It asks for at most one output token.

client.ts
import OpenAI from 'openai';
 
const client = new OpenAI({
  baseURL: 'http://127.0.0.1:8787/v1',
  apiKey: process.env.PROXY_TOKEN,
  maxRetries: 0,
});
 
const { data, response } = await client.chat.completions
  .create({
    model: 'claude-opus-5-5',
    messages: [{ role: 'user', content: 'Name the three primary colors of light.' }],
    max_tokens: 1,
  })
  .withResponse();
 
console.log(response.status, response.headers.get('x-droid-ignored-params'));
console.log(data.choices[0].message.content);

The first line prints 200 max_tokens. The second prints the answer, which is not limited to one token.

Each POST starts a new Droid session. Disable automatic retries so a failed request does not repeat the turn. Before streaming starts, failed and interrupted turns return HTTP 502. After streaming starts, the HTTP status stays 200 and the proxy sends a final error event instead of [DONE].