import { requestJSON } from './http-client.mjs';
try {
const model = process.env.API_MODEL;
const mode = process.env.API_REASONING_MODE || 'responses';
const effort = process.env.API_REASONING_EFFORT || 'medium';
if (!model?.trim() || !['chat', 'responses'].includes(mode)
|| !['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'].includes(effort)) {
throw new Error('Invalid model, protocol, or effort.');
}
const history = [{ role: 'user', content: 'Find the smallest positive integer divisible by both 6 and 8.' }];
const answers = [];
for (let turn = 0; turn < (mode === 'chat' ? 1 : 2); turn++) {
const result = await requestJSON(mode === 'chat' ? '/v1/chat/completions' : '/v1/responses',
mode === 'chat' ? { model, messages: history, reasoning_effort: effort }
: { model, input: history, reasoning: { effort }, store: false,
include: ['reasoning.encrypted_content'], instructions: 'Return a short final answer.' });
if (mode === 'chat') {
const choice = result.choices?.[0];
const message = choice?.message;
if (!Array.isArray(result.choices) || result.choices.length !== 1 || choice?.index !== 0
|| choice.finish_reason !== 'stop' || message?.role !== 'assistant'
|| message.refusal != null || message.tool_calls != null || message.function_call != null
|| typeof message.content !== 'string' || !message.content.trim()) {
throw new Error('No complete final text.');
}
answers.push(message.content);
continue;
}
if (result.status !== 'completed' || !Array.isArray(result.output) || !result.output.length) {
throw new Error('Incomplete response.');
}
const text = [];
for (const item of result.output) {
if (item?.type === 'reasoning') {
// This stateless replay example requires opaque state whenever a reasoning item exists.
if (typeof item.encrypted_content !== 'string' || !item.encrypted_content.trim()) {
throw new Error('Reasoning state is not replayable by this example.');
}
} else if (item?.type === 'message' && item.role === 'assistant' && item.status === 'completed'
&& Array.isArray(item.content) && item.content.length) {
for (const part of item.content) {
if (part?.type !== 'output_text' || typeof part.text !== 'string') throw new Error('Unexpected content.');
text.push(part.text);
}
} else { throw new Error('Unexpected output item.'); }
}
if (!text.join('').trim()) throw new Error('No final text.');
answers.push(text.join(''));
// Preserve complete items and unknown metadata, including phase; never log encrypted state.
history.push(...result.output, { role: 'user', content: 'Now find the smallest positive multiple also divisible by 5.' });
}
console.log(JSON.stringify({ answers }));
} catch {
console.error('Reasoning example failed. Check model support, replayable state, and completion status. No automatic retry.');
process.exitCode = 1;
}