Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

3.4 KB
Raw Blame
import type { AgentState } from '@lobechat/agent-runtime';
import debug from 'debug';

import { type AgentExecutionResult } from '../types';
import type { AgentRuntimeDelegate, AgentRuntimeServiceContext } from './types';

const log = debug('lobe-server:agent-runtime-service');

/** What this module reads off the service. */
export type ShareRunGateDeps = Pick<
  AgentRuntimeServiceContext,
  'completionLifecycle' | 'coordinator' | 'interruptOperation'
>;

/**
 * Whether an Agent Share visitor run has lost its authorization. Fails closed:
 * a read failure is treated as revoked. Non-share runs are never revoked.
 */
export async function isShareRunRevoked(
  verify: AgentRuntimeDelegate['verifyShareRunStillAuthorized'],
  operationId: string,
  stepIndex: number,
  agentState: AgentState,
): Promise<boolean> {
  if (!verify) return false;
  const shareMarker = agentState.principal?.actor?.shareVisitor as
    { agentId?: string; shareId?: string; visitorUserId?: string } | undefined;
  if (!shareMarker?.agentId || !shareMarker.shareId) return false;
  try {
    return !(await verify({
      agentId: shareMarker.agentId,
      shareId: shareMarker.shareId,
      visitorUserId: shareMarker.visitorUserId,
    }));
  } catch (error) {
    log('[%s][%d] Share run authorization re-check failed: %O', operationId, stepIndex, error);
    return true;
  }
}

/**
 * Terminate an Agent Share visitor run whose authorization was revoked
 * mid-flight (see the per-step check in `executeStep`).
 *
 * Persists `interrupted` onto the already-loaded state β€” the same terminal
 * status a visitor's own Stop produces β€” so the client's stream settles
 * normally instead of hanging. Falls back to `interruptOperation` when no
 * state was readable. A persistence failure is logged, never rethrown: the
 * run must stop regardless of whether the terminal status could be written.
 *
 * The completion lifecycle (`emitSignalEvents` + `dispatchHooks`) must run
 * here too: this abort short-circuits `executeStep` before `runtime.step()`,
 * so no downstream path is left to persist the terminal status. Without it
 * `saveAgentState` would only update the runtime-state cache and publish the
 * terminal stream event, leaving `agent_operations` stuck on `running` β€”
 * which `TopicModel.tryReserveTaskCallback` then reads as a live run and
 * blocks the visitor's next send on that topic for the abandoned-run TTL.
 */
export async function buildShareAbortResult(
  deps: ShareRunGateDeps,
  operationId: string,
  state: AgentState | null | undefined,
): Promise<AgentExecutionResult> {
  log('[%s] Aborting share visitor run β€” the share is no longer authorized', operationId);

  try {
    if (state) {
      const interruptedState: AgentState = {
        ...state,
        lastModified: new Date().toISOString(),
        status: 'interrupted',
      };
      await deps.coordinator.saveAgentState(operationId, interruptedState);

      await deps.completionLifecycle.emitSignalEvents(operationId, interruptedState, 'interrupted');
      await deps.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');
    } else {
      await deps.interruptOperation(operationId);
    }
  } catch (error) {
    log(
      '[%s] Failed to persist interrupted state for an aborted share run: %O',
      operationId,
      error,
    );
  }

  return {
    nextStepScheduled: false,
    state: { status: 'interrupted' },
    stepResult: null,
    success: false,
  };
}