feat(M3): Async CLI Integration
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user