setName('prescription-ai:dispatch')->setDescription('巡检处方 AI 消费者,对缺失的队列派发一轮处理') ->addOption('check', null, Option::VALUE_NONE, '只输出巡检状态'); } protected function execute(Input $input, Output $output): int { $enabled = PrescriptionAiStore::enabled(); $checkOnly = (bool) $input->getOption('check'); if (!$enabled && !$checkOnly) { $output->writeln('PRESCRIPTION_AI_DISPATCH {"enabled":false}'); return 0; } $root = $this->app->getRootPath(); $think = $root . 'think'; if (PHP_SAPI !== 'cli' || !is_readable($think)) { throw new RuntimeException('处方 AI 巡检需要 PHP CLI 和可读的 think 入口'); } $present = PHP_OS_FAMILY === 'Linux' ? PrescriptionAiLaneGuard::linuxWorkers($think) : []; $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null'; $streams = [['file', $null, 'r'], ['file', $null, 'w'], ['file', $null, 'w']]; $states = []; foreach (PrescriptionAiLaneGuard::LANES as $lane) { if (isset($present[$lane])) { $states[$lane] = $present[$lane]; continue; } if ($checkOnly) { $states[$lane] = PrescriptionAiLaneGuard::busy($this->app->getRuntimePath(), $lane) ? 'busy' : 'missing'; continue; } // Surface runtime permission errors in the admin schedule before detaching the worker. $probe = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, LOCK_EX | LOCK_NB); if ($probe === null) { $states[$lane] = 'busy'; continue; } fclose($probe); if (!function_exists('proc_open')) { throw new RuntimeException('处方 AI 单轮接管需要启用 proc_open'); } $process = proc_open([PHP_BINARY, $think, 'prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'], $streams, $pipes, $root); if (!is_resource($process)) { throw new RuntimeException('无法启动处方 AI 消费者 ' . $lane); } // proc_close waits for the model. Releasing a pipe-free handle lets the cron runner continue immediately. unset($process); $states[$lane] = 'dispatched'; } $output->writeln('PRESCRIPTION_AI_DISPATCH ' . json_encode(['enabled' => $enabled, 'lanes' => $states])); return 0; } }