@github-tools/sdk 1.21.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +9 -9
  2. package/dist/{approval-policy-CEMMPq92.mjs → approval-policy-DJlImo7H.mjs} +3 -4
  3. package/dist/{approval-policy-CEMMPq92.mjs.map → approval-policy-DJlImo7H.mjs.map} +1 -1
  4. package/dist/connect/eve.d.mts +2 -4
  5. package/dist/connect/eve.d.mts.map +1 -1
  6. package/dist/connect/eve.mjs +3 -4
  7. package/dist/connect/eve.mjs.map +1 -1
  8. package/dist/connect.d.mts +3 -9
  9. package/dist/connect.d.mts.map +1 -1
  10. package/dist/connect.mjs +3 -4
  11. package/dist/{cores-meFAMt2D.mjs → cores-H6HKlwFZ.mjs} +3 -4
  12. package/dist/{cores-meFAMt2D.mjs.map → cores-H6HKlwFZ.mjs.map} +1 -1
  13. package/dist/{dry-run-DXckOam2.d.mts → dry-run-BAbes7Mv.d.mts} +2 -28
  14. package/dist/dry-run-BAbes7Mv.d.mts.map +1 -0
  15. package/dist/{evaluation-DJHINyAu.mjs → evaluation-Dlf-571x.mjs} +4 -6
  16. package/dist/{evaluation-DJHINyAu.mjs.map → evaluation-Dlf-571x.mjs.map} +1 -1
  17. package/dist/{eve-runtime-B_CJE9JV.d.mts → eve-runtime-CoBSN8nF.d.mts} +66 -15
  18. package/dist/eve-runtime-CoBSN8nF.d.mts.map +1 -0
  19. package/dist/{eve-runtime-DPzMPCLt.mjs → eve-runtime-DEdQqbCs.mjs} +214 -27
  20. package/dist/eve-runtime-DEdQqbCs.mjs.map +1 -0
  21. package/dist/eve-runtime.d.mts +5 -5
  22. package/dist/eve-runtime.mjs +4 -4
  23. package/dist/eve.d.mts +67 -69
  24. package/dist/eve.d.mts.map +1 -1
  25. package/dist/eve.mjs +67 -68
  26. package/dist/eve.mjs.map +1 -1
  27. package/dist/{index-CzzrtCVj.d.mts → index-v5n5OLs7.d.mts} +29 -54
  28. package/dist/index-v5n5OLs7.d.mts.map +1 -0
  29. package/dist/index.d.mts +2 -2
  30. package/dist/index.mjs +3 -3
  31. package/dist/{interrupts-BSDPwdJ2.d.mts → interrupts-MwQ_v_PF.d.mts} +1 -3
  32. package/dist/interrupts-MwQ_v_PF.d.mts.map +1 -0
  33. package/dist/rolldown-runtime-D8jQpDG7.mjs +12 -0
  34. package/dist/{src-BlhrSieS.mjs → src-BRZIY_PZ.mjs} +21 -38
  35. package/dist/{src-BlhrSieS.mjs.map → src-BRZIY_PZ.mjs.map} +1 -1
  36. package/dist/tanstack/interrupts.d.mts +1 -1
  37. package/dist/tanstack/interrupts.mjs +1 -2
  38. package/dist/tanstack.d.mts +3 -20
  39. package/dist/tanstack.d.mts.map +1 -1
  40. package/dist/tanstack.mjs +8 -13
  41. package/dist/tanstack.mjs.map +1 -1
  42. package/dist/{token-BLps09gm.mjs → token-DZu9uttC.mjs} +6 -10
  43. package/dist/{token-BLps09gm.mjs.map → token-DZu9uttC.mjs.map} +1 -1
  44. package/dist/{types-Bln8U42J.d.mts → types-8KtcPTao.d.mts} +3 -7
  45. package/dist/types-8KtcPTao.d.mts.map +1 -0
  46. package/dist/{types-C7O2lwwz.d.mts → types-C-BIKmas.d.mts} +2 -4
  47. package/dist/types-C-BIKmas.d.mts.map +1 -0
  48. package/dist/workflow.d.mts +2 -4
  49. package/dist/workflow.d.mts.map +1 -1
  50. package/dist/workflow.mjs +3 -4
  51. package/dist/{write-tools-w-8tjnDQ.mjs → write-tools-C-962T9O.mjs} +57 -88
  52. package/dist/write-tools-C-962T9O.mjs.map +1 -0
  53. package/package.json +1 -1
  54. package/dist/dry-run-DXckOam2.d.mts.map +0 -1
  55. package/dist/eve-runtime-B_CJE9JV.d.mts.map +0 -1
  56. package/dist/eve-runtime-DPzMPCLt.mjs.map +0 -1
  57. package/dist/index-CzzrtCVj.d.mts.map +0 -1
  58. package/dist/interrupts-BSDPwdJ2.d.mts.map +0 -1
  59. package/dist/types-Bln8U42J.d.mts.map +0 -1
  60. package/dist/types-C7O2lwwz.d.mts.map +0 -1
  61. package/dist/write-tools-w-8tjnDQ.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"evaluation-DJHINyAu.mjs","names":["exports"],"sources":["../src/core/model-output.ts","../src/core/evaluation.ts"],"sourcesContent":["const MAX_PATCH_LENGTH = 4000\nconst MAX_CONTENT_LENGTH = 20000\nconst MAX_MODEL_TREE_ENTRIES = 200\nconst MAX_MODEL_DIFF_FILES = 80\n\nfunction truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text\n return `${text.slice(0, maxLength)}\\n\\n[truncated: ${text.length - maxLength} more characters]`\n}\n\nfunction truncatePatchFields<T extends { patch?: string }>(files: T[]): T[] {\n return files.map(file => ({\n ...file,\n patch: file.patch ? truncateText(file.patch, MAX_PATCH_LENGTH) : file.patch,\n }))\n}\n\nfunction capDiffFiles<T extends { patch?: string }>(files: T[] | undefined) {\n if (!files) return { files, filesOmitted: 0 }\n const truncated = truncatePatchFields(files)\n if (truncated.length <= MAX_MODEL_DIFF_FILES) return { files: truncated, filesOmitted: 0 }\n return {\n files: truncated.slice(0, MAX_MODEL_DIFF_FILES),\n filesOmitted: truncated.length - MAX_MODEL_DIFF_FILES,\n }\n}\n\ntype ToModelOutputOptions = {\n toolCallId: string\n input: unknown\n output: unknown\n}\n\ntype ListPullRequestFile = {\n filename: string\n status: string\n additions: number\n deletions: number\n changes: number\n patch?: string\n}\n\ntype ListPullRequestFilesOutput = {\n items: ListPullRequestFile[]\n hasMore: boolean\n page: number\n perPage: number\n nextPage?: number\n}\n\ntype GetCommitOutput = {\n sha: string\n message: string\n author?: string\n authorLogin?: string\n date?: string\n url: string\n stats: { additions: number, deletions: number, total: number } | null\n files?: Array<{\n filename: string\n status: string\n additions: number\n deletions: number\n patch?: string\n }>\n}\n\ntype GetFileContentOutput =\n | { type: 'directory', entries: Array<{ name: string, type: string, path: string }> }\n | { type: string, path: string }\n | {\n type: 'file'\n path: string\n sha: string\n size: number\n content: string\n totalLines?: number\n startLine?: number\n endLine?: number\n truncated?: boolean\n }\n\nexport function listPullRequestFilesToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as ListPullRequestFilesOutput\n return {\n type: 'json' as const,\n value: {\n ...result,\n items: truncatePatchFields(result.items),\n },\n }\n}\n\nexport function getCommitToModelOutput({ output }: ToModelOutputOptions) {\n const commit = output as GetCommitOutput\n const { files, filesOmitted } = capDiffFiles(commit.files)\n return {\n type: 'json' as const,\n value: {\n ...commit,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n\ntype CompareCommitsOutput = {\n status: string\n aheadBy: number\n behindBy: number\n totalCommits: number\n url: string\n commits: Array<{ sha: string, message: string, author?: string, authorLogin?: string }>\n files?: Array<{\n filename: string\n status: string\n additions: number\n deletions: number\n patch?: string\n }>\n}\n\nexport function compareCommitsToModelOutput({ output }: ToModelOutputOptions) {\n const comparison = output as CompareCommitsOutput\n const { files, filesOmitted } = capDiffFiles(comparison.files)\n return {\n type: 'json' as const,\n value: {\n ...comparison,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n\nexport function getFileContentToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetFileContentOutput\n if (result.type === 'directory' && 'entries' in result && result.entries.length > MAX_MODEL_TREE_ENTRIES) {\n return {\n type: 'json' as const,\n value: {\n ...result,\n truncated: true,\n entries: result.entries.slice(0, MAX_MODEL_TREE_ENTRIES),\n entriesOmitted: result.entries.length - MAX_MODEL_TREE_ENTRIES,\n },\n }\n }\n if ('content' in result && result.content.length > MAX_CONTENT_LENGTH) {\n return {\n type: 'json' as const,\n value: {\n ...result,\n content: truncateText(result.content, MAX_CONTENT_LENGTH),\n },\n }\n }\n return { type: 'json' as const, value: result }\n}\n\ntype GetRepositoryTreeOutput = {\n sha: string\n truncated: boolean\n path?: string\n entries: Array<{ path?: string, type?: string, size?: number, sha?: string }>\n}\n\nexport function getRepositoryTreeToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetRepositoryTreeOutput\n if (result.entries.length <= MAX_MODEL_TREE_ENTRIES) {\n return { type: 'json' as const, value: result }\n }\n return {\n type: 'json' as const,\n value: {\n ...result,\n truncated: true,\n entries: result.entries.slice(0, MAX_MODEL_TREE_ENTRIES),\n entriesOmitted: result.entries.length - MAX_MODEL_TREE_ENTRIES,\n },\n }\n}\n\ntype GetPullRequestContextOutput = {\n pullRequest: {\n number: number\n title: string\n body: string | null\n state: string\n url: string\n author?: string\n branch: string\n headSha: string\n base: string\n draft?: boolean\n merged: boolean\n mergeable: boolean | null\n additions: number\n deletions: number\n changedFiles: number\n createdAt: string\n updatedAt: string\n mergedAt: string | null\n }\n files?: ListPullRequestFile[]\n filesHasMore?: boolean\n reviews?: Array<{\n id: number\n state: string\n body: string\n author?: string\n url: string\n submittedAt?: string | null\n }>\n checks?: {\n checkRuns: {\n totalCount: number\n checkRuns: Array<{\n id: number\n name: string\n status: string\n conclusion: string | null\n url: string | null\n startedAt: string | null\n completedAt: string | null\n }>\n }\n combinedStatus: {\n state: string\n totalCount: number\n statuses: Array<{\n context: string\n state: string\n description: string | null\n url: string | null\n }>\n }\n }\n}\n\nexport function getPullRequestContextToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetPullRequestContextOutput\n const { files, filesOmitted } = capDiffFiles(result.files)\n return {\n type: 'json' as const,\n value: {\n ...result,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n","import * as ai from 'ai'\nimport type { Experimental_EvaluationModel, JSONValue, ModelMessage } from 'ai'\nimport { GITHUB_TOOL_CATALOG } from './catalog'\nimport { githubToolsErrors } from './errors'\nimport { CORE_READ_TOOLS, PRESET_TOOLS } from './presets'\nimport { ALL_GITHUB_TOOL_NAMES, type GithubToolName } from './tool-names'\nimport { DEFAULT_EVALUATION_MODEL, RISK_QUESTION, INTENT_QUESTION, PRESET_PURPOSES, conversationState, rankPresets, requiresApproval, type RoutablePreset } from './evaluation-policy'\nexport { DEFAULT_EVALUATION_MODEL, AUTO_APPROVAL_TOOLS } from './evaluation-policy'\nimport type { GithubWriteToolName } from './write-tools'\n\n/**\n * Tuning for `requireApproval: 'auto'` and `preset: 'auto'`. Every field is optional.\n */\nexport type GithubEvaluationOptions = {\n /**\n * Decision model for AI SDK `experimental_decide`: an AI Gateway ID or a model instance.\n * @default 'typesafe-ai/jev-1.14.0'\n */\n model?: Experimental_EvaluationModel\n /**\n * Provider options passed to every decision call, for example AI Gateway settings such as\n * `{ gateway: { zeroDataRetention: true } }`.\n */\n providerOptions?: Record<string, Record<string, JSONValue>>\n /**\n * Highest risk an `'auto'` tool call can have and still run without approval, on a 0–2 scale\n * (0 negligible, 1 visible but reversible, 2 hard to undo).\n * @default 1\n */\n maxRisk?: number\n /**\n * Lowest probability that the latest user message asked for the call, for it to run without approval.\n * @default 0.6\n */\n minIntent?: number\n /**\n * Lowest probability for `preset: 'auto'` to select a preset. When no preset reaches it,\n * read-only `repo-explorer` is used.\n * @default 0.7\n */\n minPresetProbability?: number\n /**\n * Most presets `preset: 'auto'` combines in one call, keeping the most likely ones.\n * @default 2\n */\n maxPresets?: number\n /**\n * What `preset: 'auto'` picks. `'tools'` asks the decision model about each tool and lists only\n * the likely ones plus the core read tools (`CORE_READ_TOOLS`), so the model sees far fewer tool\n * definitions. The rest stays reachable: eve defers it, and `createGithubAgent` adds a\n * `callGithubTool` tool. `'presets'` lists the tools of up to `maxPresets` presets and, on\n * `createGithubAgent`, uses their system prompts.\n * @default 'tools'\n */\n selection?: 'presets' | 'tools'\n /**\n * How long a `preset: 'auto'` decision lasts. `'session'` decides once, on the conversation's\n * first request, so the listed tools, and the provider's cached prompt prefix they start, stay\n * the same for the rest of the conversation; later needs go through deferred tools (eve) or\n * `callGithubTool` (`createGithubAgent`, which doesn't support it with `selection: 'presets'`).\n * `'turn'` decides again for each new request, which changes the tool list and makes the\n * provider write the whole conversation to its prompt cache again.\n * @default 'session', except `'turn'` for presets on `createGithubAgent`\n */\n scope?: 'turn' | 'session'\n /**\n * Keeps `createGithubAgent`'s `preset: 'auto'` decisions across processes, such as serverless\n * instances, under keys derived from the request and the routing settings (decision model,\n * thresholds and caps), so agents configured differently don't share decisions. Without it, a decision\n * lives in this process's memory, and another process decides again: that costs a decision\n * call, and a different pick changes the tool list and invalidates the provider's prompt cache.\n * The eve extension keeps decisions in the session and ignores this option.\n */\n store?: {\n get: (key: string) => Promise<readonly string[] | undefined>\n set: (key: string, value: readonly string[]) => Promise<void>\n }\n /**\n * Lowest probability for `selection: 'tools'` to list a tool beyond the core read tools.\n * @default 0.5\n */\n minToolProbability?: number\n /**\n * Most tools `selection: 'tools'` lists beyond the core read tools, keeping the most likely ones.\n * @default 8\n */\n maxTools?: number\n}\n\n/**\n * Throws `EVALUATION_UNAVAILABLE` when the installed `ai` has neither `experimental_decide`\n * nor `experimental_evaluate`. Call it where `'auto'` is configured, so a too-old `ai` fails\n * at setup instead of mid-conversation.\n */\nexport function assertEvaluationAvailable() {\n loadDecide()\n}\n\n// `experimental_decide` replaced `experimental_evaluate` in ai 7.0.128; the old name stays an alias.\nfunction loadDecide(): typeof ai.experimental_decide {\n const exports: Partial<Pick<typeof ai, 'experimental_decide' | 'experimental_evaluate'>> = ai\n const decide = exports.experimental_decide ?? exports.experimental_evaluate\n if (!decide) throw githubToolsErrors.EVALUATION_UNAVAILABLE()\n return decide\n}\n\n// `decide` throws when the model refuses any question; the error names the refused questions.\nfunction refusedQuestions(error: unknown): readonly string[] | undefined {\n const exports: Partial<Pick<typeof ai, 'Experimental_DecisionRefusalError'>> = ai\n return exports.Experimental_DecisionRefusalError?.isInstance(error) ? error.questionIds : undefined\n}\n\nfunction warnEvaluationFailed(model: Experimental_EvaluationModel, fallback: string, error: unknown, abortSignal?: AbortSignal) {\n abortSignal?.throwIfAborted()\n const cause = error instanceof Error ? error : new Error(String(error))\n console.warn('[github-tools]', githubToolsErrors.EVALUATION_FAILED({\n model: typeof model === 'string' ? model : model.modelId,\n fallback,\n detail: cause.message,\n cause,\n }))\n}\n\n/** Whether a person should approve a GitHub write, and why, as a short sentence for the approval request. */\nexport type AutoApprovalDecision = { ask: boolean, reason: string }\n\nconst RISK_LABELS = RISK_QUESTION.criteria.map(criterion => criterion.slice(0, criterion.indexOf(':')))\n\n/**\n * Asks the decision model how risky a GitHub write is and whether the user asked for it, and\n * explains the outcome: `ask` is true when a person should approve the call. A failed or refused\n * decision asks, since it gives no evidence that the call is safe.\n */\nexport async function autoApprovalDecision(\n toolName: GithubWriteToolName,\n input: unknown,\n messages: readonly ModelMessage[],\n { model = DEFAULT_EVALUATION_MODEL, maxRisk = 1, minIntent = 0.6, providerOptions }: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<AutoApprovalDecision> {\n const decide = loadDecide()\n let refused = false\n const result = await decide({\n model,\n providerOptions,\n state: {\n ...conversationState(messages, messageText),\n toolCall: {\n tool: toolName,\n description: GITHUB_TOOL_CATALOG[toolName].description,\n input: input as JSONValue,\n },\n },\n questions: {\n risk: { type: 'score', ...RISK_QUESTION },\n intent: { type: 'boolean', ...INTENT_QUESTION },\n },\n abortSignal,\n }).catch((error: unknown) => {\n // A refusal is an answer, not an outage: it gives no evidence the call is safe, so a person decides.\n refused = Boolean(refusedQuestions(error))\n if (!refused) warnEvaluationFailed(model, `asking approval for ${toolName}`, error, abortSignal)\n return undefined\n })\n if (!result) return { ask: true, reason: refused ? 'The decision model declined to rate this call.' : 'The decision model was unavailable.' }\n const risk = result.answers.risk.score\n const intent = result.answers.intent.probability\n // Jev scores risk on a continuous 0–2 scale, so the label is the nearest rubric level.\n const verdict = `${RISK_LABELS[Math.round(risk)]} (risk ${Number(risk.toFixed(1))} of 2), ${Math.round(intent * 100)}% likely you asked for it`\n return requiresApproval(risk, intent, { maxRisk, minIntent })\n ? { ask: true, reason: `${verdict}.` }\n : { ask: false, reason: `Approved automatically: ${verdict.charAt(0).toLowerCase()}${verdict.slice(1)}.` }\n}\n\n/** Whether a GitHub write needs a person's approval; see {@link autoApprovalDecision}. */\nexport async function needsAutoApproval(\n toolName: GithubWriteToolName,\n input: unknown,\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<boolean> {\n return (await autoApprovalDecision(toolName, input, messages, options, abortSignal)).ask\n}\n\n/**\n * Presets the latest user message needs, from one evaluation call with an independent\n * yes/no question per preset. Returns up to `maxPresets` presets at or above\n * `minPresetProbability`, most likely first, and read-only `repo-explorer` when none qualifies.\n * `repo-explorer` is only combined with no other preset. Rejects when the evaluation call fails;\n * {@link selectPresets} falls back instead. Never returns `maintainer`, so the full catalog is never exposed.\n */\nexport async function evaluatePresets(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<RoutablePreset[]> {\n const { minPresetProbability = 0.7, maxPresets = 2 } = options\n const presets = Object.keys(PRESET_PURPOSES) as RoutablePreset[]\n const probabilities = await decideEach(messages, presets, preset => ({\n instructions: 'Does handling this GitHub request need the tools of this preset?',\n criteria: { true: { purpose: PRESET_PURPOSES[preset], tools: [...PRESET_TOOLS[preset]] } },\n }), options, abortSignal)\n return rankPresets(probabilities, { minPresetProbability, maxPresets })\n}\n\n/**\n * Tools the latest user message needs, from one decision call with a yes/no question per tool:\n * the core read tools, plus up to `maxTools` others at or above `minToolProbability`, most likely\n * first. Rejects when the decision call fails; {@link selectTools} falls back instead.\n */\nexport async function evaluateTools(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<GithubToolName[]> {\n const { minToolProbability = 0.5, maxTools = 8 } = options\n const core: readonly GithubToolName[] = CORE_READ_TOOLS\n const candidates = ALL_GITHUB_TOOL_NAMES.filter(name => !core.includes(name))\n const probabilities = await decideEach(messages, candidates, name => ({\n instructions: 'Does handling this GitHub request need this tool?',\n criteria: { true: { tool: name, description: GITHUB_TOOL_CATALOG[name].description } },\n }), options, abortSignal)\n const likely = candidates\n .filter(name => probabilities[name] >= minToolProbability)\n .toSorted((a, b) => probabilities[b] - probabilities[a])\n .slice(0, maxTools)\n return [...core, ...likely]\n}\n\ntype BooleanQuestion = { instructions: string, criteria: { true: Record<string, JSONValue> } }\n\n// One boolean question per key against the conversation. A refused question counts as a no:\n// ask once more without it instead of losing every answer.\nasync function decideEach<K extends string>(\n messages: readonly ModelMessage[],\n keys: readonly K[],\n question: (key: K) => BooleanQuestion,\n { model = DEFAULT_EVALUATION_MODEL, providerOptions }: GithubEvaluationOptions,\n abortSignal?: AbortSignal,\n): Promise<Record<K, number>> {\n const decide = loadDecide()\n const state = conversationState(messages, messageText)\n const ask = (asked: readonly K[]) => decide({\n model,\n providerOptions,\n state,\n questions: Object.fromEntries(asked.map(key => [key, { type: 'boolean' as const, ...question(key) }])),\n abortSignal,\n })\n const probabilities = Object.fromEntries(keys.map(key => [key, 0])) as Record<K, number>\n const { answers } = await ask(keys).catch((error: unknown) => {\n const refused = refusedQuestions(error)\n const remaining = keys.filter(key => !refused?.includes(key))\n if (!refused || remaining.length === 0) throw error\n return ask(remaining)\n })\n for (const [key, answer] of Object.entries(answers)) probabilities[key as K] = answer.probability\n return probabilities\n}\n\n/**\n * Logs `EVALUATION_FAILED` for a failed {@link evaluatePresets} call and returns the read-only\n * `repo-explorer` fallback. Rethrows when `abortSignal` is aborted.\n */\nexport function fallbackPresets(error: unknown, { model = DEFAULT_EVALUATION_MODEL }: GithubEvaluationOptions = {}, abortSignal?: AbortSignal): RoutablePreset[] {\n warnEvaluationFailed(model, 'using the repo-explorer preset', error, abortSignal)\n return ['repo-explorer']\n}\n\n/**\n * Logs `EVALUATION_FAILED` for a failed {@link evaluateTools} call and returns the read-only\n * `repo-explorer` tools. Rethrows when `abortSignal` is aborted.\n */\nexport function fallbackTools(error: unknown, { model = DEFAULT_EVALUATION_MODEL }: GithubEvaluationOptions = {}, abortSignal?: AbortSignal): GithubToolName[] {\n warnEvaluationFailed(model, 'using the repo-explorer tools', error, abortSignal)\n return [...PRESET_TOOLS['repo-explorer']]\n}\n\n/**\n * {@link evaluateTools}, falling back to the read-only `repo-explorer` tools (and logging\n * `EVALUATION_FAILED`) when the decision call fails.\n */\nexport async function selectTools(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<GithubToolName[]> {\n return evaluateTools(messages, options, abortSignal).catch(error => fallbackTools(error, options, abortSignal))\n}\n\n/**\n * {@link evaluatePresets}, falling back to read-only `repo-explorer` (and logging\n * `EVALUATION_FAILED`) when the evaluation call fails.\n */\nexport async function selectPresets(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<RoutablePreset[]> {\n return evaluatePresets(messages, options, abortSignal).catch(error => fallbackPresets(error, options, abortSignal))\n}\n\nexport function latestUserText(messages: readonly ModelMessage[]): string {\n return conversationState(messages, messageText).request\n}\n\n/** The `request` and `repliedTo` the evaluation model sees for these messages. */\nexport function evaluationRequest(messages: readonly ModelMessage[]) {\n return conversationState(messages, messageText)\n}\n\nfunction messageText(message: ModelMessage): string {\n if (typeof message.content === 'string') return message.content\n return message.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\\n')\n}\n"],"mappings":";;;AAAA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAE7B,SAAS,aAAa,MAAc,WAA2B;CAC7D,IAAI,KAAK,UAAU,WAAW,OAAO;CACrC,OAAO,GAAG,KAAK,MAAM,GAAG,SAAS,EAAE,kBAAkB,KAAK,SAAS,UAAU;AAC/E;AAEA,SAAS,oBAAkD,OAAiB;CAC1E,OAAO,MAAM,KAAI,UAAS;EACxB,GAAG;EACH,OAAO,KAAK,QAAQ,aAAa,KAAK,OAAO,gBAAgB,IAAI,KAAK;CACxE,EAAE;AACJ;AAEA,SAAS,aAA2C,OAAwB;CAC1E,IAAI,CAAC,OAAO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Q,SAAQ,SAAQ,KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI;AAC3F"}
1
+ {"version":3,"file":"evaluation-Dlf-571x.mjs","names":["exports"],"sources":["../src/core/model-output.ts","../src/core/evaluation.ts"],"sourcesContent":["const MAX_PATCH_LENGTH = 4000\nconst MAX_CONTENT_LENGTH = 20000\nconst MAX_MODEL_TREE_ENTRIES = 200\nconst MAX_MODEL_DIFF_FILES = 80\n\nfunction truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text\n return `${text.slice(0, maxLength)}\\n\\n[truncated: ${text.length - maxLength} more characters]`\n}\n\nfunction truncatePatchFields<T extends { patch?: string }>(files: T[]): T[] {\n return files.map(file => ({\n ...file,\n patch: file.patch ? truncateText(file.patch, MAX_PATCH_LENGTH) : file.patch,\n }))\n}\n\nfunction capDiffFiles<T extends { patch?: string }>(files: T[] | undefined) {\n if (!files) return { files, filesOmitted: 0 }\n const truncated = truncatePatchFields(files)\n if (truncated.length <= MAX_MODEL_DIFF_FILES) return { files: truncated, filesOmitted: 0 }\n return {\n files: truncated.slice(0, MAX_MODEL_DIFF_FILES),\n filesOmitted: truncated.length - MAX_MODEL_DIFF_FILES,\n }\n}\n\ntype ToModelOutputOptions = {\n toolCallId: string\n input: unknown\n output: unknown\n}\n\ntype ListPullRequestFile = {\n filename: string\n status: string\n additions: number\n deletions: number\n changes: number\n patch?: string\n}\n\ntype ListPullRequestFilesOutput = {\n items: ListPullRequestFile[]\n hasMore: boolean\n page: number\n perPage: number\n nextPage?: number\n}\n\ntype GetCommitOutput = {\n sha: string\n message: string\n author?: string\n authorLogin?: string\n date?: string\n url: string\n stats: { additions: number, deletions: number, total: number } | null\n files?: Array<{\n filename: string\n status: string\n additions: number\n deletions: number\n patch?: string\n }>\n}\n\ntype GetFileContentOutput =\n | { type: 'directory', entries: Array<{ name: string, type: string, path: string }> }\n | { type: string, path: string }\n | {\n type: 'file'\n path: string\n sha: string\n size: number\n content: string\n totalLines?: number\n startLine?: number\n endLine?: number\n truncated?: boolean\n }\n\nexport function listPullRequestFilesToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as ListPullRequestFilesOutput\n return {\n type: 'json' as const,\n value: {\n ...result,\n items: truncatePatchFields(result.items),\n },\n }\n}\n\nexport function getCommitToModelOutput({ output }: ToModelOutputOptions) {\n const commit = output as GetCommitOutput\n const { files, filesOmitted } = capDiffFiles(commit.files)\n return {\n type: 'json' as const,\n value: {\n ...commit,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n\ntype CompareCommitsOutput = {\n status: string\n aheadBy: number\n behindBy: number\n totalCommits: number\n url: string\n commits: Array<{ sha: string, message: string, author?: string, authorLogin?: string }>\n files?: Array<{\n filename: string\n status: string\n additions: number\n deletions: number\n patch?: string\n }>\n}\n\nexport function compareCommitsToModelOutput({ output }: ToModelOutputOptions) {\n const comparison = output as CompareCommitsOutput\n const { files, filesOmitted } = capDiffFiles(comparison.files)\n return {\n type: 'json' as const,\n value: {\n ...comparison,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n\nexport function getFileContentToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetFileContentOutput\n if (result.type === 'directory' && 'entries' in result && result.entries.length > MAX_MODEL_TREE_ENTRIES) {\n return {\n type: 'json' as const,\n value: {\n ...result,\n truncated: true,\n entries: result.entries.slice(0, MAX_MODEL_TREE_ENTRIES),\n entriesOmitted: result.entries.length - MAX_MODEL_TREE_ENTRIES,\n },\n }\n }\n if ('content' in result && result.content.length > MAX_CONTENT_LENGTH) {\n return {\n type: 'json' as const,\n value: {\n ...result,\n content: truncateText(result.content, MAX_CONTENT_LENGTH),\n },\n }\n }\n return { type: 'json' as const, value: result }\n}\n\ntype GetRepositoryTreeOutput = {\n sha: string\n truncated: boolean\n path?: string\n entries: Array<{ path?: string, type?: string, size?: number, sha?: string }>\n}\n\nexport function getRepositoryTreeToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetRepositoryTreeOutput\n if (result.entries.length <= MAX_MODEL_TREE_ENTRIES) {\n return { type: 'json' as const, value: result }\n }\n return {\n type: 'json' as const,\n value: {\n ...result,\n truncated: true,\n entries: result.entries.slice(0, MAX_MODEL_TREE_ENTRIES),\n entriesOmitted: result.entries.length - MAX_MODEL_TREE_ENTRIES,\n },\n }\n}\n\ntype GetPullRequestContextOutput = {\n pullRequest: {\n number: number\n title: string\n body: string | null\n state: string\n url: string\n author?: string\n branch: string\n headSha: string\n base: string\n draft?: boolean\n merged: boolean\n mergeable: boolean | null\n additions: number\n deletions: number\n changedFiles: number\n createdAt: string\n updatedAt: string\n mergedAt: string | null\n }\n files?: ListPullRequestFile[]\n filesHasMore?: boolean\n reviews?: Array<{\n id: number\n state: string\n body: string\n author?: string\n url: string\n submittedAt?: string | null\n }>\n checks?: {\n checkRuns: {\n totalCount: number\n checkRuns: Array<{\n id: number\n name: string\n status: string\n conclusion: string | null\n url: string | null\n startedAt: string | null\n completedAt: string | null\n }>\n }\n combinedStatus: {\n state: string\n totalCount: number\n statuses: Array<{\n context: string\n state: string\n description: string | null\n url: string | null\n }>\n }\n }\n}\n\nexport function getPullRequestContextToModelOutput({ output }: ToModelOutputOptions) {\n const result = output as GetPullRequestContextOutput\n const { files, filesOmitted } = capDiffFiles(result.files)\n return {\n type: 'json' as const,\n value: {\n ...result,\n files,\n ...filesOmitted > 0 ? { filesOmitted } : {},\n },\n }\n}\n","import * as ai from 'ai'\nimport type { Experimental_EvaluationModel, JSONValue, ModelMessage } from 'ai'\nimport { GITHUB_TOOL_CATALOG } from './catalog'\nimport { githubToolsErrors } from './errors'\nimport { CORE_READ_TOOLS, PRESET_TOOLS } from './presets'\nimport { ALL_GITHUB_TOOL_NAMES, type GithubToolName } from './tool-names'\nimport { DEFAULT_EVALUATION_MODEL, RISK_QUESTION, INTENT_QUESTION, PRESET_PURPOSES, conversationState, rankPresets, requiresApproval, type RoutablePreset } from './evaluation-policy'\nexport { DEFAULT_EVALUATION_MODEL, AUTO_APPROVAL_TOOLS } from './evaluation-policy'\nimport type { GithubWriteToolName } from './write-tools'\n\n/**\n * Tuning for `requireApproval: 'auto'` and `preset: 'auto'`. Every field is optional.\n */\nexport type GithubEvaluationOptions = {\n /**\n * Decision model for AI SDK `experimental_decide`: an AI Gateway ID or a model instance.\n * @default 'typesafe-ai/jev-1.14.0'\n */\n model?: Experimental_EvaluationModel\n /**\n * Provider options passed to every decision call, for example AI Gateway settings such as\n * `{ gateway: { zeroDataRetention: true } }`.\n */\n providerOptions?: Record<string, Record<string, JSONValue>>\n /**\n * Highest risk an `'auto'` tool call can have and still run without approval, on a 0–2 scale\n * (0 negligible, 1 visible but reversible, 2 hard to undo).\n * @default 1\n */\n maxRisk?: number\n /**\n * Lowest probability that the latest user message asked for the call, for it to run without approval.\n * @default 0.6\n */\n minIntent?: number\n /**\n * Lowest probability for `preset: 'auto'` to select a preset. When no preset reaches it,\n * read-only `repo-explorer` is used.\n * @default 0.7\n */\n minPresetProbability?: number\n /**\n * Most presets `preset: 'auto'` combines in one call, keeping the most likely ones.\n * @default 2\n */\n maxPresets?: number\n /**\n * What `preset: 'auto'` picks. `'tools'` asks the decision model about each tool and lists only\n * the likely ones plus the core read tools (`CORE_READ_TOOLS`), so the model sees far fewer tool\n * definitions. The rest stays reachable: eve defers it, and `createGithubAgent` adds a\n * `callGithubTool` tool. `'presets'` lists the tools of up to `maxPresets` presets and, on\n * `createGithubAgent`, uses their system prompts.\n * @default 'tools'\n */\n selection?: 'presets' | 'tools'\n /**\n * How long a `preset: 'auto'` decision lasts. `'session'` decides once, on the conversation's\n * first request, so the listed tools, and the provider's cached prompt prefix they start, stay\n * the same for the rest of the conversation; later needs go through deferred tools (eve) or\n * `callGithubTool` (`createGithubAgent`, which doesn't support it with `selection: 'presets'`).\n * `'turn'` decides again for each new request, which changes the tool list and makes the\n * provider write the whole conversation to its prompt cache again.\n * @default 'session', except `'turn'` for presets on `createGithubAgent`\n */\n scope?: 'turn' | 'session'\n /**\n * Keeps `createGithubAgent`'s `preset: 'auto'` decisions across processes, such as serverless\n * instances, under keys derived from the request and the routing settings (decision model,\n * thresholds and caps), so agents configured differently don't share decisions. Without it, a decision\n * lives in this process's memory, and another process decides again: that costs a decision\n * call, and a different pick changes the tool list and invalidates the provider's prompt cache.\n * The eve extension keeps decisions in the session and ignores this option.\n */\n store?: {\n get: (key: string) => Promise<readonly string[] | undefined>\n set: (key: string, value: readonly string[]) => Promise<void>\n }\n /**\n * Lowest probability for `selection: 'tools'` to list a tool beyond the core read tools.\n * @default 0.5\n */\n minToolProbability?: number\n /**\n * Most tools `selection: 'tools'` lists beyond the core read tools, keeping the most likely ones.\n * @default 8\n */\n maxTools?: number\n}\n\n/**\n * Throws `EVALUATION_UNAVAILABLE` when the installed `ai` has neither `experimental_decide`\n * nor `experimental_evaluate`. Call it where `'auto'` is configured, so a too-old `ai` fails\n * at setup instead of mid-conversation.\n */\nexport function assertEvaluationAvailable() {\n loadDecide()\n}\n\n// `experimental_decide` replaced `experimental_evaluate` in ai 7.0.128; the old name stays an alias.\nfunction loadDecide(): typeof ai.experimental_decide {\n const exports: Partial<Pick<typeof ai, 'experimental_decide' | 'experimental_evaluate'>> = ai\n const decide = exports.experimental_decide ?? exports.experimental_evaluate\n if (!decide) throw githubToolsErrors.EVALUATION_UNAVAILABLE()\n return decide\n}\n\n// `decide` throws when the model refuses any question; the error names the refused questions.\nfunction refusedQuestions(error: unknown): readonly string[] | undefined {\n const exports: Partial<Pick<typeof ai, 'Experimental_DecisionRefusalError'>> = ai\n return exports.Experimental_DecisionRefusalError?.isInstance(error) ? error.questionIds : undefined\n}\n\nfunction warnEvaluationFailed(model: Experimental_EvaluationModel, fallback: string, error: unknown, abortSignal?: AbortSignal) {\n abortSignal?.throwIfAborted()\n const cause = error instanceof Error ? error : new Error(String(error))\n console.warn('[github-tools]', githubToolsErrors.EVALUATION_FAILED({\n model: typeof model === 'string' ? model : model.modelId,\n fallback,\n detail: cause.message,\n cause,\n }))\n}\n\n/** Whether a person should approve a GitHub write, and why, as a short sentence for the approval request. */\nexport type AutoApprovalDecision = { ask: boolean, reason: string }\n\nconst RISK_LABELS = RISK_QUESTION.criteria.map(criterion => criterion.slice(0, criterion.indexOf(':')))\n\n/**\n * Asks the decision model how risky a GitHub write is and whether the user asked for it, and\n * explains the outcome: `ask` is true when a person should approve the call. A failed or refused\n * decision asks, since it gives no evidence that the call is safe.\n */\nexport async function autoApprovalDecision(\n toolName: GithubWriteToolName,\n input: unknown,\n messages: readonly ModelMessage[],\n { model = DEFAULT_EVALUATION_MODEL, maxRisk = 1, minIntent = 0.6, providerOptions }: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<AutoApprovalDecision> {\n const decide = loadDecide()\n let refused = false\n const result = await decide({\n model,\n providerOptions,\n state: {\n ...conversationState(messages, messageText),\n toolCall: {\n tool: toolName,\n description: GITHUB_TOOL_CATALOG[toolName].description,\n input: input as JSONValue,\n },\n },\n questions: {\n risk: { type: 'score', ...RISK_QUESTION },\n intent: { type: 'boolean', ...INTENT_QUESTION },\n },\n abortSignal,\n }).catch((error: unknown) => {\n // A refusal is an answer, not an outage: it gives no evidence the call is safe, so a person decides.\n refused = Boolean(refusedQuestions(error))\n if (!refused) warnEvaluationFailed(model, `asking approval for ${toolName}`, error, abortSignal)\n return undefined\n })\n if (!result) return { ask: true, reason: refused ? 'The decision model declined to rate this call.' : 'The decision model was unavailable.' }\n const risk = result.answers.risk.score\n const intent = result.answers.intent.probability\n // Jev scores risk on a continuous 0–2 scale, so the label is the nearest rubric level.\n const verdict = `${RISK_LABELS[Math.round(risk)]} (risk ${Number(risk.toFixed(1))} of 2), ${Math.round(intent * 100)}% likely you asked for it`\n return requiresApproval(risk, intent, { maxRisk, minIntent })\n ? { ask: true, reason: `${verdict}.` }\n : { ask: false, reason: `Approved automatically: ${verdict.charAt(0).toLowerCase()}${verdict.slice(1)}.` }\n}\n\n/** Whether a GitHub write needs a person's approval; see {@link autoApprovalDecision}. */\nexport async function needsAutoApproval(\n toolName: GithubWriteToolName,\n input: unknown,\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<boolean> {\n return (await autoApprovalDecision(toolName, input, messages, options, abortSignal)).ask\n}\n\n/**\n * Presets the latest user message needs, from one evaluation call with an independent\n * yes/no question per preset. Returns up to `maxPresets` presets at or above\n * `minPresetProbability`, most likely first, and read-only `repo-explorer` when none qualifies.\n * `repo-explorer` is only combined with no other preset. Rejects when the evaluation call fails;\n * {@link selectPresets} falls back instead. Never returns `maintainer`, so the full catalog is never exposed.\n */\nexport async function evaluatePresets(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<RoutablePreset[]> {\n const { minPresetProbability = 0.7, maxPresets = 2 } = options\n const presets = Object.keys(PRESET_PURPOSES) as RoutablePreset[]\n const probabilities = await decideEach(messages, presets, preset => ({\n instructions: 'Does handling this GitHub request need the tools of this preset?',\n criteria: { true: { purpose: PRESET_PURPOSES[preset], tools: [...PRESET_TOOLS[preset]] } },\n }), options, abortSignal)\n return rankPresets(probabilities, { minPresetProbability, maxPresets })\n}\n\n/**\n * Tools the latest user message needs, from one decision call with a yes/no question per tool:\n * the core read tools, plus up to `maxTools` others at or above `minToolProbability`, most likely\n * first. Rejects when the decision call fails; {@link selectTools} falls back instead.\n */\nexport async function evaluateTools(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<GithubToolName[]> {\n const { minToolProbability = 0.5, maxTools = 8 } = options\n const core: readonly GithubToolName[] = CORE_READ_TOOLS\n const candidates = ALL_GITHUB_TOOL_NAMES.filter(name => !core.includes(name))\n const probabilities = await decideEach(messages, candidates, name => ({\n instructions: 'Does handling this GitHub request need this tool?',\n criteria: { true: { tool: name, description: GITHUB_TOOL_CATALOG[name].description } },\n }), options, abortSignal)\n const likely = candidates\n .filter(name => probabilities[name] >= minToolProbability)\n .toSorted((a, b) => probabilities[b] - probabilities[a])\n .slice(0, maxTools)\n return [...core, ...likely]\n}\n\ntype BooleanQuestion = { instructions: string, criteria: { true: Record<string, JSONValue> } }\n\n// One boolean question per key against the conversation. A refused question counts as a no:\n// ask once more without it instead of losing every answer.\nasync function decideEach<K extends string>(\n messages: readonly ModelMessage[],\n keys: readonly K[],\n question: (key: K) => BooleanQuestion,\n { model = DEFAULT_EVALUATION_MODEL, providerOptions }: GithubEvaluationOptions,\n abortSignal?: AbortSignal,\n): Promise<Record<K, number>> {\n const decide = loadDecide()\n const state = conversationState(messages, messageText)\n const ask = (asked: readonly K[]) => decide({\n model,\n providerOptions,\n state,\n questions: Object.fromEntries(asked.map(key => [key, { type: 'boolean' as const, ...question(key) }])),\n abortSignal,\n })\n const probabilities = Object.fromEntries(keys.map(key => [key, 0])) as Record<K, number>\n const { answers } = await ask(keys).catch((error: unknown) => {\n const refused = refusedQuestions(error)\n const remaining = keys.filter(key => !refused?.includes(key))\n if (!refused || remaining.length === 0) throw error\n return ask(remaining)\n })\n for (const [key, answer] of Object.entries(answers)) probabilities[key as K] = answer.probability\n return probabilities\n}\n\n/**\n * Logs `EVALUATION_FAILED` for a failed {@link evaluatePresets} call and returns the read-only\n * `repo-explorer` fallback. Rethrows when `abortSignal` is aborted.\n */\nexport function fallbackPresets(error: unknown, { model = DEFAULT_EVALUATION_MODEL }: GithubEvaluationOptions = {}, abortSignal?: AbortSignal): RoutablePreset[] {\n warnEvaluationFailed(model, 'using the repo-explorer preset', error, abortSignal)\n return ['repo-explorer']\n}\n\n/**\n * Logs `EVALUATION_FAILED` for a failed {@link evaluateTools} call and returns the read-only\n * `repo-explorer` tools. Rethrows when `abortSignal` is aborted.\n */\nexport function fallbackTools(error: unknown, { model = DEFAULT_EVALUATION_MODEL }: GithubEvaluationOptions = {}, abortSignal?: AbortSignal): GithubToolName[] {\n warnEvaluationFailed(model, 'using the repo-explorer tools', error, abortSignal)\n return [...PRESET_TOOLS['repo-explorer']]\n}\n\n/**\n * {@link evaluateTools}, falling back to the read-only `repo-explorer` tools (and logging\n * `EVALUATION_FAILED`) when the decision call fails.\n */\nexport async function selectTools(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<GithubToolName[]> {\n return evaluateTools(messages, options, abortSignal).catch(error => fallbackTools(error, options, abortSignal))\n}\n\n/**\n * {@link evaluatePresets}, falling back to read-only `repo-explorer` (and logging\n * `EVALUATION_FAILED`) when the evaluation call fails.\n */\nexport async function selectPresets(\n messages: readonly ModelMessage[],\n options: GithubEvaluationOptions = {},\n abortSignal?: AbortSignal,\n): Promise<RoutablePreset[]> {\n return evaluatePresets(messages, options, abortSignal).catch(error => fallbackPresets(error, options, abortSignal))\n}\n\nexport function latestUserText(messages: readonly ModelMessage[]): string {\n return conversationState(messages, messageText).request\n}\n\n/** The `request` and `repliedTo` the evaluation model sees for these messages. */\nexport function evaluationRequest(messages: readonly ModelMessage[]) {\n return conversationState(messages, messageText)\n}\n\nfunction messageText(message: ModelMessage): string {\n if (typeof message.content === 'string') return message.content\n return message.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\\n')\n}\n"],"mappings":";;;AAAA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAE7B,SAAS,aAAa,MAAc,WAA2B;CAC7D,IAAI,KAAK,UAAU,WAAW,OAAO;CACrC,OAAO,GAAG,KAAK,MAAM,GAAG,SAAS,EAAE,kBAAkB,KAAK,SAAS,UAAU;AAC/E;AAEA,SAAS,oBAAkD,OAAiB;CAC1E,OAAO,MAAM,KAAI,UAAS;EACxB,GAAG;EACH,OAAO,KAAK,QAAQ,aAAa,KAAK,OAAO,gBAAgB,IAAI,KAAK;CACxE,EAAE;AACJ;AAEA,SAAS,aAA2C,OAAwB;CAC1E,IAAI,CAAC,OAAO,OAAO;EAAE;EAA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KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI;AAC3F"}
@@ -1,10 +1,9 @@
1
- import { G as GithubWriteToolName, I as GithubGuardrails, N as GithubTokenInput, R as CombinedPresetToolNames, V as PresetToolName, W as GithubToolName, c as CommitIdentity, s as GithubToolsContext, t as GithubDryRunApproval, z as GithubToolPreset } from "./dry-run-DXckOam2.mjs";
2
- import { i as EveToolFactoryOptions, n as EveApprovalValue, r as EveGithubToolsOptions, t as EveApprovalConfig } from "./types-C7O2lwwz.mjs";
3
- import "./index-CzzrtCVj.mjs";
1
+ import "./index-v5n5OLs7.mjs";
2
+ import { B as GithubToolPreset, G as GithubToolName, H as PresetToolName, K as GithubWriteToolName, L as GithubGuardrails, N as GithubTokenInput, P as GithubTokenResolver, c as CommitIdentity, s as GithubToolsContext, t as GithubDryRunApproval, z as CombinedPresetToolNames } from "./dry-run-BAbes7Mv.mjs";
3
+ import { i as EveToolFactoryOptions, n as EveApprovalValue, r as EveGithubToolsOptions, t as EveApprovalConfig } from "./types-C-BIKmas.mjs";
4
4
  import { z } from "zod";
5
5
  import { ToolDefinition, ToolModelOutput } from "eve/tools";
6
6
  import { Approval, ApprovalPolicy } from "eve/tools/approval";
7
- //#region src/eve/registry.d.ts
8
7
  type ToolBuildContext = {
9
8
  token: GithubTokenInput;
10
9
  context?: GithubToolsContext;
@@ -24,8 +23,6 @@ declare function hasGithubEveToolModelOutput(name: GithubToolName): boolean;
24
23
  * Used by `@github-tools/eve-extension` so the callback only closes over a serializable tool name.
25
24
  */
26
25
  declare function formatGithubEveToolOutput(name: GithubToolName, output: unknown): ToolModelOutput;
27
- //#endregion
28
- //#region src/eve/build.d.ts
29
26
  type BuildOptions = EveGithubToolsOptions | (EveToolFactoryOptions & {
30
27
  preset?: EveGithubToolsOptions['preset'];
31
28
  });
@@ -62,11 +59,12 @@ declare function listEveToolDescriptors(options?: EveGithubToolsOptions): {
62
59
  }[];
63
60
  /**
64
61
  * Execute a GitHub tool by name with the given eve options (token/context/attribution).
62
+ * A failed call throws, so eve settles it as `failed`. For a catalog error, the message is
63
+ * its `{ code, message, why, fix, link }` as JSON and `cause` is its `{ code, status }`.
64
+ * The thrown error holds nothing from the GitHub request.
65
65
  * Used by `@github-tools/eve-extension` so `execute` only closes over a serializable tool name.
66
66
  */
67
67
  declare function executeGithubEveTool(name: GithubToolName, input: Record<string, unknown>, options?: EveGithubToolsOptions): Promise<unknown>;
68
- //#endregion
69
- //#region src/eve/approval.d.ts
70
68
  /**
71
69
  * `false` / `'never'` should omit the tool `approval` field entirely.
72
70
  * eve treats a missing `approval` like `never()`; attaching `never()` is
@@ -81,12 +79,66 @@ declare function resolveEveApproval(toolName: GithubWriteToolName, config: EveAp
81
79
  * attach a redundant `never()` handler.
82
80
  */
83
81
  declare function resolveEveToolApproval(toolName: GithubWriteToolName, config: EveApprovalConfig | undefined, override?: EveApprovalValue): Approval | undefined;
84
- //#endregion
85
- //#region src/eve/steps.d.ts
86
82
  /** Why `guardrails` block a call once `context` defaults are applied, or `undefined` when they allow it. */
87
83
  declare function githubGuardrailViolation(name: GithubToolName, input: Record<string, unknown>, { context, guardrails }: Pick<ToolBuildContext, 'context' | 'guardrails'>): string | undefined;
88
- //#endregion
89
- //#region src/eve/load-eve.d.ts
84
+ /** GitHub's repository roles, lowest first. */
85
+ declare const GITHUB_ROLES: readonly ["read", "triage", "write", "maintain", "admin"];
86
+ type GithubRole = typeof GITHUB_ROLES[number];
87
+ /**
88
+ * Rank of an answer from GitHub's collaborator permission endpoint in {@link GITHUB_ROLES}, or `-1`
89
+ * without access. A custom role ranks as the base permission GitHub reports for it.
90
+ */
91
+ declare function githubRoleRank({ permission, roleName }: {
92
+ permission: string;
93
+ roleName?: string;
94
+ }): number;
95
+ type Repository = {
96
+ owner: string;
97
+ repo: string;
98
+ };
99
+ /** A person the tools act for with a token that isn't theirs, such as a GitHub App's. */
100
+ type GithubCaller = {
101
+ /** Their GitHub login. */
102
+ login: string;
103
+ /** The repository they asked from. A search runs only when its token reaches this repository and no other. */
104
+ repository?: Repository;
105
+ };
106
+ /**
107
+ * Wrap a token so every call it resolves for is first checked against what `caller` may do, read
108
+ * from GitHub with that same token. Use it when the tools run with a GitHub App's token for a person
109
+ * who can't get their own, such as someone commenting on GitHub: the App then does nothing that
110
+ * person couldn't. A refused call throws `github_tools.CALLER_FORBIDDEN` before it reaches GitHub.
111
+ *
112
+ * - A call on a repository needs the Read role there for a read and Write for a write, which is
113
+ * stricter than GitHub for the writes a reader can make, such as a comment. `addSubIssue` also
114
+ * needs Read on the sub-issue's repository.
115
+ * - `resolveReviewThread` needs Write on the repository the thread is in.
116
+ * - A search needs `caller.repository`, the Read role there, and a token that reaches that
117
+ * repository and no other, so it can't return results from one the caller can't see.
118
+ * - Every other call without a repository is refused, since no role on a repository covers it:
119
+ * gists, notifications, `createRepository` and `forkRepository`.
120
+ */
121
+ declare function withGithubCallerAccess(token: GithubTokenInput | undefined, caller: GithubCaller): GithubTokenResolver;
122
+ /** A GitHub App's bot account, the identity GitHub shows for what the App writes. */
123
+ type GithubAppBot = {
124
+ /** The App's slug, as in `https://github.com/apps/<slug>`. */
125
+ slug: string;
126
+ /** The bot's login, `<slug>[bot]`. */
127
+ login: string;
128
+ /** The bot's numeric user id. */
129
+ id: number;
130
+ };
131
+ /** The tools that create a commit and add `coAuthors` to its message. */
132
+ declare const GITHUB_COMMIT_TOOLS: ReadonlySet<GithubToolName>;
133
+ /**
134
+ * Read the bot of the GitHub App that issued `token`, a user access token. GitHub lists only that
135
+ * App's installations to such a token, so the first one names the App.
136
+ */
137
+ declare function githubAppBot(token: string): Promise<GithubAppBot>;
138
+ /** The bot as a commit identity, with the noreply address GitHub links to its account. */
139
+ declare function githubAppBotIdentity(bot: GithubAppBot): CommitIdentity;
140
+ /** `body` with a closing line saying the App generated the pull request. */
141
+ declare function withGithubAppFooter(body: string | undefined, bot: GithubAppBot): string;
90
142
  /**
91
143
  * @deprecated Never thrown since eve moved to static ESM imports — a missing
92
144
  * `eve` package now fails at module resolution with the bundler/runtime's own
@@ -94,6 +146,5 @@ declare function githubGuardrailViolation(name: GithubToolName, input: Record<st
94
146
  * match on it. Will be removed in the next major.
95
147
  */
96
148
  declare const MISSING_EVE_MESSAGE = "The \"eve\" package is required to use @github-tools/sdk/eve. Install it with: pnpm add eve";
97
- //#endregion
98
- export { resolveEveApproval as a, buildEveToolMap as c, listEveToolDescriptors as d, listResolvedEveToolNames as f, mapEveApprovalValue as i, createEveGithubToolsDynamic as l, hasGithubEveToolModelOutput as m, githubGuardrailViolation as n, resolveEveToolApproval as o, formatGithubEveToolOutput as p, isEveApprovalDisabled as r, buildEveToolDefinition as s, MISSING_EVE_MESSAGE as t, executeGithubEveTool as u };
99
- //# sourceMappingURL=eve-runtime-B_CJE9JV.d.mts.map
149
+ export { formatGithubEveToolOutput as C, listResolvedEveToolNames as S, buildEveToolDefinition as _, githubAppBotIdentity as a, executeGithubEveTool as b, GithubCaller as c, withGithubCallerAccess as d, githubGuardrailViolation as f, resolveEveToolApproval as g, resolveEveApproval as h, githubAppBot as i, GithubRole as l, mapEveApprovalValue as m, GITHUB_COMMIT_TOOLS as n, withGithubAppFooter as o, isEveApprovalDisabled as p, GithubAppBot as r, GITHUB_ROLES as s, MISSING_EVE_MESSAGE as t, githubRoleRank as u, buildEveToolMap as v, hasGithubEveToolModelOutput as w, listEveToolDescriptors as x, createEveGithubToolsDynamic as y };
150
+ //# sourceMappingURL=eve-runtime-CoBSN8nF.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eve-runtime-CoBSN8nF.d.mts","names":["_$__0.GithubWriteToolName"],"sources":["../src/eve/registry.ts","../src/eve/build.ts","../src/eve/approval.ts","../src/eve/steps.ts","../src/core/caller-access.ts","../src/core/attribution.ts","../src/eve/load-eve.ts"],"mappings":";;;;;;KAuBY;EACV,OAAO;EACP,UAAU;EACV,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,aAAa;EACb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as toModelErrorPayload, S as resolveGithubToken, T as GITHUB_TOOL_CATALOG, Xa as EvlogError, Za as githubToolsErrors, b as createGithubTokenResolver, i as dryRunWrite, o as mergeContextArgs, s as softenContextSchema, w as ALL_GITHUB_TOOL_NAMES, x as githubTokenCall, y as resolvePresetTools, zr as guardrailViolation } from "./write-tools-w-8tjnDQ.mjs";
2
- import { _ as listPullRequestFilesToModelOutput, f as compareCommitsToModelOutput, g as getRepositoryTreeToModelOutput, h as getPullRequestContextToModelOutput, m as getFileContentToModelOutput, p as getCommitToModelOutput } from "./evaluation-DJHINyAu.mjs";
3
- import { t as GITHUB_TOOL_CORES } from "./cores-meFAMt2D.mjs";
1
+ import { $a as stripRateLimit, E as isGithubWriteToolName, Pa as getCollaboratorPermissionCore, Qa as toModelErrorPayload, S as resolveGithubToken, T as GITHUB_TOOL_CATALOG, Xa as EvlogError, Ya as createOctokit, Za as githubToolsErrors, b as createGithubTokenResolver, i as dryRunWrite, o as mergeContextArgs, s as softenContextSchema, w as ALL_GITHUB_TOOL_NAMES, x as githubTokenCall, y as resolvePresetTools, zr as guardrailViolation } from "./write-tools-C-962T9O.mjs";
2
+ import { t as GITHUB_TOOL_CORES } from "./cores-H6HKlwFZ.mjs";
3
+ import { _ as listPullRequestFilesToModelOutput, f as compareCommitsToModelOutput, g as getRepositoryTreeToModelOutput, h as getPullRequestContextToModelOutput, m as getFileContentToModelOutput, p as getCommitToModelOutput } from "./evaluation-Dlf-571x.mjs";
4
4
  import * as eveTools from "eve/tools";
5
5
  import * as eveApproval from "eve/tools/approval";
6
- //#region src/eve/load-eve.ts
6
+ // src/eve/load-eve.ts
7
7
  /**
8
8
  * @deprecated Never thrown since eve moved to static ESM imports — a missing
9
9
  * `eve` package now fails at module resolution with the bundler/runtime's own
@@ -17,8 +17,7 @@ function getEveTools() {
17
17
  function getEveApprovalHelpers() {
18
18
  return eveApproval;
19
19
  }
20
- //#endregion
21
- //#region src/eve/approval.ts
20
+ // src/eve/approval.ts
22
21
  /**
23
22
  * `false` / `'never'` should omit the tool `approval` field entirely.
24
23
  * eve treats a missing `approval` like `never()`; attaching `never()` is
@@ -55,8 +54,7 @@ function resolveEveToolApproval(toolName, config, override) {
55
54
  if (typeof value === "function" || typeof value === "object") return value;
56
55
  return mapEveApprovalValue(value);
57
56
  }
58
- //#endregion
59
- //#region src/eve/registry.ts
57
+ // src/eve/registry.ts
60
58
  function withToken(core, ctx, extra, guard) {
61
59
  return async (input) => core({
62
60
  token: await resolveGithubToken(ctx.token),
@@ -93,10 +91,6 @@ function hasGithubEveToolModelOutput(name) {
93
91
  */
94
92
  function formatGithubEveToolOutput(name, output) {
95
93
  const stripped = stripRateLimit(output);
96
- if (isErrorPayload(stripped)) return {
97
- type: "json",
98
- value: stripped
99
- };
100
94
  const format = GITHUB_EVE_TOOL_MODEL_OUTPUT[name];
101
95
  if (!format) return {
102
96
  type: "json",
@@ -104,11 +98,6 @@ function formatGithubEveToolOutput(name, output) {
104
98
  };
105
99
  return format(stripped);
106
100
  }
107
- function isErrorPayload(output) {
108
- if (output == null || typeof output !== "object" || Array.isArray(output)) return false;
109
- const { error } = output;
110
- return typeof error === "string" || error != null && typeof error === "object";
111
- }
112
101
  function createToolRegistry(ctx, names = ALL_GITHUB_TOOL_NAMES) {
113
102
  const commitExtras = {
114
103
  createOrUpdateFile: {
@@ -151,8 +140,7 @@ function createToolRegistry(ctx, names = ALL_GITHUB_TOOL_NAMES) {
151
140
  inputSchema: softenContextSchema(entry.inputSchema, ctx.context)
152
141
  }));
153
142
  }
154
- //#endregion
155
- //#region src/eve/steps.ts
143
+ // src/eve/steps.ts
156
144
  async function executeGithubToolStep(name, input, ctx) {
157
145
  "use step";
158
146
  const [entry] = createToolRegistry(ctx, ALL_GITHUB_TOOL_NAMES.filter((tool) => tool === name));
@@ -163,6 +151,15 @@ async function executeGithubToolStep(name, input, ctx) {
163
151
  function githubGuardrailViolation(name, input, { context, guardrails }) {
164
152
  return guardrailViolation(githubTokenCall(name, mergeContextArgs(input, context ?? {})), guardrails);
165
153
  }
154
+ function isErrorResult(result) {
155
+ return typeof result === "object" && result !== null && "error" in result && typeof result.error === "string";
156
+ }
157
+ function withoutRequest(error) {
158
+ if (!(error instanceof Error) || !("request" in error || "response" in error)) return error;
159
+ const reduced = new Error(error.message);
160
+ reduced.name = error.name;
161
+ return reduced;
162
+ }
166
163
  async function runGithubToolStep(name, input, ctx) {
167
164
  try {
168
165
  const call = githubTokenCall(name, mergeContextArgs(input, ctx.context ?? {}));
@@ -170,17 +167,21 @@ async function runGithubToolStep(name, input, ctx) {
170
167
  if (reason) throw githubToolsErrors.GUARDRAIL_BLOCKED({ reason });
171
168
  if (ctx.dryRun && isGithubWriteToolName(name)) return dryRunWrite(name, call.input, ctx.guardrails, () => ctx.dryRunApproval);
172
169
  const token = await resolveGithubToken(ctx.token, call);
173
- return await executeGithubToolStep(name, input, {
170
+ const result = await executeGithubToolStep(name, input, {
174
171
  ...ctx,
175
172
  token
176
173
  });
174
+ if (isErrorResult(result)) throw new Error(result.error);
175
+ return result;
177
176
  } catch (error) {
178
- if (EvlogError.isEvlogError(error)) return { error: toModelErrorPayload(error) };
179
- return { error: error instanceof Error ? error.message : String(error) };
177
+ if (EvlogError.isEvlogError(error)) throw new Error(JSON.stringify(toModelErrorPayload(error)), { cause: {
178
+ code: error.code,
179
+ status: error.status
180
+ } });
181
+ throw withoutRequest(error);
180
182
  }
181
183
  }
182
- //#endregion
183
- //#region src/eve/build.ts
184
+ // src/eve/build.ts
184
185
  function resolveAllowedToolNames(options) {
185
186
  const presetAllowed = options.preset ? resolvePresetTools(options.preset) : null;
186
187
  const includeAllowed = options.include ? new Set(options.include) : null;
@@ -293,6 +294,9 @@ function listEveToolDescriptors(options = {}) {
293
294
  }
294
295
  /**
295
296
  * Execute a GitHub tool by name with the given eve options (token/context/attribution).
297
+ * A failed call throws, so eve settles it as `failed`. For a catalog error, the message is
298
+ * its `{ code, message, why, fix, link }` as JSON and `cause` is its `{ code, status }`.
299
+ * The thrown error holds nothing from the GitHub request.
296
300
  * Used by `@github-tools/eve-extension` so `execute` only closes over a serializable tool name.
297
301
  */
298
302
  async function executeGithubEveTool(name, input, options = {}) {
@@ -307,7 +311,190 @@ async function executeGithubEveTool(name, input, options = {}) {
307
311
  dryRunApproval: options.dryRunApproval
308
312
  });
309
313
  }
310
- //#endregion
311
- export { listEveToolDescriptors as a, formatGithubEveToolOutput as c, mapEveApprovalValue as d, resolveEveApproval as f, executeGithubEveTool as i, hasGithubEveToolModelOutput as l, MISSING_EVE_MESSAGE as m, buildEveToolMap as n, listResolvedEveToolNames as o, resolveEveToolApproval as p, createEveGithubToolsDynamic as r, githubGuardrailViolation as s, buildEveToolDefinition as t, isEveApprovalDisabled as u };
314
+ // src/core/caller-access.ts
315
+ /** GitHub's repository roles, lowest first. */
316
+ const GITHUB_ROLES = [
317
+ "read",
318
+ "triage",
319
+ "write",
320
+ "maintain",
321
+ "admin"
322
+ ];
323
+ /**
324
+ * Rank of an answer from GitHub's collaborator permission endpoint in {@link GITHUB_ROLES}, or `-1`
325
+ * without access. A custom role ranks as the base permission GitHub reports for it.
326
+ */
327
+ function githubRoleRank({ permission, roleName }) {
328
+ const role = GITHUB_ROLES.indexOf(roleName);
329
+ return role >= 0 ? role : GITHUB_ROLES.indexOf(permission);
330
+ }
331
+ const ROLE_TTL_MS = 6e4;
332
+ const MAX_CACHED_ROLES = 500;
333
+ const roles = /* @__PURE__ */ new Map();
334
+ function callerRank(resolve, login, { owner, repo }) {
335
+ const key = `${login}\n${owner}/${repo}`.toLowerCase();
336
+ const cached = roles.get(key);
337
+ if (cached && cached.expires > Date.now()) return cached.rank;
338
+ const input = {
339
+ owner,
340
+ repo,
341
+ username: login
342
+ };
343
+ const rank = resolve({
344
+ toolName: "getCollaboratorPermission",
345
+ input,
346
+ owner,
347
+ repo
348
+ }).then((token) => getCollaboratorPermissionCore({
349
+ token,
350
+ ...input
351
+ })).then(githubRoleRank);
352
+ roles.set(key, {
353
+ expires: Date.now() + ROLE_TTL_MS,
354
+ rank
355
+ });
356
+ rank.catch(() => roles.delete(key));
357
+ if (roles.size > MAX_CACHED_ROLES) roles.delete(roles.keys().next().value);
358
+ return rank;
359
+ }
360
+ const refusal = (reason) => githubToolsErrors.CALLER_FORBIDDEN({ reason });
361
+ async function requireRole(resolve, login, toolName, repository, role) {
362
+ const rank = await callerRank(resolve, login, repository);
363
+ if (rank < GITHUB_ROLES.indexOf(role)) throw refusal(`${login} has ${rank < 0 ? "no" : GITHUB_ROLES[rank]} access to ${repository.owner}/${repository.repo}, and \`${toolName}\` needs ${role} access.`);
364
+ }
365
+ const REVIEW_THREAD_REPOSITORY = `
366
+ query ReviewThreadRepository($threadId: ID!) {
367
+ node(id: $threadId) {
368
+ ... on PullRequestReviewThread {
369
+ repository {
370
+ name
371
+ owner {
372
+ login
373
+ }
374
+ }
375
+ }
376
+ }
377
+ }
378
+ `;
379
+ async function reviewThreadRepository(token, threadId) {
380
+ const repository = (await createOctokit(token).graphql(REVIEW_THREAD_REPOSITORY, { threadId })).node?.repository;
381
+ return repository && {
382
+ owner: repository.owner.login,
383
+ repo: repository.name
384
+ };
385
+ }
386
+ async function reachesOnly(token, { owner, repo }) {
387
+ try {
388
+ const { data } = await createOctokit(token).rest.apps.listReposAccessibleToInstallation({ per_page: 2 });
389
+ return data.total_count === 1 && data.repositories[0]?.full_name.toLowerCase() === `${owner}/${repo}`.toLowerCase();
390
+ } catch (error) {
391
+ if (EvlogError.isEvlogError(error) && (error.status === 403 || error.status === 404)) return false;
392
+ throw error;
393
+ }
394
+ }
395
+ const SEARCH_TOOLS = /* @__PURE__ */ new Set([
396
+ "searchCode",
397
+ "searchIssues",
398
+ "searchRepositories"
399
+ ]);
400
+ /**
401
+ * Wrap a token so every call it resolves for is first checked against what `caller` may do, read
402
+ * from GitHub with that same token. Use it when the tools run with a GitHub App's token for a person
403
+ * who can't get their own, such as someone commenting on GitHub: the App then does nothing that
404
+ * person couldn't. A refused call throws `github_tools.CALLER_FORBIDDEN` before it reaches GitHub.
405
+ *
406
+ * - A call on a repository needs the Read role there for a read and Write for a write, which is
407
+ * stricter than GitHub for the writes a reader can make, such as a comment. `addSubIssue` also
408
+ * needs Read on the sub-issue's repository.
409
+ * - `resolveReviewThread` needs Write on the repository the thread is in.
410
+ * - A search needs `caller.repository`, the Read role there, and a token that reaches that
411
+ * repository and no other, so it can't return results from one the caller can't see.
412
+ * - Every other call without a repository is refused, since no role on a repository covers it:
413
+ * gists, notifications, `createRepository` and `forkRepository`.
414
+ */
415
+ function withGithubCallerAccess(token, caller) {
416
+ const resolve = createGithubTokenResolver(token);
417
+ const { login } = caller;
418
+ return async (call) => {
419
+ if (!call) throw new Error("`withGithubCallerAccess` needs the tool call to check the caller's access.");
420
+ const { toolName } = call;
421
+ if (toolName === "createRepository" || toolName === "forkRepository") throw refusal(`\`${toolName}\` creates a repository, which no role on a repository allows, so it can't run for ${login}.`);
422
+ if (call.owner && call.repo) {
423
+ const { owner } = call;
424
+ await requireRole(resolve, login, toolName, {
425
+ owner,
426
+ repo: call.repo
427
+ }, isGithubWriteToolName(toolName) ? "write" : "read");
428
+ const { subIssueRepo } = call.input;
429
+ if (toolName === "addSubIssue" && typeof subIssueRepo === "string") await requireRole(resolve, login, toolName, {
430
+ owner,
431
+ repo: subIssueRepo
432
+ }, "read");
433
+ return resolve(call);
434
+ }
435
+ if (toolName === "resolveReviewThread") {
436
+ const { threadId } = call.input;
437
+ const repository = await reviewThreadRepository(await resolve({
438
+ ...call,
439
+ ...caller.repository
440
+ }), threadId);
441
+ if (!repository) throw refusal(`The review thread can't be found, so ${login}'s role on its repository can't be checked.`);
442
+ await requireRole(resolve, login, toolName, repository, "write");
443
+ return resolve({
444
+ ...call,
445
+ ...repository
446
+ });
447
+ }
448
+ if (SEARCH_TOOLS.has(toolName) && caller.repository) {
449
+ const { owner, repo } = caller.repository;
450
+ await requireRole(resolve, login, toolName, caller.repository, "read");
451
+ const scoped = await resolve({
452
+ ...call,
453
+ owner,
454
+ repo
455
+ });
456
+ if (!await reachesOnly(scoped, caller.repository)) throw refusal(`\`${toolName}\` would search every repository the agent's token reaches, not only ${owner}/${repo}, and ${login}'s role can't be checked on all of them.`);
457
+ return scoped;
458
+ }
459
+ throw refusal(`\`${toolName}\` names no repository, so ${login}'s role can't be checked for it.`);
460
+ };
461
+ }
462
+ // src/core/attribution.ts
463
+ /** The tools that create a commit and add `coAuthors` to its message. */
464
+ const GITHUB_COMMIT_TOOLS = /* @__PURE__ */ new Set([
465
+ "createOrUpdateFile",
466
+ "editFiles",
467
+ "mergePullRequest",
468
+ "enablePullRequestAutoMerge"
469
+ ]);
470
+ /**
471
+ * Read the bot of the GitHub App that issued `token`, a user access token. GitHub lists only that
472
+ * App's installations to such a token, so the first one names the App.
473
+ */
474
+ async function githubAppBot(token) {
475
+ const octokit = createOctokit(token);
476
+ const { data } = await octokit.rest.apps.listInstallationsForAuthenticatedUser({ per_page: 1 });
477
+ const slug = data.installations[0]?.app_slug;
478
+ if (!slug) throw githubToolsErrors.APP_BOT_UNKNOWN();
479
+ const { data: bot } = await octokit.rest.users.getByUsername({ username: `${slug}[bot]` });
480
+ return {
481
+ slug,
482
+ login: bot.login,
483
+ id: bot.id
484
+ };
485
+ }
486
+ /** The bot as a commit identity, with the noreply address GitHub links to its account. */
487
+ function githubAppBotIdentity(bot) {
488
+ return {
489
+ name: bot.login,
490
+ email: `${bot.id}+${bot.login}@users.noreply.github.com`
491
+ };
492
+ }
493
+ /** `body` with a closing line saying the App generated the pull request. */
494
+ function withGithubAppFooter(body, bot) {
495
+ const footer = `Generated by [${bot.slug}](https://github.com/apps/${bot.slug}).`;
496
+ return body?.trim() ? `${body.trimEnd()}\n\n---\n\n${footer}` : footer;
497
+ }
498
+ export { isEveApprovalDisabled as _, GITHUB_ROLES as a, resolveEveToolApproval as b, buildEveToolDefinition as c, executeGithubEveTool as d, listEveToolDescriptors as f, hasGithubEveToolModelOutput as g, formatGithubEveToolOutput as h, withGithubAppFooter as i, buildEveToolMap as l, githubGuardrailViolation as m, githubAppBot as n, githubRoleRank as o, listResolvedEveToolNames as p, githubAppBotIdentity as r, withGithubCallerAccess as s, GITHUB_COMMIT_TOOLS as t, createEveGithubToolsDynamic as u, mapEveApprovalValue as v, MISSING_EVE_MESSAGE as x, resolveEveApproval as y };
312
499
 
313
- //# sourceMappingURL=eve-runtime-DPzMPCLt.mjs.map
500
+ //# sourceMappingURL=eve-runtime-DEdQqbCs.mjs.map