SPB Git

Repository Public

index.ts 14.6 KB 240 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : packages/workflow-engine/src/index.ts9 * Module           : workflow-engine10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Adaptive Navigator Engine, level 1: typed DSL executor. Recipes are data; no code, XPath, CSS or43// coordinates can be expressed. The executor talks to a Driver (Playwright in the worker, a fake in tests).44import { createHash } from 'node:crypto';45import { RecipeDefinition, TEMPLATE_VARS, type Action, type Condition, type Locator } from '@mls/contracts';46import { hostMatches } from '@mls/policy-engine';4748export interface Driver {49  currentUrl(): Promise<string>;50  navigate(url: string, timeoutMs: number): Promise<void>;51  isVisible(loc: Locator, timeoutMs: number): Promise<boolean>;52  isHidden(loc: Locator, timeoutMs: number): Promise<boolean>;53  textVisible(text: string, timeoutMs: number): Promise<boolean>;54  read(loc: Locator, what: 'text' | 'value' | 'count' | 'href', timeoutMs: number): Promise<string>;55  click(loc: Locator, timeoutMs: number): Promise<void>;56  fill(loc: Locator, value: string, timeoutMs: number): Promise<void>;57  select(loc: Locator, option: string, timeoutMs: number): Promise<void>;58  upload(loc: Locator, files: string[], timeoutMs: number): Promise<void>;59  /** Returns an opaque evidence reference; the driver masks every input and the given locators. */60  captureRedacted(label: string, mask: Locator[], timeoutMs: number): Promise<{ ref: string; sha256: string }>;61}62export type RunContext = {63  vars: Partial<Record<(typeof TEMPLATE_VARS)[number], string>>;64  approvedMediaPaths: string[];65  flags?: Partial<Record<'content.hasMedia' | 'content.hasLink', boolean>>;66  signal: AbortSignal;67  /** Re-checked before every step: lease still held, session state allows agents, no emergency stop. */68  guard(): Promise<{ ok: true } | { ok: false; reason: string }>;69  /** Persist "about to click an externally visible control" BEFORE the click. Must be durable. */70  beforeExternalEffect(stepId: string): Promise<void>;71  afterExternalEffect(stepId: string): Promise<void>;72  onStep?(r: StepResult): void;73};74export type StepResult = { id: string; action: string; status: 'ok' | 'skipped' | 'failed' | 'refused' | 'aborted' | 'stopped' | 'awaiting_approval'; ms: number; error?: string };75export type RunOutcome = {76  status: 'completed' | 'awaiting_approval' | 'stopped' | 'failed' | 'refused' | 'aborted';77  /** True once an external_submit click was attempted: the caller must never retry. */78  externalEffectAttempted: boolean;79  failedStep?: string; reason?: string; finalUrl?: string;80  steps: StepResult[]; inspected: Record<string, string>; evidence: { label: string; ref: string; sha256: string }[];81};8283export class RecipeValidationError extends Error { constructor(public issues: string[]) { super('recipe_invalid: ' + issues.join('; ')); } }84const TPL = /\{\{\s*([^}]*?)\s*\}\}/g;8586export function recipeSha256(def: RecipeDefinition): string {87  return createHash('sha256').update(JSON.stringify(def)).digest('hex');88}89/** Structural + semantic validation. Returns the parsed definition or throws RecipeValidationError. */90export function validateRecipe(input: unknown): RecipeDefinition {91  const parsed = RecipeDefinition.safeParse(input);92  if (!parsed.success) throw new RecipeValidationError(parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`));93  const def = parsed.data; const issues: string[] = [];94  const ids = new Set<string>();95  const walk = (v: unknown, path: string) => {96    if (typeof v === 'string') {97      for (const m of v.matchAll(TPL)) if (!(TEMPLATE_VARS as readonly string[]).includes(m[1])) issues.push(`${path}: variable inconnue {{${m[1]}}}`);98      if (/^\s*(javascript|data|file|chrome|about|vbscript):/i.test(v)) issues.push(`${path}: schéma interdit`);99    } else if (Array.isArray(v)) v.forEach((x, i) => walk(x, `${path}[${i}]`));100    else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) walk(x, `${path}.${k}`);101  };102  def.steps.forEach((s, i) => {103    if (ids.has(s.id)) issues.push(`steps[${i}]: id dupliqué ${s.id}`); ids.add(s.id);104    walk(s, `steps[${i}]`);105    if (s.action === 'navigate' && !s.url.includes('{{')) {106      try { const u = new URL(s.url); const h = u.port ? `${u.hostname}:${u.port}` : u.hostname; if (!def.allowedHosts.some((a) => hostMatches(h, a))) issues.push(`steps[${i}]: hôte hors périmètre ${h}`); }107      catch { issues.push(`steps[${i}]: URL invalide`); }108    }109    if (s.action === 'click' && s.effect === 'external_submit' && def.purpose !== 'submit') issues.push(`steps[${i}]: external_submit réservé aux recettes « submit »`);110  });111  const submits = def.steps.filter((s) => s.action === 'click' && s.effect === 'external_submit').length;112  if (def.purpose === 'submit' && submits !== 1) issues.push('une recette « submit » contient exactement un clic external_submit');113  if (def.purpose === 'prepare_composer' && !def.steps.some((s) => s.action === 'assertPage')) issues.push('prepare_composer exige une étape assertPage (identité de page)');114  if (def.purpose === 'prepare_composer' && def.steps.at(-1)?.action !== 'requestApproval') issues.push('prepare_composer se termine par requestApproval');115  if (issues.length) throw new RecipeValidationError(issues);116  return def;117}118119function render(tpl: string, vars: RunContext['vars']): string {120  return tpl.replace(TPL, (_, k: string) => {121    const v = vars[k as keyof RunContext['vars']];122    if (v === undefined || v === null) throw new Error(`variable_absente:${k}`);123    return v;124  });125}126function renderLoc(loc: Locator, vars: RunContext['vars']): Locator {127  const o: any = { ...loc };128  for (const k of ['name', 'label', 'text', 'placeholder']) if (typeof o[k] === 'string') o[k] = render(o[k], vars);129  if (o.within?.name) o.within = { ...o.within, name: render(o.within.name, vars) };130  return o;131}132function inScope(def: RecipeDefinition, url: string): boolean {133  try { const u = new URL(url); const h = u.port ? `${u.hostname}:${u.port}` : u.hostname; return def.allowedHosts.some((a) => hostMatches(h, a) || hostMatches(u.hostname, a)); } catch { return false; }134}135async function checkCond(d: Driver, c: Condition, vars: RunContext['vars'], timeoutMs: number): Promise<boolean> {136  switch (c.kind) {137    case 'urlStartsWith': return (await d.currentUrl()).startsWith(render(c.value, vars));138    case 'visible': return d.isVisible(renderLoc(c.locator, vars), timeoutMs);139    case 'hidden': return d.isHidden(renderLoc(c.locator, vars), timeoutMs);140    case 'textVisible': return d.textVisible(render(c.text, vars), timeoutMs);141    case 'valueEquals': return (await d.read(renderLoc(c.locator, vars), 'value', timeoutMs)).trim() === render(c.value, vars).trim();142  }143}144const norm = (s: string) => s.normalize('NFC').replace(/\s+/g, ' ').trim().toLowerCase();145146export async function runRecipe(defInput: RecipeDefinition, driver: Driver, ctx: RunContext): Promise<RunOutcome> {147  const def = validateRecipe(defInput);148  const out: RunOutcome = { status: 'completed', externalEffectAttempted: false, steps: [], inspected: {}, evidence: [] };149  const finish = async (status: RunOutcome['status'], step?: Action, reason?: string): Promise<RunOutcome> => { out.status = status; out.failedStep = step?.id; out.reason = reason; out.finalUrl = await driver.currentUrl().catch(() => undefined); return out; };150151  for (const step of def.steps) {152    const t0 = Date.now();153    const rec = (status: StepResult['status'], error?: string) => { const r = { id: step.id, action: step.action, status, ms: Date.now() - t0, error }; out.steps.push(r); ctx.onStep?.(r); };154    if (ctx.signal.aborted) { rec('aborted', 'signal'); return finish('aborted', step, 'aborted'); }155    if (step.when && !ctx.flags?.[step.when]) { rec('skipped'); continue; }156    const g = await ctx.guard();157    if (!g.ok) { rec('aborted', g.reason); return finish('aborted', step, g.reason); }158    try {159      // The page we are on must still be in scope before touching anything (a redirect may have moved us).160      const here = await driver.currentUrl();161      if (step.action !== 'navigate' && step.action !== 'stop' && here !== 'about:blank' && !inScope(def, here)) { rec('refused', 'page_hors_perimetre'); return finish('refused', step, 'page_hors_perimetre'); }162      for (const c of step.pre ?? []) if (!(await checkCond(driver, c, ctx.vars, Math.min(step.timeoutMs, 5000)))) { rec('failed', `precondition:${c.kind}`); return finish('failed', step, `precondition:${c.kind}`); }163      const to = step.timeoutMs;164      switch (step.action) {165        case 'navigate': {166          const url = render(step.url, ctx.vars);167          if (!inScope(def, url)) { rec('refused', 'hote_hors_perimetre'); return finish('refused', step, 'hote_hors_perimetre'); }168          await driver.navigate(url, to);169          if (!inScope(def, await driver.currentUrl())) { rec('refused', 'redirection_hors_perimetre'); return finish('refused', step, 'redirection_hors_perimetre'); }170          break;171        }172        case 'inspect': out.inspected[step.as] = await driver.read(renderLoc(step.locator, ctx.vars), step.read, to); break;173        case 'click': {174          const loc = renderLoc(step.locator, ctx.vars);175          if (step.effect === 'external_submit') {176            if (!(await driver.isVisible(loc, to))) { rec('failed', 'cible_absente'); return finish('failed', step, 'cible_absente'); }177            await ctx.beforeExternalEffect(step.id);178            out.externalEffectAttempted = true;179            await driver.click(loc, to);180            await ctx.afterExternalEffect(step.id);181          } else await driver.click(loc, to);182          break;183        }184        case 'fill': {185          const loc = renderLoc(step.locator, ctx.vars); const value = render(step.value, ctx.vars);186          await driver.fill(loc, value, to);187          const got = await driver.read(loc, 'value', to);188          if (norm(got) !== norm(value)) throw new Error('valeur_non_conforme_apres_saisie');189          break;190        }191        case 'select': await driver.select(renderLoc(step.locator, ctx.vars), render(step.option, ctx.vars), to); break;192        case 'uploadApprovedMedia':193          if (!ctx.approvedMediaPaths.length) throw new Error('aucun_media_approuve');194          await driver.upload(renderLoc(step.locator, ctx.vars), ctx.approvedMediaPaths, to); break;195        case 'waitFor': if (!(await checkCond(driver, step.cond, ctx.vars, to))) throw new Error(`attente_expiree:${step.cond.kind}`); break;196        case 'captureRedacted': {197          const ev = await driver.captureRedacted(step.label, (step.mask ?? []).map((m) => renderLoc(m, ctx.vars)), to);198          out.evidence.push({ label: step.label, ...ev }); break;199        }200        case 'assertPage': {201          if (step.expectedName) {202            if (!step.nameLocator) throw new Error('assertPage_sans_nameLocator');203            const seen = await driver.read(renderLoc(step.nameLocator, ctx.vars), 'text', to);204            if (norm(seen) !== norm(render(step.expectedName, ctx.vars))) { rec('refused', 'identite_de_page_differente'); return finish('refused', step, 'identite_de_page_differente'); }205          }206          if (step.expectedExternalId) {207            const id = render(step.expectedExternalId, ctx.vars);208            if (!(await driver.currentUrl()).includes(id)) { rec('refused', 'identifiant_de_page_different'); return finish('refused', step, 'identifiant_de_page_different'); }209          }210          break;211        }212        case 'requestApproval': rec('awaiting_approval'); return finish('awaiting_approval', step, step.reason);213        case 'stop': rec('stopped'); return finish('stopped', step, step.reason);214      }215      for (const c of step.post ?? []) if (!(await checkCond(driver, c, ctx.vars, to))) throw new Error(`postcondition:${c.kind}`);216      if (ctx.signal.aborted) { rec('aborted', 'signal'); return finish('aborted', step, 'aborted'); }217      rec('ok');218    } catch (e: any) {219      const msg = ctx.signal.aborted ? 'aborted' : String(e?.message ?? e).slice(0, 300);220      rec(ctx.signal.aborted ? 'aborted' : 'failed', msg);221      return finish(ctx.signal.aborted ? 'aborted' : 'failed', step, msg);222    }223  }224  out.finalUrl = await driver.currentUrl().catch(() => undefined);225  return out;226}227228/* ───────────── Level 2: repair plan proposed by a vision model ─────────────229   The model only ever returns DATA validated by the same schema. A proposal is stored as a DRAFT230   recipe version and cannot run until a human validates it. */231export function parseRepairProposal(raw: unknown, original: RecipeDefinition): RecipeDefinition {232  const def = validateRecipe(raw);233  if (def.slug !== original.slug || def.purpose !== original.purpose) throw new RecipeValidationError(['la proposition change le slug ou la finalité']);234  const extra = def.allowedHosts.filter((h) => !original.allowedHosts.includes(h));235  if (extra.length) throw new RecipeValidationError([`la proposition élargit le périmètre : ${extra.join(', ')}`]);236  const count = (d: RecipeDefinition) => d.steps.filter((s) => s.action === 'click' && s.effect === 'external_submit').length;237  if (count(def) > count(original)) throw new RecipeValidationError(['la proposition ajoute un clic à effet externe']);238  return def;239}240
Files main
Menu

Theme