// EOF and Stop drain submissions. Shutdown cancels invocations and preserves durable tasks for restart. export async function serve(harness: any, context: any, afterSubmit?: () => Promise, api?: any, defaultConversation?: () => Promise) { const pending = new Set>(); const track = (work: Promise) => { const task = work.catch(error => Deno.core.ops.op_output(`${String(error)}\n`)).finally(() => pending.delete(task)); pending.add(task); }; while (true) { const input = await Deno.core.ops.op_input(); if (input?.type === 'shutdown') { // Close cancels invocations without terminal outcomes, so durable tasks resume after restart. await harness.close(context); await Promise.all(pending); return; } if (input === null || input.type === 'stop') { await harness.waitForIdle(context); await Promise.all(pending); return; } if (input.type === 'api') { track(api.handle(input)); continue; } const id = defaultConversation ? await defaultConversation() : input.conversation; const conversation = await harness.conversation(id, context); if (!conversation) throw new Error(`Unknown conversation: ${id}`); const submission = await conversation.submit({ type: 'input', content: input.content, requestId: input.requestId, }, context); if (afterSubmit) { track(submission.wait(context).then(async (result: any) => { await afterSubmit(); if (result.status !== 'done') throw new Error(`Run ended: ${JSON.stringify(result)}`); })); } } }