// 重构前 index.ts 只读参考：commit 6a04144d3f5103014f75b637d7e6bc2f45bf007f，blob 56e590c1a6b5ca7ad128bf2c992f60e46c355a58；可用 `git show 6a04144d3f5103014f75b637d7e6bc2f45bf007f:src/components/microservices/code-queue/src/index.ts` 查看。

import type { QueueTaskRequest } from "./types";

export const resolvedReferenceContextTitle = "# Code Queue 已解析引用上下文";
export const currentTaskPromptMarker = "\n# 本次任务\n";
export const codeQueueEnvironmentHintTitle = "# Code Queue 运行环境提示";
export const codeQueueEnvironmentHint = [
  codeQueueEnvironmentHintTitle,
  "如果当前 Code Queue Docker 容器缺少完成任务所需的环境、系统包或语言依赖，可以先在容器内临时安装以推进当前任务；同时必须把该依赖补到 `src/components/microservices/code-queue/Dockerfile`，让后续任务重建镜像后可直接使用。",
  "任务可通过 `UNIDESK_SKILLS_PATH` 读取注入的宿主 skills；默认目标是 `/root/.agents/skills`。如果该路径不可读或缺少必需 skills，runner/preflight 会以 infra blocker 暴露 target projection 缺口；不要读取或输出宿主 token/auth 配置。",
].join("\n");

export function stripAutoReferenceHint(prompt: string): string {
  const trimmed = prompt.trimStart();
  if (!/^引用\s+Code Queue\s+任务\s+codex_\d+_[A-Za-z0-9_-]+/u.test(trimmed)) return prompt;
  const marker = "\n\n本次任务：";
  const index = trimmed.indexOf(marker);
  if (index === -1) return prompt;
  return trimmed.slice(index + marker.length).trimStart();
}

export function stripResolvedReferenceContext(prompt: string): string {
  const trimmed = prompt.trimStart();
  if (!trimmed.startsWith(resolvedReferenceContextTitle)) return prompt;
  const offset = prompt.length - trimmed.length;
  const index = prompt.lastIndexOf(currentTaskPromptMarker);
  if (index < offset) return prompt;
  return prompt.slice(index + currentTaskPromptMarker.length).trimStart();
}

export function stripCodeQueueEnvironmentHint(prompt: string): string {
  const trimmed = prompt.trimStart();
  if (!trimmed.startsWith(codeQueueEnvironmentHintTitle)) return prompt;
  const offset = prompt.length - trimmed.length;
  const index = prompt.indexOf(currentTaskPromptMarker, offset);
  if (index < offset) return prompt;
  return prompt.slice(index + currentTaskPromptMarker.length).trimStart();
}

export function userPromptForDisplay(prompt: string): string {
  return stripAutoReferenceHint(stripResolvedReferenceContext(stripCodeQueueEnvironmentHint(prompt)));
}

export function promptWithCodeQueueEnvironmentHint(prompt: string): string {
  if (prompt.trimStart().startsWith(codeQueueEnvironmentHintTitle)) return prompt;
  return [codeQueueEnvironmentHint, "", "# 本次任务", prompt.trim()].join("\n");
}

export function injectCodeQueueEnvironmentHint(request: QueueTaskRequest): QueueTaskRequest {
  if (request.prompt.trimStart().startsWith(codeQueueEnvironmentHintTitle)) return request;
  const basePrompt = request.basePrompt ?? userPromptForDisplay(request.prompt);
  return { ...request, prompt: promptWithCodeQueueEnvironmentHint(request.prompt), basePrompt };
}
