| 1 | import { withGenerationLease, type DraftClaimLockNamespace } from "./draft-claim-lock"; |
| 2 | import { OUTBOUND_TIMEOUT_MS } from "@/lib/bounded-body"; |
| 3 | import { fetchRepoStats } from "@/lib/github"; |
| 4 | import { |
| 5 | agentChat, |
| 6 | DIGEST_PROMPT, |
| 7 | saveDraft, |
| 8 | getDraftResolution, |
| 9 | renderDigestBody, |
| 10 | logUsage, |
| 11 | type WeeklyDigestRecord, |
| 12 | type AgentDraft, |
| 13 | type DeepSeekEnv, |
| 14 | } from "@/lib/community-agent"; |
| 15 | |
| 16 | export interface AgentEnv { |
| 17 | DRAFT_CLAIM_LOCK?: DraftClaimLockNamespace; |
| 18 | CURATED_KV?: { |
| 19 | get(k: string): Promise<string | null>; |
| 20 | put(k: string, v: string, o?: { expirationTtl?: number }): Promise<void>; |
| 21 | list(o?: { prefix?: string; limit?: number }): Promise<{ keys: { name: string }[] }>; |
| 22 | delete(key: string): Promise<void>; |
| 23 | }; |
| 24 | DEEPSEEK_API_KEY?: string; |
| 25 | DEEPSEEK_BASE_URL?: string; |
| 26 | DEEPSEEK_MODEL?: string; |
| 27 | GITHUB_TOKEN?: string; |
| 28 | CRON_SECRET?: string; |
| 29 | GITHUB_REPO?: string; |
| 30 | MAINTAINER_TOKEN?: string; |
| 31 | MAINTAINER_GITHUB_PAT?: string; |
| 32 | } |
| 33 | |
| 34 | function dsEnv(env: AgentEnv): DeepSeekEnv { |
| 35 | return { |
| 36 | baseUrl: env.DEEPSEEK_BASE_URL ?? process.env.DEEPSEEK_BASE_URL, |
| 37 | model: env.DEEPSEEK_MODEL ?? process.env.DEEPSEEK_MODEL, |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | async function generateDigest(env: AgentEnv): Promise<Record<string, unknown>> { |
| 42 | const repo = env.GITHUB_REPO ?? "codewhale-hq/CodeWhale"; |
| 43 | const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(); |
| 44 | |
| 45 | // Compute week ID |
| 46 | const now = new Date(); |
| 47 | const startOfYear = new Date(now.getFullYear(), 0, 1); |
| 48 | const weekNum = Math.ceil(((now.getTime() - startOfYear.getTime()) / 86400000 + startOfYear.getDay() + 1) / 7); |
| 49 | const weekId = `${now.getFullYear()}-W${String(weekNum).padStart(2, "0")}`; |
| 50 | |
| 51 | try { |
| 52 | if (await getDraftResolution(env.CURATED_KV, "digest", weekId)) { |
| 53 | return { ok: true, skipped: true, weekId, reason: "digest already reviewed" }; |
| 54 | } |
| 55 | |
| 56 | const [issuesRes, pullsRes, stats] = await Promise.all([ |
| 57 | fetch( |
| 58 | `https://api.github.com/repos/${repo}/issues?state=all&since=${weekAgo}&per_page=50&sort=updated&direction=desc`, |
| 59 | { |
| 60 | signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), |
| 61 | headers: { |
| 62 | Accept: "application/vnd.github+json", |
| 63 | "X-GitHub-Api-Version": "2022-11-28", |
| 64 | "User-Agent": "codewhale-web", |
| 65 | ...(env.GITHUB_TOKEN ? { Authorization: `Bearer ${env.GITHUB_TOKEN}` } : {}), |
| 66 | }, |
| 67 | } |
| 68 | ), |
| 69 | fetch( |
| 70 | `https://api.github.com/repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=50`, |
| 71 | { |
| 72 | signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), |
| 73 | headers: { |
| 74 | Accept: "application/vnd.github+json", |
| 75 | "X-GitHub-Api-Version": "2022-11-28", |
| 76 | "User-Agent": "codewhale-web", |
| 77 | ...(env.GITHUB_TOKEN ? { Authorization: `Bearer ${env.GITHUB_TOKEN}` } : {}), |
| 78 | }, |
| 79 | } |
| 80 | ), |
| 81 | fetchRepoStats(env.GITHUB_TOKEN), |
| 82 | ]); |
| 83 | |
| 84 | const issues = (await issuesRes.json()) as { number: number; title: string; state: string; pull_request?: unknown; created_at: string; user: { login: string } }[]; |
| 85 | const pulls = (await pullsRes.json()) as { number: number; title: string; state: string; merged_at?: string; created_at: string; user: { login: string } }[]; |
| 86 | |
| 87 | const weekIssues = issues.filter((i) => !i.pull_request && new Date(i.created_at) > new Date(weekAgo)); |
| 88 | const weekPRs = pulls.filter((p) => new Date(p.created_at) > new Date(weekAgo)); |
| 89 | const mergedPRs = pulls.filter((p) => p.merged_at && new Date(p.merged_at) > new Date(weekAgo)); |
| 90 | |
| 91 | const contributors = new Set([ |
| 92 | ...weekIssues.map((i) => i.user.login), |
| 93 | ...weekPRs.map((p) => p.user.login), |
| 94 | ]); |
| 95 | |
| 96 | const payload = { |
| 97 | period: `${weekAgo.slice(0, 10)} — ${new Date().toISOString().slice(0, 10)}`, |
| 98 | stats: { stars: stats.stars, forks: stats.forks }, |
| 99 | newIssues: weekIssues.map((i) => ({ number: i.number, title: i.title, author: i.user.login })), |
| 100 | newPRs: weekPRs.map((p) => ({ number: p.number, title: p.title, author: p.user.login })), |
| 101 | mergedPRs: mergedPRs.map((p) => ({ number: p.number, title: p.title })), |
| 102 | contributors: [...contributors], |
| 103 | }; |
| 104 | |
| 105 | const { content, usage } = await agentChat( |
| 106 | [{ role: "system", content: DIGEST_PROMPT }, { role: "user", content: JSON.stringify(payload) }], |
| 107 | env.DEEPSEEK_API_KEY!, |
| 108 | true, |
| 109 | dsEnv(env) |
| 110 | ); |
| 111 | |
| 112 | const parsed = JSON.parse(content) as { titleEn: string; titleZh: string; summaryEn: string; summaryZh: string; sections: { heading: string; items: string[] }[] }; |
| 113 | |
| 114 | const draft: AgentDraft = { |
| 115 | id: weekId, |
| 116 | type: "digest", |
| 117 | bodyEn: renderDigestBody(parsed, "en"), |
| 118 | bodyZh: renderDigestBody(parsed, "zh"), |
| 119 | generatedAt: new Date().toISOString(), |
| 120 | posted: false, |
| 121 | }; |
| 122 | |
| 123 | // Stage the structured digest for the weekly page, unapproved. The page |
| 124 | // renders it only after the maintainer posts the draft from /admin. |
| 125 | // Pick fields explicitly: model output must never be able to set |
| 126 | // `approved` or any other record key. |
| 127 | const record: WeeklyDigestRecord = { |
| 128 | titleEn: parsed.titleEn, |
| 129 | titleZh: parsed.titleZh, |
| 130 | summaryEn: parsed.summaryEn, |
| 131 | summaryZh: parsed.summaryZh, |
| 132 | sections: parsed.sections, |
| 133 | weekId, |
| 134 | generatedAt: draft.generatedAt, |
| 135 | approved: false, |
| 136 | }; |
| 137 | if (!(await saveDraft(env, draft, { digest: record }))) { |
| 138 | return { ok: true, skipped: true, weekId, reason: "digest already under review or resolved" }; |
| 139 | } |
| 140 | |
| 141 | await logUsage(env.CURATED_KV, usage.input, usage.output); |
| 142 | return { ok: true, weekId }; |
| 143 | } catch (e) { |
| 144 | return { ok: false, error: String(e) }; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /** The existing durable claim authority also serializes each bounded cron batch. |
| 149 | * Missing bindings stop generation before provider spend; KV is never a lock. |
| 150 | * The 45-minute lease covers at most ten 180-second model calls and reads. |
| 151 | * A completed batch retains a short hold for its KV drafts to propagate. |
| 152 | */ |
| 153 | async function withGenerationClaim(env: AgentEnv, task: string, generate: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>> { |
| 154 | if (!env.DEEPSEEK_API_KEY) return { skipped: true, reason: "DEEPSEEK_API_KEY not set" }; |
| 155 | if (!env.DRAFT_CLAIM_LOCK || !env.CURATED_KV) return { skipped: true, reason: "durable generation claim unavailable; no provider call started" }; |
| 156 | const result = await withGenerationLease(env.DRAFT_CLAIM_LOCK, task, generate); |
| 157 | if (result === "busy") return { ok: true, processed: 0, skipped: 1, reason: "generation already in progress or recently completed" }; |
| 158 | if (result === "unavailable") return { skipped: true, reason: "durable generation claim unavailable; no provider call started" }; |
| 159 | return result; |
| 160 | } |
| 161 | |
| 162 | export const runDigest = (env: AgentEnv) => withGenerationClaim(env, "digest", () => generateDigest(env)); |
| 163 |