{"version":3,"sources":["../src/worker.ts","../../node_modules/.pnpm/tsup@8.4.0_@microsoft+api-extractor@7.58.12_@types+node@22.19.1__postcss@8.5.23_tsx@4.23.1_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { JobAssignment, JobTermination, TrackSource } from '@livekit/protocol';\nimport {\n  type AvailabilityRequest,\n  JobType,\n  ParticipantPermission,\n  ServerMessage,\n  WorkerMessage,\n  WorkerStatus,\n} from '@livekit/protocol';\nimport { type Throws, ThrowsPromise } from '@livekit/throws-transformer/throws';\nimport type { ParticipantInfo } from 'livekit-server-sdk';\nimport { AccessToken, RoomServiceClient } from 'livekit-server-sdk';\nimport { EventEmitter } from 'node:events';\nimport { availableParallelism } from 'node:os';\nimport { extname } from 'node:path';\nimport { WebSocket } from 'ws';\nimport { APIStatusError } from './_exceptions.js';\nimport { ATTRIBUTE_AGENT_NAME } from './constants.js';\nimport { getCpuMonitor } from './cpu.js';\nimport { HTTPServer } from './http_server.js';\nimport { _getLocalInferenceModule } from './inference/_warmup.js';\nimport { EOT_INFERENCE_METHOD } from './inference/eot/runner.js';\nimport { InferenceRunner } from './inference_runner.js';\nimport { InferenceProcExecutor } from './ipc/inference_proc_executor.js';\nimport { ProcPool } from './ipc/proc_pool.js';\nimport type { JobAcceptArguments, JobProcess, RunningJobInfo } from './job.js';\nimport { JobRequest } from './job.js';\nimport { DEFAULT_SESSION_END_TIMEOUT, validateSessionEndTimeout } from './job_lifecycle.js';\nimport { log } from './log.js';\nimport {\n  type EventLoopMonitor,\n  startMonitoring,\n  stopMonitoring,\n} from './telemetry/loop_monitor.js';\nimport { Future, rejectOnAbort } from './utils.js';\nimport { version } from './version.js';\n\nconst MAX_RECONNECT_ATTEMPTS = 10;\nconst ASSIGNMENT_TIMEOUT = 7.5 * 1000;\nconst UPDATE_LOAD_INTERVAL = 2.5 * 1000;\nconst DRAIN_TIMEOUT = 60 * 60 * 1000;\nconst PROJECT_TYPE = 'nodejs';\n// Mirrors CurrentWorkerProtocol in livekit/protocol. LiveKit Cloud reads this off\n// the /worker endpoint to decide whether the SDK supports agent deployments; a\n// worker that omits it is treated as legacy and registered without its deployment.\nconst WORKER_PROTOCOL_VERSION = 1;\n\nlet localEotRunnerRegistered = false;\n/**\n * Register the local audio-EOT inference runner so it runs in the shared\n * inference process. Idempotent and guarded by native-binding availability;\n * a no-op (with a one-time warning) when `@livekit/local-inference` can't be\n * loaded so the worker still starts on unsupported platforms.\n */\nfunction maybeRegisterLocalEotRunner(): void {\n  if (localEotRunnerRegistered) return;\n  localEotRunnerRegistered = true;\n  if (InferenceRunner.registeredRunners[EOT_INFERENCE_METHOD]) return;\n  if (_getLocalInferenceModule() === undefined) {\n    log().warn(\n      '@livekit/local-inference native binding unavailable; local audio EOT disabled ' +\n        '(predictions will degrade to a positive default). cloud EOT and other turn ' +\n        'detection modes are unaffected.',\n    );\n    return;\n  }\n  const ext = extname(import.meta.url); // '.js' (built) or '.ts' (tsx/ts-node)\n  InferenceRunner.registerRunner(\n    EOT_INFERENCE_METHOD,\n    new URL(`./inference/eot/runner${ext}`, import.meta.url).toString(),\n  );\n}\n\nclass Default {\n  static loadThreshold(production: boolean): number {\n    if (production) {\n      return 0.7;\n    } else {\n      return Infinity;\n    }\n  }\n\n  static numIdleProcesses(production: boolean): number {\n    if (production) {\n      return Math.min(availableParallelism(), 4);\n    } else {\n      return 0;\n    }\n  }\n\n  static port(production: boolean): number {\n    if (production) {\n      return 8081;\n    } else {\n      return 0;\n    }\n  }\n}\n\n/** Necessary credentials not provided and not found in an appropriate environment variable. */\nexport class MissingCredentialsError extends Error {\n  constructor(msg?: string) {\n    super(msg);\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/** Worker did not run as expected. */\nexport class WorkerError extends Error {\n  constructor(msg?: string) {\n    super(msg);\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/** @internal */\nexport const defaultInitializeProcessFunc = (_: JobProcess) => _;\nconst defaultRequestFunc = async (ctx: JobRequest) => {\n  await ctx.accept();\n};\n\nconst cpuMonitor = getCpuMonitor();\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst defaultCpuLoad = async (_worker: AgentServer): Promise<number> => {\n  return cpuMonitor.cpuPercent(UPDATE_LOAD_INTERVAL);\n};\n\n/** Participant permissions to pass to every agent spun up by this worker. */\nexport class WorkerPermissions {\n  canPublish: boolean;\n  canSubscribe: boolean;\n  canPublishData: boolean;\n  canUpdateMetadata: boolean;\n  canPublishSources: TrackSource[];\n  hidden: boolean;\n\n  constructor(\n    canPublish = true,\n    canSubscribe = true,\n    canPublishData = true,\n    canUpdateMetadata = true,\n    canPublishSources: TrackSource[] = [],\n    hidden = false,\n  ) {\n    this.canPublish = canPublish;\n    this.canSubscribe = canSubscribe;\n    this.canPublishData = canPublishData;\n    this.canUpdateMetadata = canUpdateMetadata;\n    this.canPublishSources = canPublishSources;\n    this.hidden = hidden;\n  }\n}\n\n/**\n * Data class describing worker behaviour.\n *\n * @remarks\n * The Agents framework provides sane worker defaults, and works out-of-the-box with no tweaking\n * necessary. The only mandatory parameter is `agent`, which points to the entry function.\n *\n * This class is mostly useful in conjunction with {@link cli.runApp}.\n */\nexport class ServerOptions {\n  agent: string;\n  requestFunc: (job: JobRequest) => Promise<void>;\n  loadFunc: (worker: AgentServer) => Promise<number>;\n  loadThreshold: number;\n  numIdleProcesses: number;\n  drainTimeout: number;\n  shutdownProcessTimeout: number;\n  /**\n   * Maximum time to wait for `onSessionEnd`. Defaults to five minutes.\n   */\n  sessionEndTimeout: number;\n  initializeProcessTimeout: number;\n  permissions: WorkerPermissions;\n  agentName: string;\n  agentNameIsEnv: boolean;\n  serverType: JobType;\n  maxRetry: number;\n  wsURL: string;\n  apiKey?: string;\n  apiSecret?: string;\n  workerToken?: string;\n  host: string;\n  port: number;\n  logLevel: string;\n  production: boolean;\n  simulation: boolean;\n  jobMemoryWarnMB: number;\n  jobMemoryLimitMB: number;\n\n  /** @param options - Worker options */\n  constructor({\n    agent,\n    requestFunc = defaultRequestFunc,\n    loadFunc = defaultCpuLoad,\n    loadThreshold = undefined,\n    numIdleProcesses = undefined,\n    drainTimeout = DRAIN_TIMEOUT,\n    shutdownProcessTimeout = 60 * 1000,\n    sessionEndTimeout = DEFAULT_SESSION_END_TIMEOUT,\n    initializeProcessTimeout = 10 * 1000,\n    permissions = new WorkerPermissions(),\n    agentName = '',\n    agentNameIsEnv = undefined,\n    serverType = JobType.JT_ROOM,\n    maxRetry = MAX_RECONNECT_ATTEMPTS,\n    wsURL = 'ws://localhost:7880',\n    apiKey = undefined,\n    apiSecret = undefined,\n    workerToken = undefined,\n    host = '0.0.0.0',\n    port = undefined,\n    logLevel = 'info',\n    production = false,\n    simulation = false,\n    jobMemoryWarnMB = 1000,\n    jobMemoryLimitMB = 0,\n  }: {\n    /**\n     * Path to a file that has {@link Agent} as a default export, dynamically imported later for\n     * entrypoint and prewarm functions\n     */\n    agent: string;\n    requestFunc?: (job: JobRequest) => Promise<void>;\n    /** Called to determine the current load of the worker. Should return a value between 0 and 1. */\n    loadFunc?: (worker: AgentServer) => Promise<number>;\n    /** When the load exceeds this threshold, the worker will be marked as unavailable. */\n    loadThreshold?: number;\n    numIdleProcesses?: number;\n    /** Number of milliseconds to wait for current jobs to finish upon shutdown. */\n    drainTimeout?: number;\n    shutdownProcessTimeout?: number;\n    /**\n     * Maximum number of milliseconds to wait for `onSessionEnd`.\n     */\n    sessionEndTimeout?: number;\n    initializeProcessTimeout?: number;\n    permissions?: WorkerPermissions;\n    /**\n     * Set agentName to enable explicit dispatch. When explicit dispatch is enabled, jobs will not\n     * be dispatched to rooms automatically. Instead, you can either specify the agent(s) to be\n     * dispatched in the end-user's token, or use the AgentDispatch.createDispatch API.\n     *\n     * By default it uses `LIVEKIT_AGENT_NAME` from environment.\n     */\n    agentName?: string;\n    /**\n     * Internal flag indicating that `agentName` was resolved from `LIVEKIT_AGENT_NAME`. Forwarded\n     * through ServerOptions re-construction (e.g. cli.ts spread) so the env-source signal isn't\n     * lost.\n     */\n    agentNameIsEnv?: boolean;\n    serverType?: JobType;\n    maxRetry?: number;\n    wsURL?: string;\n    apiKey?: string;\n    apiSecret?: string;\n    workerToken?: string;\n    host?: string;\n    port?: number;\n    logLevel?: string;\n    production?: boolean;\n    simulation?: boolean;\n    jobMemoryWarnMB?: number;\n    jobMemoryLimitMB?: number;\n  }) {\n    this.agent = agent;\n    if (!this.agent) {\n      throw new Error('No Agent file was passed to the worker');\n    }\n    this.requestFunc = requestFunc;\n    this.loadFunc = loadFunc;\n    this.loadThreshold = simulation ? Infinity : loadThreshold || Default.loadThreshold(production);\n    this.numIdleProcesses = numIdleProcesses || Default.numIdleProcesses(production);\n    this.drainTimeout = drainTimeout;\n    this.shutdownProcessTimeout = shutdownProcessTimeout;\n    this.sessionEndTimeout = validateSessionEndTimeout(sessionEndTimeout);\n    this.initializeProcessTimeout = initializeProcessTimeout;\n    this.permissions = permissions;\n    // agentNameIsEnv may be passed explicitly when ServerOptions is re-constructed (e.g.\n    // cli.ts spreads an existing ServerOptions instance), so prefer it when defined.\n    if (process.env.LIVEKIT_AGENT_NAME_OVERRIDE) {\n      // Highest priority: `lk simulate` sets this to force the worker to register\n      // under the agent name it dispatches to, overriding any configured agentName.\n      this.agentName = process.env.LIVEKIT_AGENT_NAME_OVERRIDE;\n      this.agentNameIsEnv = agentNameIsEnv ?? true;\n    } else if (agentName) {\n      this.agentName = agentName;\n      this.agentNameIsEnv = agentNameIsEnv ?? false;\n    } else if (process.env.LIVEKIT_AGENT_NAME) {\n      this.agentName = process.env.LIVEKIT_AGENT_NAME;\n      this.agentNameIsEnv = agentNameIsEnv ?? true;\n    } else {\n      this.agentName = '';\n      this.agentNameIsEnv = agentNameIsEnv ?? false;\n    }\n    this.serverType = serverType;\n    this.maxRetry = maxRetry;\n    this.wsURL = wsURL;\n    this.apiKey = apiKey;\n    this.apiSecret = apiSecret;\n    this.workerToken = workerToken;\n    this.host = host;\n    this.port = port || Default.port(production);\n    this.logLevel = logLevel;\n    this.production = production;\n    this.simulation = simulation;\n    this.jobMemoryWarnMB = jobMemoryWarnMB;\n    this.jobMemoryLimitMB = jobMemoryLimitMB;\n  }\n}\n\nclass PendingAssignment {\n  promise = new ThrowsPromise<JobAssignment, never>((resolve) => {\n    this.resolve = resolve; // this is how JavaScript lets you resolve promises externally\n  });\n  resolve(arg: JobAssignment) {\n    arg; // useless call to counteract TypeScript E6133\n  }\n}\n\n/**\n * Central orchestrator for all processes and job requests.\n *\n * @remarks\n * For most usecases, Worker should not be initialized or handled directly; you should instead call\n * for its creation through {@link cli.runApp}. This could, however, be useful in situations where\n * you don't have access to a command line, such as a headless program, or one that uses Agents\n * behind a wrapper.\n */\nexport class AgentServer {\n  #opts: ServerOptions;\n  #procPool: ProcPool;\n\n  #deployment = process.env.LIVEKIT_AGENT_DEPLOYMENT || '';\n  #id = 'unregistered';\n  #closed = true;\n  #draining = false;\n  #connecting = false;\n  #tasks: Promise<void>[] = [];\n  #pending: { [id: string]: PendingAssignment } = {};\n  #close = new Future();\n\n  event = new EventEmitter();\n  #session: WebSocket | undefined = undefined;\n  #httpServer?: HTTPServer;\n  #logger = log().child({ version });\n  #inferenceExecutor?: InferenceProcExecutor;\n  #loopMonitor?: EventLoopMonitor;\n\n  /* @throws {@link MissingCredentialsError} if URL, API key or API secret are missing */\n  constructor(opts: ServerOptions) {\n    opts.wsURL = opts.wsURL || process.env.LIVEKIT_URL || '';\n    opts.apiKey = opts.apiKey || process.env.LIVEKIT_API_KEY || '';\n    opts.apiSecret = opts.apiSecret || process.env.LIVEKIT_API_SECRET || '';\n\n    if (opts.wsURL === '')\n      throw new MissingCredentialsError(\n        'URL is required: Set LIVEKIT_URL, run with --url, or pass wsURL in ServerOptions',\n      );\n    if (opts.apiKey === '')\n      throw new MissingCredentialsError(\n        'API Key is required: Set LIVEKIT_API_KEY, run with --api-key, or pass apiKey in ServerOptions',\n      );\n    if (opts.apiSecret === '')\n      throw new MissingCredentialsError(\n        'API Secret is required: Set LIVEKIT_API_SECRET, run with --api-secret, or pass apiSecret in ServerOptions',\n      );\n\n    if (opts.workerToken) {\n      // Re-export into the environment so forked subprocesses inherit it (fork()\n      // copies process.env by default). The inference-header code in the child reads\n      // process.env.LIVEKIT_WORKER_TOKEN — see inference/utils.ts buildMetadataHeaders().\n      // Mirrors Python worker.py, which sets os.environ before spawning job procs.\n      process.env.LIVEKIT_WORKER_TOKEN = opts.workerToken;\n\n      if (opts.loadFunc !== defaultCpuLoad) {\n        this.#logger.warn(\n          'custom loadFunc is not supported when deploying to Cloud, using defaults',\n        );\n        opts.loadFunc = defaultCpuLoad;\n      }\n      const loadThreshold = Default.loadThreshold(opts.production);\n      if (opts.loadThreshold !== loadThreshold) {\n        this.#logger.warn(\n          'custom loadThreshold is not supported when deploying to Cloud, using defaults',\n        );\n        opts.loadThreshold = loadThreshold;\n      }\n    }\n\n    // Register the local audio-EOT runner so it runs in the shared inference\n    // process (loaded once per host, ~138 MB) instead of in every job worker.\n    // Guarded by binding availability: on a platform where\n    // `@livekit/local-inference` can't load, skip registration so the worker\n    // still starts (local EOT then degrades to a positive-default prediction).\n    maybeRegisterLocalEotRunner();\n\n    this.#inferenceExecutor = InferenceProcExecutor.createIfNeeded();\n\n    this.#procPool = new ProcPool({\n      agent: opts.agent,\n      numIdleProcesses: opts.numIdleProcesses,\n      initializeTimeout: opts.initializeProcessTimeout,\n      closeTimeout: opts.shutdownProcessTimeout,\n      sessionEndTimeout: opts.sessionEndTimeout,\n      inferenceExecutor: this.#inferenceExecutor,\n      memoryWarnMB: opts.jobMemoryWarnMB,\n      memoryLimitMB: opts.jobMemoryLimitMB,\n    });\n\n    this.#opts = opts;\n\n    // Simulations run ephemeral workers side by side; a health endpoint on a fixed port would make\n    // concurrent runs collide.\n    if (!opts.simulation) {\n      const healthCheck = () => {\n        // Check if inference executor exists and is not alive\n        if (this.#inferenceExecutor && !this.#inferenceExecutor.isAlive) {\n          return { healthy: false, message: 'inference process not running' };\n        }\n\n        // Only healthy when fully connected with an active WebSocket\n        if (\n          this.#closed ||\n          this.#connecting ||\n          !this.#session ||\n          this.#session.readyState !== WebSocket.OPEN\n        ) {\n          return { healthy: false, message: 'not connected to livekit' };\n        }\n\n        return { healthy: true, message: 'OK' };\n      };\n\n      const getWorkerInfo = () => ({\n        agent_name: opts.agentName,\n        agent_name_is_env: opts.agentNameIsEnv,\n        deployment: this.#deployment,\n        worker_type: JobType[opts.serverType],\n        active_jobs: this.activeJobs.length,\n        sdk_version: version,\n        project_type: PROJECT_TYPE,\n        protocol_version: WORKER_PROTOCOL_VERSION,\n      });\n\n      this.#httpServer = new HTTPServer(opts.host, opts.port, healthCheck, getWorkerInfo);\n    }\n  }\n\n  /** @throws {@link WorkerError} if worker failed to connect or already running */\n  async run() {\n    if (!this.#closed) {\n      throw new WorkerError('worker is already running');\n    }\n\n    if (this.#inferenceExecutor) {\n      await this.#inferenceExecutor.start();\n      await this.#inferenceExecutor.initialize();\n    }\n\n    this.#logger.info('starting worker');\n    this.#closed = false;\n    this.#loopMonitor = startMonitoring({ name: 'worker', emitSpans: false });\n    this.#procPool.start();\n\n    const workerWS = async () => {\n      let retries = 0;\n      this.#connecting = true;\n\n      while (!this.#closed) {\n        const url = new URL(this.#opts.wsURL);\n        url.protocol = url.protocol.replace('http', 'ws');\n        const token = new AccessToken(this.#opts.apiKey, this.#opts.apiSecret);\n        token.addGrant({ agent: true });\n        const jwt = await token.toJwt();\n        const wsUrl = new URL(url + 'agent');\n        if (this.#opts.workerToken) {\n          wsUrl.searchParams.append('worker_token', this.#opts.workerToken);\n        }\n        this.#session = new WebSocket(wsUrl, {\n          headers: { authorization: 'Bearer ' + jwt },\n        });\n\n        try {\n          await new ThrowsPromise<unknown, Error>((resolve, reject) => {\n            this.#session!.on('open', resolve);\n            this.#session!.on('error', (error) => reject(error));\n            this.#session!.on('close', (code) => reject(new Error(`WebSocket returned ${code}`)));\n          });\n\n          retries = 0;\n          this.#logger.debug('connected to LiveKit server');\n          await this.#runWS(this.#session);\n        } catch (e: unknown) {\n          if (this.#closed) return;\n          if (retries >= this.#opts.maxRetry) {\n            throw new WorkerError(\n              `failed to connect to LiveKit server (${this.#opts.wsURL}) after ${retries} attempts: ${e}`,\n            );\n          }\n\n          retries++;\n          const delay = Math.min(retries * 2, 10);\n\n          this.#logger.warn(\n            { error: e, retry_count: retries, max_retry: this.#opts.maxRetry },\n            `failed to connect to LiveKit server (${this.#opts.wsURL}), retrying in ${delay} seconds: (${retries}/${this.#opts.maxRetry})`,\n          );\n\n          await new ThrowsPromise<void, never>((resolve) => setTimeout(resolve, delay * 1000));\n        }\n      }\n    };\n\n    const tasks = [workerWS()];\n    if (this.#httpServer) {\n      tasks.push(this.#httpServer.run());\n    }\n    try {\n      await ThrowsPromise.all(tasks);\n      this.#close.resolve();\n    } catch (e) {\n      if (!this.#close.done) {\n        this.#close.reject(e instanceof Error ? e : new Error(String(e)));\n      }\n      throw e;\n    }\n  }\n\n  get id(): string {\n    return this.#id;\n  }\n\n  get activeJobs(): RunningJobInfo[] {\n    return this.#procPool.processes\n      .filter((proc) => proc.runningJob)\n      .map((proc) => proc.runningJob!);\n  }\n\n  /** @throws {@link WorkerError} if worker did not drain in time */\n  async drain(timeout?: number): Promise<Throws<void, WorkerError | Error>> {\n    if (this.#draining) {\n      return;\n    }\n\n    this.#logger.debug('draining worker');\n    this.#draining = true;\n\n    this.event.emit(\n      'worker_msg',\n      new WorkerMessage({\n        message: {\n          case: 'updateWorker',\n          value: {\n            status: WorkerStatus.WS_FULL,\n          },\n        },\n      }),\n    );\n\n    const joinJobs = async (): Promise<Throws<void[], Error>> => {\n      return ThrowsPromise.all(\n        this.#procPool.processes.map((proc): Promise<Throws<void, Error>> => {\n          if (!proc.runningJob) {\n            proc.close();\n          }\n          return proc.join();\n        }),\n      );\n    };\n\n    const promises = [joinJobs()];\n\n    const timeoutMs = timeout ?? this.#opts.drainTimeout;\n\n    if (timeoutMs) {\n      promises.push(\n        rejectOnAbort(AbortSignal.timeout(timeoutMs)).catch(() => {\n          throw new WorkerError('timed out draining');\n        }),\n      );\n    }\n    await ThrowsPromise.race(promises);\n  }\n\n  async simulateJob(roomName: string, participantIdentity?: string) {\n    const client = new RoomServiceClient(this.#opts.wsURL, this.#opts.apiKey, this.#opts.apiSecret);\n    const room = await client.createRoom({ name: roomName });\n    let participant: ParticipantInfo | undefined = undefined;\n    if (participantIdentity) {\n      try {\n        // TODO(AJS-269): resolve compatibility issue with node-sdk to remove the forced type casting\n        participant = (await client.getParticipant(\n          roomName,\n          participantIdentity,\n        )) as unknown as ParticipantInfo;\n      } catch (e) {\n        this.#logger.fatal(\n          `participant with identity ${participantIdentity} not found in room ${roomName}`,\n        );\n        throw e;\n      }\n    }\n\n    this.event.emit(\n      'worker_msg',\n      new WorkerMessage({\n        message: {\n          case: 'simulateJob',\n          value: {\n            type: JobType.JT_PUBLISHER,\n            room,\n            participant,\n          },\n        },\n      }),\n    );\n  }\n\n  async #runWS(ws: WebSocket) {\n    let closingWS = false;\n\n    const send = (msg: WorkerMessage) => {\n      if (closingWS) {\n        this.event.off('worker_msg', send);\n        return;\n      }\n      ws.send(msg.toBinary());\n    };\n    this.event.on('worker_msg', send);\n\n    const close = new ThrowsPromise<void, APIStatusError>((resolve, reject) => {\n      ws.addEventListener('close', (event) => {\n        closingWS = true;\n        if (!this.#closed) {\n          reject(\n            new APIStatusError({\n              message: 'worker connection closed unexpectedly',\n              options: {\n                statusCode: event.code || -1,\n                body: {\n                  code: event.code,\n                  reason: event.reason,\n                  wasClean: event.wasClean,\n                },\n              },\n            }),\n          );\n          return;\n        }\n        resolve();\n      });\n    });\n\n    ws.addEventListener('error', (event) => {\n      this.#logger.error('worker error:', event.message);\n    });\n\n    ws.addEventListener('message', (event) => {\n      let data: Uint8Array;\n      if (event.data instanceof Uint8Array) {\n        data = event.data;\n      } else if (event.data instanceof ArrayBuffer) {\n        data = new Uint8Array(event.data);\n      } else if (Array.isArray(event.data)) {\n        data = Buffer.concat(event.data);\n      } else {\n        let wsData = String(event.data);\n        if (wsData.length > 128) {\n          wsData = `${wsData.slice(0, 128)}...(+${wsData.length - 128} more)`;\n        }\n        const type = typeof event.data;\n        this.#logger.warn(\n          { type, 'lk.pii.ws_data': wsData },\n          'received unexpected worker message type',\n        );\n        return;\n      }\n\n      const msg = new ServerMessage();\n      msg.fromBinary(data);\n\n      // register is the only valid first message, and it is only valid as the\n      // first message\n      if (this.#connecting && msg.message.case !== 'register') {\n        throw new WorkerError('expected register response as first message');\n      }\n\n      switch (msg.message.case) {\n        case 'register': {\n          this.#id = msg.message.value.workerId;\n          this.#logger\n            .child({\n              id: this.id,\n              agentName: this.#opts.agentName,\n              agentNameIsEnv: this.#opts.agentNameIsEnv,\n              deployment: this.#deployment,\n              server_info: msg.message.value.serverInfo,\n            })\n            .info('registered worker');\n          this.event.emit(\n            'worker_registered',\n            msg.message.value.workerId,\n            msg.message.value.serverInfo,\n          );\n          this.#connecting = false;\n          break;\n        }\n        case 'availability': {\n          if (!msg.message.value.job) return;\n          const task = this.#availability(msg.message.value);\n          this.#tasks.push(task);\n          task.finally(() => {\n            const taskIndex = this.#tasks.indexOf(task);\n            if (taskIndex !== -1) {\n              this.#tasks.splice(taskIndex, 1);\n            } else {\n              throw new Error(`task ${task} not found in tasks`);\n            }\n          });\n          break;\n        }\n        case 'assignment': {\n          if (!msg.message.value.job) return;\n          const job = msg.message.value.job;\n          if (job.id in this.#pending) {\n            const task = this.#pending[job.id];\n            delete this.#pending[job.id];\n            task?.resolve(msg.message.value);\n          } else {\n            this.#logger.child({ job }).warn('received assignment for unknown job ' + job.id);\n          }\n          break;\n        }\n        case 'termination': {\n          const task = this.#termination(msg.message.value);\n          this.#tasks.push(task);\n          task.finally(() => {\n            const taskIndex = this.#tasks.indexOf(task);\n            if (taskIndex !== -1) {\n              this.#tasks.splice(taskIndex, 1);\n            } else {\n              throw new Error(`task ${task} not found in tasks`);\n            }\n          });\n          break;\n        }\n      }\n    });\n\n    this.event.emit(\n      'worker_msg',\n      new WorkerMessage({\n        message: {\n          case: 'register',\n          value: {\n            type: this.#opts.serverType,\n            agentName: this.#opts.agentName,\n            deployment: this.#deployment,\n            allowedPermissions: new ParticipantPermission({\n              canPublish: this.#opts.permissions.canPublish,\n              canSubscribe: this.#opts.permissions.canSubscribe,\n              canPublishData: this.#opts.permissions.canPublishData,\n              canUpdateMetadata: this.#opts.permissions.canUpdateMetadata,\n              hidden: this.#opts.permissions.hidden,\n              agent: true,\n            }),\n            version,\n          },\n        },\n      }),\n    );\n\n    let currentStatus = WorkerStatus.WS_AVAILABLE;\n    const loadMonitor = setInterval(() => {\n      if (closingWS) clearInterval(loadMonitor);\n\n      if (this.#draining) {\n        if (currentStatus !== WorkerStatus.WS_FULL) {\n          currentStatus = WorkerStatus.WS_FULL;\n          this.event.emit(\n            'worker_msg',\n            new WorkerMessage({\n              message: {\n                case: 'updateWorker',\n                value: {\n                  load: 1,\n                  status: WorkerStatus.WS_FULL,\n                },\n              },\n            }),\n          );\n        }\n        return;\n      }\n\n      const oldStatus = currentStatus;\n      this.#opts\n        .loadFunc(this)\n        .then((currentLoad: number) => {\n          const isFull = currentLoad >= this.#opts.loadThreshold;\n          const currentlyAvailable = !isFull;\n          currentStatus = currentlyAvailable ? WorkerStatus.WS_AVAILABLE : WorkerStatus.WS_FULL;\n\n          if (oldStatus != currentStatus) {\n            const extra = { load: currentLoad, loadThreshold: this.#opts.loadThreshold };\n            if (isFull) {\n              this.#logger.child(extra).info('worker is at full capacity, marking as unavailable');\n            } else {\n              this.#logger.child(extra).info('worker is below capacity, marking as available');\n            }\n          }\n\n          this.event.emit(\n            'worker_msg',\n            new WorkerMessage({\n              message: {\n                case: 'updateWorker',\n                value: {\n                  load: currentLoad,\n                  status: currentStatus,\n                },\n              },\n            }),\n          );\n        })\n        .catch((e) => {\n          this.#logger.warn({ error: e }, 'failed to measure CPU load');\n        });\n    }, UPDATE_LOAD_INTERVAL);\n\n    try {\n      await close;\n    } finally {\n      ws.removeAllListeners();\n    }\n  }\n\n  async #availability(msg: AvailabilityRequest) {\n    let answered = false;\n\n    const onReject = async () => {\n      answered = true;\n      this.event.emit(\n        'worker_msg',\n        new WorkerMessage({\n          message: {\n            case: 'availability',\n            value: {\n              jobId: msg.job!.id,\n              available: false,\n            },\n          },\n        }),\n      );\n    };\n\n    const onAccept = async (args: JobAcceptArguments) => {\n      answered = true;\n\n      this.event.emit(\n        'worker_msg',\n        new WorkerMessage({\n          message: {\n            case: 'availability',\n            value: {\n              jobId: msg.job!.id,\n              available: true,\n              participantIdentity: args.identity,\n              participantName: args.name,\n              participantMetadata: args.metadata,\n              // Stamp the agent name on the participant (matches the Python SDK).\n              // Consumers like `lk agent simulate` find the agent participant by\n              // this attribute; without it they never detect the agent joining.\n              participantAttributes: {\n                ...args.attributes,\n                [ATTRIBUTE_AGENT_NAME]: this.#opts.agentName,\n              },\n            },\n          },\n        }),\n      );\n\n      this.#pending[req.id] = new PendingAssignment();\n\n      const timer = setTimeout(() => {\n        this.#logger.child({ req }).warn(`assignment for job ${req.id} timed out`);\n        return;\n      }, ASSIGNMENT_TIMEOUT);\n      const asgn = await this.#pending[req.id]?.promise.then(async (asgn) => {\n        clearTimeout(timer);\n        return asgn;\n      });\n\n      if (asgn) {\n        try {\n          await this.#procPool.launchJob({\n            acceptArguments: args,\n            job: msg.job!,\n            url: asgn.url || this.#opts.wsURL,\n            token: asgn.token,\n            workerId: this.id,\n            apiKey: this.#opts.apiKey,\n            apiSecret: this.#opts.apiSecret,\n          });\n        } catch (e) {\n          this.#logger.child({ requestId: req.id }).error(e, 'error launching job');\n        }\n      } else {\n        this.#logger.child({ requestId: req.id }).warn('pending assignment not found');\n      }\n    };\n\n    const req = new JobRequest(msg.job!, onReject, onAccept);\n    this.#logger\n      .child({\n        jobId: msg.job?.id,\n        room_id: msg.job?.room?.sid,\n        resuming: msg.resuming,\n        agentName: this.#opts.agentName,\n      })\n      .info('received job request');\n\n    if (this.#draining) {\n      this.#logger\n        .child({\n          jobId: msg.job?.id,\n          room_id: msg.job?.room?.sid,\n          resuming: msg.resuming,\n          agentName: this.#opts.agentName,\n        })\n        .info('Worker is draining and no longer available, rejecting job');\n      await req.reject();\n      return;\n    }\n\n    const jobRequestTask = async () => {\n      try {\n        await this.#opts.requestFunc(req);\n      } catch (e) {\n        this.#logger\n          .child({ job: msg.job, resuming: msg.resuming, agentName: this.#opts.agentName })\n          .info('jobRequestFunc failed');\n        await onReject();\n      }\n\n      if (!answered) {\n        this.#logger\n          .child({ job: msg.job, resuming: msg.resuming, agentName: this.#opts.agentName })\n          .info('no answer was given inside the jobRequestFunc, automatically rejecting the job');\n      }\n    };\n\n    const task = jobRequestTask();\n    this.#tasks.push(task);\n    task.finally(() => {\n      const taskIndex = this.#tasks.indexOf(task);\n      if (taskIndex !== -1) {\n        this.#tasks.splice(taskIndex, 1);\n      } else {\n        throw new Error(`task ${task} not found in tasks`);\n      }\n    });\n  }\n\n  async #termination(msg: JobTermination) {\n    const proc = this.#procPool.getByJobId(msg.jobId);\n    if (proc === null) {\n      // safe to ignore\n      return;\n    }\n    await proc.close().catch((e) => this.#logger.error(e, 'Error terminating job'));\n  }\n\n  async close() {\n    if (this.#closed) {\n      await this.#close.await.catch(() => undefined);\n      return;\n    }\n\n    this.#logger.debug('shutting down worker');\n\n    this.#closed = true;\n    if (this.#loopMonitor) stopMonitoring(this.#loopMonitor);\n    this.#loopMonitor = undefined;\n\n    await this.#inferenceExecutor?.close();\n    await this.#procPool.close();\n    await this.#httpServer?.close();\n    await ThrowsPromise.allSettled(this.#tasks);\n\n    this.#session?.close();\n    await this.#close.await.catch(() => undefined);\n  }\n}\n\n/**\n * @deprecated Use {@link AgentServer} instead. This alias is provided for backward compatibility.\n */\nexport const Worker = AgentServer;\n\n/**\n * @deprecated Use {@link ServerOptions} instead. This alias is provided for backward compatibility.\n */\nexport const WorkerOptions = ServerOptions;\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n  typeof document === 'undefined'\n    ? new URL(`file:${__filename}`).href\n    : (document.currentScript && document.currentScript.src) ||\n      new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,OAClD,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEpC,IAAM,gBAAgC,iCAAiB;ADP9D,sBAOO;AACP,oBAA2C;AAE3C,gCAA+C;AAC/C,yBAA6B;AAC7B,qBAAqC;AACrC,uBAAwB;AACxB,gBAA0B;AAC1B,wBAA+B;AAC/B,uBAAqC;AACrC,iBAA8B;AAC9B,yBAA2B;AAC3B,oBAAyC;AACzC,oBAAqC;AACrC,8BAAgC;AAChC,qCAAsC;AACtC,uBAAyB;AAEzB,iBAA2B;AAC3B,2BAAuE;AACvE,iBAAoB;AACpB,0BAIO;AACP,mBAAsC;AACtC,qBAAwB;AAExB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB,MAAM;AACjC,MAAM,uBAAuB,MAAM;AACnC,MAAM,gBAAgB,KAAK,KAAK;AAChC,MAAM,eAAe;AAIrB,MAAM,0BAA0B;AAEhC,IAAI,2BAA2B;AAO/B,SAAS,8BAAoC;AAC3C,MAAI,yBAA0B;AAC9B,6BAA2B;AAC3B,MAAI,wCAAgB,kBAAkB,kCAAoB,EAAG;AAC7D,UAAI,wCAAyB,MAAM,QAAW;AAC5C,wBAAI,EAAE;AAAA,MACJ;AAAA,IAGF;AACA;AAAA,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