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.

1.7 KB
Raw Blame
import type { LobeChatDatabase } from '@lobechat/database';
import type {
  DeviceToolCallResult,
  GatewayToolCallCompletion,
} from '@lobechat/device-gateway-client';
import type { DeviceClient } from '@lobechat/types';

import { resolveDeviceDispatchAuthorizationFailure } from './dispatchAuthorization';
import { deviceGateway } from './index';

/**
 * Executes a device tool call after a last-moment workspace registry check.
 *
 * Use when:
 * - An Agent runtime dispatches new work to its active device
 *
 * Expects:
 * - `workspaceId`, when present, is the same principal used during target selection
 *
 * Returns:
 * - The Gateway result, or immediate structured `DEVICE_NOT_FOUND` after Unshare
 */
export const executeAuthorizedDeviceToolCall = async (
  serverDB: LobeChatDatabase | undefined,
  params: {
    /** Device clients that may serve the call; see `deviceGateway.executeToolCall`. */
    clientKinds?: DeviceClient[];
    /** Lets the device report this call's final result later; see `buildShellCompletion`. */
    completion?: GatewayToolCallCompletion;
    deviceId: string;
    operationId?: string;
    userId: string;
    workspaceId?: string;
  },
  toolCall: { apiName: string; arguments: string; identifier: string },
  timeout?: number,
): Promise<DeviceToolCallResult> => {
  const errorData = await resolveDeviceDispatchAuthorizationFailure(
    serverDB,
    params.userId,
    params.deviceId,
    params.workspaceId,
  );
  if (errorData) {
    return {
      content: 'The workspace device is no longer registered or visible for this run.',
      error: 'DEVICE_NOT_FOUND',
      errorData,
      success: false,
    };
  }

  return deviceGateway.executeToolCall(params, toolCall, timeout);
};