|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const MAX_LOG_BYTES = 32 * 1024 * 1024; |
| 4 | +const MAX_RESULT_CHARS = 16000; |
| 5 | +const REQUEST_TIMEOUT_MS = 60000; |
| 6 | +const UUID = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/; |
| 7 | +const ENDPOINTS = new Set([ |
| 8 | + "https://api.githubcopilot.com", "https://api.individual.githubcopilot.com", |
| 9 | + "https://api.business.githubcopilot.com", "https://api.enterprise.githubcopilot.com", |
| 10 | +]); |
| 11 | + |
| 12 | +// Same endpoint discovery and SSE transport as GitHub CLI's agent-task view. |
| 13 | +// Never derive authority from prompts, tool output, reasoning, or a branch file. |
| 14 | +async function readTaskResult(copilot, task, candidateHash) { |
| 15 | + if (!task.sessions?.length) return null; |
| 16 | + if (task.state !== "completed" || task.session_count !== 1 || task.sessions.length !== 1) |
| 17 | + throw new Error("Task result requires one completed session; reconcile manually"); |
| 18 | + const session = task.sessions[0]; |
| 19 | + if (!UUID.test(session.id) || session.task_id !== task.id || session.state !== "completed" |
| 20 | + || !Number.isSafeInteger(task.repository?.id) || session.repository?.id !== task.repository.id) |
| 21 | + throw new Error("Task result session identity mismatch"); |
| 22 | + const { data } = await copilot.request("POST /graphql", { |
| 23 | + query: "query { viewer { copilotEndpoints { api } } }", |
| 24 | + }); |
| 25 | + const endpoint = data?.data?.viewer?.copilotEndpoints?.api; |
| 26 | + if (!ENDPOINTS.has(endpoint)) throw new Error("Unapproved Copilot result endpoint"); |
| 27 | + // CAPI requires Bearer, whereas Octokit's auth hook rewrites it to token. |
| 28 | + // Obtain only this dedicated client's credential, after endpoint validation. |
| 29 | + const auth = await copilot.auth(); |
| 30 | + if (auth.type !== "token" || !auth.token) throw new Error("Copilot result requires user token authentication"); |
| 31 | + const response = await fetch(`${endpoint}/agents/sessions/${session.id}/logs`, { |
| 32 | + headers: { Authorization: `Bearer ${auth.token}`, |
| 33 | + "Copilot-Integration-Id": "copilot-4-cli", "X-GitHub-Api-Version": "2026-01-09" }, |
| 34 | + redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), |
| 35 | + }); |
| 36 | + if (!response.ok) throw new Error(`Copilot session log request failed: HTTP ${response.status}`); |
| 37 | + const chunks = []; |
| 38 | + let bytes = 0; |
| 39 | + for await (const chunk of response.body) { |
| 40 | + bytes += chunk.length; |
| 41 | + if (bytes > MAX_LOG_BYTES) throw new Error("Copilot session log exceeds size budget"); |
| 42 | + chunks.push(Buffer.from(chunk)); |
| 43 | + } |
| 44 | + let pending = null, final = null; |
| 45 | + for (const line of Buffer.concat(chunks).toString("utf8").split("\n")) { |
| 46 | + if (!line.trim()) continue; |
| 47 | + if (!line.startsWith("data: ")) throw new Error("Unexpected Copilot session log format"); |
| 48 | + if (line.slice(6).trim() === "[DONE]") continue; |
| 49 | + let entry; |
| 50 | + try { entry = JSON.parse(line.slice(6)); } |
| 51 | + catch { throw new Error("Malformed Copilot session log event"); } |
| 52 | + if (entry.object !== "chat.completion.chunk") continue; |
| 53 | + if (typeof entry.id !== "string" || !entry.id) throw new Error("Missing Copilot result message identity"); |
| 54 | + if (Array.isArray(entry.choices) && entry.choices.length === 0) continue; |
| 55 | + final = null; |
| 56 | + for (const choice of entry.choices ?? []) { |
| 57 | + const delta = choice.delta ?? {}; |
| 58 | + if (delta.tool_calls?.length || (delta.role && delta.role !== "assistant") |
| 59 | + || (choice.finish_reason && choice.finish_reason !== "stop")) { |
| 60 | + pending = null; |
| 61 | + continue; |
| 62 | + } |
| 63 | + // CAPI sometimes omits indexes, including in GitHub CLI's log fixtures. |
| 64 | + if ((choice.index ?? 0) !== 0 || (choice.index == null && entry.choices.length !== 1)) |
| 65 | + throw new Error("Ambiguous Copilot result choice"); |
| 66 | + if (delta.role === "assistant" && pending?.id !== entry.id) pending = { id: entry.id, text: "" }; |
| 67 | + if (!pending || pending.id !== entry.id) continue; |
| 68 | + if (typeof delta.content === "string") pending.text += delta.content; |
| 69 | + if (pending.text.length > MAX_RESULT_CHARS) throw new Error("Copilot final answer exceeds size budget"); |
| 70 | + if (choice.finish_reason === "stop") { final = pending.text.trim(); pending = null; } |
| 71 | + } |
| 72 | + } |
| 73 | + if (!final) return null; |
| 74 | + const markers = final.match(/<!-- upstream-gateway-disposition:v1:[\s\S]*?-->/g) ?? []; |
| 75 | + const match = markers.length === 1 && markers[0].match(new RegExp( |
| 76 | + "^<!-- upstream-gateway-disposition:v1:" + candidateHash |
| 77 | + + ":(supported|intentionally-unsupported|existing-work|confirmed-gap) -->$")); |
| 78 | + if (!match || final.replace(markers[0], "").trim().length < 80) return null; |
| 79 | + return { sessionId: session.id, disposition: match[1], text: final }; |
| 80 | +} |
| 81 | + |
| 82 | +module.exports = { readTaskResult }; |
0 commit comments