Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Wallet8 * File : services/research-runner/src/runner.ts9 * Module : services10 * Repository : https://git.spboucher.ai/sp-wallet11 * Project Website : https://wallet.spboucher.ai12 * Created : 2026-11-1113 * Last Modified : 2026-11-1114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// The runner loop: claim one job, run it, push its log and its result. One job at a time.44import { MAX_LOG_BATCH, type RunnerJob, type RunnerResult } from '@spw/core/research-job';45import type { LogLine, RunnerApi } from './api-client.ts';46import type { RunnerConfig } from './config.ts';47import { runJob } from './job.ts';4849/** Run one claimed job to its result, streaming the log. Never throws: a runner error is a `failed` result. */50export async function processJob(job: RunnerJob, cfg: RunnerConfig, api: RunnerApi): Promise<RunnerResult> {51 const buffer: LogLine[] = []; let cancel = false, sending: Promise<void> = Promise.resolve(), dropped = 0, announce = false;52 const flush = (): Promise<void> => {53 sending = sending.then(async () => {54 while (buffer.length || announce) {55 const batch = buffer.splice(0, MAX_LOG_BATCH), state = announce ? 'running' as const : undefined; announce = false;56 try { if ((await api.log(job, batch, state)).cancel) cancel = true; } catch { /* the API is away: the job goes on, these lines are lost */ }57 }58 });59 return sending;60 };61 // v10: a cancel request is learned from the ANSWER to a log push. An agent that prints nothing (thinking, or hung) pushed62 // nothing, so the owner's cancel never reached the runner until the wall-clock budget: a silent job could not be cancelled.63 // When there is nothing to send, an empty batch is pushed every heartbeat (4 s by default) to ask.64 const heartbeatMs = Math.min(5000, cfg.logFlushMs * 2); let lastPush = Date.now();65 const heartbeat = (): void => {66 if (cancel || buffer.length || announce || Date.now() - lastPush < heartbeatMs) return;67 lastPush = Date.now();68 sending = sending.then(async () => { try { if ((await api.log(job, [])).cancel) cancel = true; } catch { /* the API is away: asked again at the next heartbeat */ } });69 };70 const timer = setInterval(() => { if (buffer.length || announce) lastPush = Date.now(); void flush(); heartbeat(); }, cfg.logFlushMs);71 const result = await runJob(job, cfg, {72 log: (s, t) => { if (buffer.length < 5000) buffer.push({ s, t }); else dropped += 1; },73 running: () => { announce = true; void flush(); },74 cancelRequested: () => cancel,75 });76 clearInterval(timer);77 if (dropped) buffer.push({ s: 'sys', t: `${dropped} log lines were dropped (the agent wrote faster than the log is sent)` });78 await flush();79 return result;80}8182export async function pushResult(job: RunnerJob, result: RunnerResult, api: RunnerApi, attempts = 5): Promise<boolean> {83 for (let i = 0; i < attempts; i++) {84 try { await api.result(job, result); return true; } catch (e) { if (i === attempts - 1) { console.error(`result of ${job.id} could not be pushed: ${(e as Error).message}`); return false; } await new Promise((r) => setTimeout(r, 1000 * 2 ** i)); }85 }86 return false;87}8889export async function runOnce(cfg: RunnerConfig, api: RunnerApi): Promise<RunnerResult | null> {90 const job = await api.claim();91 if (!job) return null;92 const result = await processJob(job, cfg, api);93 await pushResult(job, result, api);94 return result;95}9697export function startRunner(cfg: RunnerConfig, api: RunnerApi): () => void {98 let stopped = false;99 void (async () => {100 while (!stopped) {101 try { if (!(await runOnce(cfg, api))) await new Promise((r) => setTimeout(r, cfg.pollMs)); }102 catch (e) { console.error(`runner: ${(e as Error).message}`); await new Promise((r) => setTimeout(r, Math.max(cfg.pollMs, 5000))); }103 }104 })();105 return () => { stopped = true; };106}107