86 lines
2.3 KiB
TypeScript
86 lines
2.3 KiB
TypeScript
import type { ClientName, ExecResult, DebugInfo, Job } from "./types.js";
|
|
|
|
export interface RunContext {
|
|
jsonMode: boolean;
|
|
stdoutWrite: (chunk: string) => void;
|
|
stderrWrite: (chunk: string) => void;
|
|
}
|
|
|
|
export function reportError(err: unknown, jsonMode: boolean): number {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
if (jsonMode) {
|
|
console.error(JSON.stringify({ error: message }, null, 2));
|
|
} else {
|
|
console.error(message);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
export function reportCliError(message: string, jsonMode: boolean): number {
|
|
if (jsonMode) {
|
|
console.error(JSON.stringify({ error: message }, null, 2));
|
|
} else {
|
|
console.error(`Error: ${message}`);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
export async function handleSyncRun(
|
|
executePrompt: (
|
|
client: ClientName,
|
|
prompt: string,
|
|
options?: { timeoutMs?: number; debug?: boolean; onDebug?: (info: DebugInfo) => void }
|
|
) => Promise<ExecResult>,
|
|
client: ClientName,
|
|
prompt: string,
|
|
timeoutMs: number | undefined,
|
|
debug: boolean,
|
|
ctx: RunContext
|
|
): Promise<number> {
|
|
try {
|
|
const result = await executePrompt(client, prompt, {
|
|
timeoutMs,
|
|
debug,
|
|
onDebug: debug ? (info) => ctx.stderrWrite(JSON.stringify(info) + "\n") : undefined,
|
|
});
|
|
if (ctx.jsonMode) {
|
|
console.log(JSON.stringify(result, null, 2));
|
|
} else {
|
|
if (result.stdout) ctx.stdoutWrite(result.stdout);
|
|
if (result.stderr) ctx.stderrWrite(result.stderr);
|
|
}
|
|
return 0;
|
|
} catch (err) {
|
|
return reportError(err, ctx.jsonMode);
|
|
}
|
|
}
|
|
|
|
export async function handleAsyncRun(
|
|
startJob: (
|
|
client: ClientName,
|
|
prompt: string,
|
|
options?: { timeoutMs?: number; debug?: boolean; onDebug?: (info: DebugInfo) => void }
|
|
) => Promise<Job>,
|
|
client: ClientName,
|
|
prompt: string,
|
|
timeoutMs: number | undefined,
|
|
debug: boolean,
|
|
ctx: RunContext
|
|
): Promise<number> {
|
|
try {
|
|
const job = await startJob(client, prompt, {
|
|
timeoutMs,
|
|
debug,
|
|
onDebug: debug ? (info) => ctx.stderrWrite(JSON.stringify(info) + "\n") : undefined,
|
|
});
|
|
if (ctx.jsonMode) {
|
|
console.log(JSON.stringify({ jobId: job.id, client: job.client, status: job.status }, null, 2));
|
|
} else {
|
|
console.log(`Job ${job.id} started (${job.client}): ${job.status}`);
|
|
}
|
|
return 0;
|
|
} catch (err) {
|
|
return reportError(err, ctx.jsonMode);
|
|
}
|
|
}
|