← Files Flows by plugin.spaceARCHIVED FILE

lib/flow-work.mjs

1.29 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { randomUUID } from 'node:crypto';

// Ephemeral, project-scoped work. A late completion cannot clear a newer task.
// Expiration also recovers from a stopped chat that cannot send its final call.
export function createFlowWork({ now = Date.now } = {}) {
  const tasks = new Map();
  const ttl = 30 * 60 * 1000;
  const current = workspace => {
    const task = tasks.get(workspace);
    if (task && task.expiresAt <= now()) { tasks.delete(workspace); return undefined; }
    return task;
  };
  return {
    current,
    start(workspace, flowId, activityId) {
      const previous = current(workspace);
      if (activityId && previous?.id !== activityId) throw Object.assign(new Error('This flow task is no longer active. Start a new task.'), { status: 409 });
      const renewing = Boolean(activityId && previous?.id === activityId);
      const target = flowId || (renewing ? previous.flowId : undefined);
      const task = { id: activityId || randomUUID(), startedAt: renewing ? previous.startedAt : now(), expiresAt: now() + ttl, ...(target ? { flowId: target } : {}) };
      tasks.set(workspace, task);
      return task;
    },
    finish(workspace, activityId) {
      if (current(workspace)?.id === activityId) tasks.delete(workspace);
    },
    forget(workspace) { tasks.delete(workspace); },
  };
}

SHA-256: 876b8eaa941f072712b961c2da0538f0f04555538d061e18017a81abe6805e1f