@github-tools/sdk 1.21.0 → 1.22.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.
- package/README.md +9 -9
- package/dist/{approval-policy-CEMMPq92.mjs → approval-policy-C2rcAY77.mjs} +3 -4
- package/dist/{approval-policy-CEMMPq92.mjs.map → approval-policy-C2rcAY77.mjs.map} +1 -1
- package/dist/connect/eve.d.mts +2 -4
- package/dist/connect/eve.d.mts.map +1 -1
- package/dist/connect/eve.mjs +3 -4
- package/dist/connect/eve.mjs.map +1 -1
- package/dist/connect.d.mts +3 -9
- package/dist/connect.d.mts.map +1 -1
- package/dist/connect.mjs +3 -4
- package/dist/{cores-meFAMt2D.mjs → cores-CMUr_SEv.mjs} +3 -4
- package/dist/{cores-meFAMt2D.mjs.map → cores-CMUr_SEv.mjs.map} +1 -1
- package/dist/{dry-run-DXckOam2.d.mts → dry-run-BAbes7Mv.d.mts} +2 -28
- package/dist/dry-run-BAbes7Mv.d.mts.map +1 -0
- package/dist/{evaluation-DJHINyAu.mjs → evaluation-DskA4Lzk.mjs} +4 -6
- package/dist/{evaluation-DJHINyAu.mjs.map → evaluation-DskA4Lzk.mjs.map} +1 -1
- package/dist/{eve-runtime-B_CJE9JV.d.mts → eve-runtime-Bmdw1C-K.d.mts} +43 -15
- package/dist/eve-runtime-Bmdw1C-K.d.mts.map +1 -0
- package/dist/{eve-runtime-DPzMPCLt.mjs → eve-runtime-DM9yjOsG.mjs} +158 -15
- package/dist/eve-runtime-DM9yjOsG.mjs.map +1 -0
- package/dist/eve-runtime.d.mts +5 -5
- package/dist/eve-runtime.mjs +4 -4
- package/dist/eve.d.mts +67 -69
- package/dist/eve.d.mts.map +1 -1
- package/dist/eve.mjs +67 -68
- package/dist/eve.mjs.map +1 -1
- package/dist/{index-CzzrtCVj.d.mts → index-DgCZi9Ns.d.mts} +23 -54
- package/dist/index-DgCZi9Ns.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +3 -3
- package/dist/{interrupts-BSDPwdJ2.d.mts → interrupts-MwQ_v_PF.d.mts} +1 -3
- package/dist/interrupts-MwQ_v_PF.d.mts.map +1 -0
- package/dist/rolldown-runtime-D8jQpDG7.mjs +12 -0
- package/dist/{src-BlhrSieS.mjs → src-Djn_FFj1.mjs} +21 -38
- package/dist/{src-BlhrSieS.mjs.map → src-Djn_FFj1.mjs.map} +1 -1
- package/dist/tanstack/interrupts.d.mts +1 -1
- package/dist/tanstack/interrupts.mjs +1 -2
- package/dist/tanstack.d.mts +3 -20
- package/dist/tanstack.d.mts.map +1 -1
- package/dist/tanstack.mjs +8 -13
- package/dist/tanstack.mjs.map +1 -1
- package/dist/{token-BLps09gm.mjs → token-HpJhSRkl.mjs} +6 -10
- package/dist/{token-BLps09gm.mjs.map → token-HpJhSRkl.mjs.map} +1 -1
- package/dist/{types-Bln8U42J.d.mts → types-8KtcPTao.d.mts} +3 -7
- package/dist/types-8KtcPTao.d.mts.map +1 -0
- package/dist/{types-C7O2lwwz.d.mts → types-C-BIKmas.d.mts} +2 -4
- package/dist/types-C-BIKmas.d.mts.map +1 -0
- package/dist/workflow.d.mts +2 -4
- package/dist/workflow.d.mts.map +1 -1
- package/dist/workflow.mjs +3 -4
- package/dist/{write-tools-w-8tjnDQ.mjs → write-tools-BR29EOoM.mjs} +51 -88
- package/dist/write-tools-BR29EOoM.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/dry-run-DXckOam2.d.mts.map +0 -1
- package/dist/eve-runtime-B_CJE9JV.d.mts.map +0 -1
- package/dist/eve-runtime-DPzMPCLt.mjs.map +0 -1
- package/dist/index-CzzrtCVj.d.mts.map +0 -1
- package/dist/interrupts-BSDPwdJ2.d.mts.map +0 -1
- package/dist/types-Bln8U42J.d.mts.map +0 -1
- package/dist/types-C7O2lwwz.d.mts.map +0 -1
- 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,OAAO;EAAE;EAAO,cAAc;CAAE;CAC5C,MAAM,YAAY,oBAAoB,KAAK;CAC3C,IAAI,UAAU,UAAU,sBAAsB,OAAO;EAAE,OAAO;EAAW,cAAc;CAAE;CACzF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4Lzk.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;EAAO,cAAc;CAAE;CAC5C,MAAM,YAAY,oBAAoB,KAAK;CAC3C,IAAI,UAAU,UAAU,sBAAsB,OAAO;EAAE,OAAO;EAAW,cAAc;CAAE;CACzF,OAAO;E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|
2
|
-
import {
|
|
3
|
-
import "./
|
|
1
|
+
import "./index-DgCZi9Ns.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
|
});
|
|
@@ -65,8 +62,6 @@ declare function listEveToolDescriptors(options?: EveGithubToolsOptions): {
|
|
|
65
62
|
* Used by `@github-tools/eve-extension` so `execute` only closes over a serializable tool name.
|
|
66
63
|
*/
|
|
67
64
|
declare function executeGithubEveTool(name: GithubToolName, input: Record<string, unknown>, options?: EveGithubToolsOptions): Promise<unknown>;
|
|
68
|
-
//#endregion
|
|
69
|
-
//#region src/eve/approval.d.ts
|
|
70
65
|
/**
|
|
71
66
|
* `false` / `'never'` should omit the tool `approval` field entirely.
|
|
72
67
|
* eve treats a missing `approval` like `never()`; attaching `never()` is
|
|
@@ -81,12 +76,46 @@ declare function resolveEveApproval(toolName: GithubWriteToolName, config: EveAp
|
|
|
81
76
|
* attach a redundant `never()` handler.
|
|
82
77
|
*/
|
|
83
78
|
declare function resolveEveToolApproval(toolName: GithubWriteToolName, config: EveApprovalConfig | undefined, override?: EveApprovalValue): Approval | undefined;
|
|
84
|
-
//#endregion
|
|
85
|
-
//#region src/eve/steps.d.ts
|
|
86
79
|
/** Why `guardrails` block a call once `context` defaults are applied, or `undefined` when they allow it. */
|
|
87
80
|
declare function githubGuardrailViolation(name: GithubToolName, input: Record<string, unknown>, { context, guardrails }: Pick<ToolBuildContext, 'context' | 'guardrails'>): string | undefined;
|
|
88
|
-
|
|
89
|
-
|
|
81
|
+
/** GitHub's repository roles, lowest first. */
|
|
82
|
+
declare const GITHUB_ROLES: readonly ["read", "triage", "write", "maintain", "admin"];
|
|
83
|
+
type GithubRole = typeof GITHUB_ROLES[number];
|
|
84
|
+
/**
|
|
85
|
+
* Rank of an answer from GitHub's collaborator permission endpoint in {@link GITHUB_ROLES}, or `-1`
|
|
86
|
+
* without access. A custom role ranks as the base permission GitHub reports for it.
|
|
87
|
+
*/
|
|
88
|
+
declare function githubRoleRank({ permission, roleName }: {
|
|
89
|
+
permission: string;
|
|
90
|
+
roleName?: string;
|
|
91
|
+
}): number;
|
|
92
|
+
type Repository = {
|
|
93
|
+
owner: string;
|
|
94
|
+
repo: string;
|
|
95
|
+
};
|
|
96
|
+
/** A person the tools act for with a token that isn't theirs, such as a GitHub App's. */
|
|
97
|
+
type GithubCaller = {
|
|
98
|
+
/** Their GitHub login. */
|
|
99
|
+
login: string;
|
|
100
|
+
/** The repository they asked from. A search runs only when its token reaches this repository and no other. */
|
|
101
|
+
repository?: Repository;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Wrap a token so every call it resolves for is first checked against what `caller` may do, read
|
|
105
|
+
* from GitHub with that same token. Use it when the tools run with a GitHub App's token for a person
|
|
106
|
+
* who can't get their own, such as someone commenting on GitHub: the App then does nothing that
|
|
107
|
+
* person couldn't. A refused call throws `github_tools.CALLER_FORBIDDEN` before it reaches GitHub.
|
|
108
|
+
*
|
|
109
|
+
* - A call on a repository needs the Read role there for a read and Write for a write, which is
|
|
110
|
+
* stricter than GitHub for the writes a reader can make, such as a comment. `addSubIssue` also
|
|
111
|
+
* needs Read on the sub-issue's repository.
|
|
112
|
+
* - `resolveReviewThread` needs Write on the repository the thread is in.
|
|
113
|
+
* - A search needs `caller.repository`, the Read role there, and a token that reaches that
|
|
114
|
+
* repository and no other, so it can't return results from one the caller can't see.
|
|
115
|
+
* - Every other call without a repository is refused, since no role on a repository covers it:
|
|
116
|
+
* gists, notifications, `createRepository` and `forkRepository`.
|
|
117
|
+
*/
|
|
118
|
+
declare function withGithubCallerAccess(token: GithubTokenInput | undefined, caller: GithubCaller): GithubTokenResolver;
|
|
90
119
|
/**
|
|
91
120
|
* @deprecated Never thrown since eve moved to static ESM imports — a missing
|
|
92
121
|
* `eve` package now fails at module resolution with the bundler/runtime's own
|
|
@@ -94,6 +123,5 @@ declare function githubGuardrailViolation(name: GithubToolName, input: Record<st
|
|
|
94
123
|
* match on it. Will be removed in the next major.
|
|
95
124
|
*/
|
|
96
125
|
declare const MISSING_EVE_MESSAGE = "The \"eve\" package is required to use @github-tools/sdk/eve. Install it with: pnpm add eve";
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
//# sourceMappingURL=eve-runtime-B_CJE9JV.d.mts.map
|
|
126
|
+
export { listResolvedEveToolNames as _, githubRoleRank as a, isEveApprovalDisabled as c, resolveEveToolApproval as d, buildEveToolDefinition as f, listEveToolDescriptors as g, executeGithubEveTool as h, GithubRole as i, mapEveApprovalValue as l, createEveGithubToolsDynamic as m, GITHUB_ROLES as n, withGithubCallerAccess as o, buildEveToolMap as p, GithubCaller as r, githubGuardrailViolation as s, MISSING_EVE_MESSAGE as t, resolveEveApproval as u, formatGithubEveToolOutput as v, hasGithubEveToolModelOutput as y };
|
|
127
|
+
//# sourceMappingURL=eve-runtime-Bmdw1C-K.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"eve-runtime-Bmdw1C-K.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/eve/load-eve.ts"],"mappings":";;;;;;KAuBY;EACV,OAAO;EACP,UAAU;EACV,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,aAAa;EACb;EACA,iBAAiB;;;iBA6CH,4BAA4B,MAAM;;;;;;;iBAUlC,0BAA0B,MAAM,gBAAgB,kBAAkB;KC7E7E,eAAe,yBAAyB;EAA0B,SAAS;;KAC3E,aAAa,QAAQ,OAAO,gBAAgB;iBA8CjC,uBACd,MAAM,gBACN,UAAS,eACR;iBAmCa,gBAAgB,UAAS,wBAA6B;iBAsCtD,4BAA4B,UAAS,4CAA0B,oCAAA,uCAAA;iBAQ/D,yBAAyB;EAAY;EAAoB;EAAqB;IAAwB;iBACtG,yBAAyB,UAAU,kBAAkB;EAAW,QAAQ;EAAG;EAAqB;IAAwB,eAAe;iBACvI,yBAAyB,mBAAmB,oBAAoB;EAAW,QAAQ;EAAG;EAAqB;IAAwB,wBAAwB;iBAC3J,yBAAyB,SAAS,KAAK,2DAA2D;;;;;iBAUlG,uBAAuB,UAAS;;;;E,WAAAA;;;;;;;iBA6B1B,qBACpB,MAAM,gBACN,OAAO,yBACP,UAAS,wBAA0B;;;;;;iBC/KrB,sBAAsB,OAAO;iBAI7B,oBAAoB,OAAO,mBAAmB;iBAY9C,mBACd,UAAU,qBACV,QAAQ,gCACP;;;;;;iBAgBa,uBACd,UAAU,qBACV,QAAQ,+BACR,WAAW,mBACV;;iBC3Ba,yBACd,MAAM,gBACN,OAAO,2BACL,SAAS,cAAc,KAAK;;cCjBnB;KAED,oBAAoB;;;;;iBAMhB,iBAAiB,YAAY;EAAc;EAAoB;;KAK1E;EAAe;EAAe;;;KAGvB;;EAEV;;EAEA,aAAa;;;;;;;;;;;;;;;;;iBAiFC,uBAAuB,OAAO,8BAA8B,QAAQ,eAAe;;;;;;;cC5FtF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { $a as stripRateLimit, E as isGithubWriteToolName, Qa 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-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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-BR29EOoM.mjs";
|
|
2
|
+
import { t as GITHUB_TOOL_CORES } from "./cores-CMUr_SEv.mjs";
|
|
3
|
+
import { _ as listPullRequestFilesToModelOutput, f as compareCommitsToModelOutput, g as getRepositoryTreeToModelOutput, h as getPullRequestContextToModelOutput, m as getFileContentToModelOutput, p as getCommitToModelOutput } from "./evaluation-DskA4Lzk.mjs";
|
|
4
4
|
import * as eveTools from "eve/tools";
|
|
5
5
|
import * as eveApproval from "eve/tools/approval";
|
|
6
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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),
|
|
@@ -151,8 +149,7 @@ function createToolRegistry(ctx, names = ALL_GITHUB_TOOL_NAMES) {
|
|
|
151
149
|
inputSchema: softenContextSchema(entry.inputSchema, ctx.context)
|
|
152
150
|
}));
|
|
153
151
|
}
|
|
154
|
-
|
|
155
|
-
//#region src/eve/steps.ts
|
|
152
|
+
// src/eve/steps.ts
|
|
156
153
|
async function executeGithubToolStep(name, input, ctx) {
|
|
157
154
|
"use step";
|
|
158
155
|
const [entry] = createToolRegistry(ctx, ALL_GITHUB_TOOL_NAMES.filter((tool) => tool === name));
|
|
@@ -179,8 +176,7 @@ async function runGithubToolStep(name, input, ctx) {
|
|
|
179
176
|
return { error: error instanceof Error ? error.message : String(error) };
|
|
180
177
|
}
|
|
181
178
|
}
|
|
182
|
-
|
|
183
|
-
//#region src/eve/build.ts
|
|
179
|
+
// src/eve/build.ts
|
|
184
180
|
function resolveAllowedToolNames(options) {
|
|
185
181
|
const presetAllowed = options.preset ? resolvePresetTools(options.preset) : null;
|
|
186
182
|
const includeAllowed = options.include ? new Set(options.include) : null;
|
|
@@ -307,7 +303,154 @@ async function executeGithubEveTool(name, input, options = {}) {
|
|
|
307
303
|
dryRunApproval: options.dryRunApproval
|
|
308
304
|
});
|
|
309
305
|
}
|
|
310
|
-
|
|
311
|
-
|
|
306
|
+
// src/core/caller-access.ts
|
|
307
|
+
/** GitHub's repository roles, lowest first. */
|
|
308
|
+
const GITHUB_ROLES = [
|
|
309
|
+
"read",
|
|
310
|
+
"triage",
|
|
311
|
+
"write",
|
|
312
|
+
"maintain",
|
|
313
|
+
"admin"
|
|
314
|
+
];
|
|
315
|
+
/**
|
|
316
|
+
* Rank of an answer from GitHub's collaborator permission endpoint in {@link GITHUB_ROLES}, or `-1`
|
|
317
|
+
* without access. A custom role ranks as the base permission GitHub reports for it.
|
|
318
|
+
*/
|
|
319
|
+
function githubRoleRank({ permission, roleName }) {
|
|
320
|
+
const role = GITHUB_ROLES.indexOf(roleName);
|
|
321
|
+
return role >= 0 ? role : GITHUB_ROLES.indexOf(permission);
|
|
322
|
+
}
|
|
323
|
+
const ROLE_TTL_MS = 6e4;
|
|
324
|
+
const MAX_CACHED_ROLES = 500;
|
|
325
|
+
const roles = /* @__PURE__ */ new Map();
|
|
326
|
+
function callerRank(resolve, login, { owner, repo }) {
|
|
327
|
+
const key = `${login}\n${owner}/${repo}`.toLowerCase();
|
|
328
|
+
const cached = roles.get(key);
|
|
329
|
+
if (cached && cached.expires > Date.now()) return cached.rank;
|
|
330
|
+
const input = {
|
|
331
|
+
owner,
|
|
332
|
+
repo,
|
|
333
|
+
username: login
|
|
334
|
+
};
|
|
335
|
+
const rank = resolve({
|
|
336
|
+
toolName: "getCollaboratorPermission",
|
|
337
|
+
input,
|
|
338
|
+
owner,
|
|
339
|
+
repo
|
|
340
|
+
}).then((token) => getCollaboratorPermissionCore({
|
|
341
|
+
token,
|
|
342
|
+
...input
|
|
343
|
+
})).then(githubRoleRank);
|
|
344
|
+
roles.set(key, {
|
|
345
|
+
expires: Date.now() + ROLE_TTL_MS,
|
|
346
|
+
rank
|
|
347
|
+
});
|
|
348
|
+
rank.catch(() => roles.delete(key));
|
|
349
|
+
if (roles.size > MAX_CACHED_ROLES) roles.delete(roles.keys().next().value);
|
|
350
|
+
return rank;
|
|
351
|
+
}
|
|
352
|
+
const refusal = (reason) => githubToolsErrors.CALLER_FORBIDDEN({ reason });
|
|
353
|
+
async function requireRole(resolve, login, toolName, repository, role) {
|
|
354
|
+
const rank = await callerRank(resolve, login, repository);
|
|
355
|
+
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.`);
|
|
356
|
+
}
|
|
357
|
+
const REVIEW_THREAD_REPOSITORY = `
|
|
358
|
+
query ReviewThreadRepository($threadId: ID!) {
|
|
359
|
+
node(id: $threadId) {
|
|
360
|
+
... on PullRequestReviewThread {
|
|
361
|
+
repository {
|
|
362
|
+
name
|
|
363
|
+
owner {
|
|
364
|
+
login
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
`;
|
|
371
|
+
async function reviewThreadRepository(token, threadId) {
|
|
372
|
+
const repository = (await createOctokit(token).graphql(REVIEW_THREAD_REPOSITORY, { threadId })).node?.repository;
|
|
373
|
+
return repository && {
|
|
374
|
+
owner: repository.owner.login,
|
|
375
|
+
repo: repository.name
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
async function reachesOnly(token, { owner, repo }) {
|
|
379
|
+
try {
|
|
380
|
+
const { data } = await createOctokit(token).rest.apps.listReposAccessibleToInstallation({ per_page: 2 });
|
|
381
|
+
return data.total_count === 1 && data.repositories[0]?.full_name.toLowerCase() === `${owner}/${repo}`.toLowerCase();
|
|
382
|
+
} catch (error) {
|
|
383
|
+
if (EvlogError.isEvlogError(error) && (error.status === 403 || error.status === 404)) return false;
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const SEARCH_TOOLS = /* @__PURE__ */ new Set([
|
|
388
|
+
"searchCode",
|
|
389
|
+
"searchIssues",
|
|
390
|
+
"searchRepositories"
|
|
391
|
+
]);
|
|
392
|
+
/**
|
|
393
|
+
* Wrap a token so every call it resolves for is first checked against what `caller` may do, read
|
|
394
|
+
* from GitHub with that same token. Use it when the tools run with a GitHub App's token for a person
|
|
395
|
+
* who can't get their own, such as someone commenting on GitHub: the App then does nothing that
|
|
396
|
+
* person couldn't. A refused call throws `github_tools.CALLER_FORBIDDEN` before it reaches GitHub.
|
|
397
|
+
*
|
|
398
|
+
* - A call on a repository needs the Read role there for a read and Write for a write, which is
|
|
399
|
+
* stricter than GitHub for the writes a reader can make, such as a comment. `addSubIssue` also
|
|
400
|
+
* needs Read on the sub-issue's repository.
|
|
401
|
+
* - `resolveReviewThread` needs Write on the repository the thread is in.
|
|
402
|
+
* - A search needs `caller.repository`, the Read role there, and a token that reaches that
|
|
403
|
+
* repository and no other, so it can't return results from one the caller can't see.
|
|
404
|
+
* - Every other call without a repository is refused, since no role on a repository covers it:
|
|
405
|
+
* gists, notifications, `createRepository` and `forkRepository`.
|
|
406
|
+
*/
|
|
407
|
+
function withGithubCallerAccess(token, caller) {
|
|
408
|
+
const resolve = createGithubTokenResolver(token);
|
|
409
|
+
const { login } = caller;
|
|
410
|
+
return async (call) => {
|
|
411
|
+
if (!call) throw new Error("`withGithubCallerAccess` needs the tool call to check the caller's access.");
|
|
412
|
+
const { toolName } = call;
|
|
413
|
+
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}.`);
|
|
414
|
+
if (call.owner && call.repo) {
|
|
415
|
+
const { owner } = call;
|
|
416
|
+
await requireRole(resolve, login, toolName, {
|
|
417
|
+
owner,
|
|
418
|
+
repo: call.repo
|
|
419
|
+
}, isGithubWriteToolName(toolName) ? "write" : "read");
|
|
420
|
+
const { subIssueRepo } = call.input;
|
|
421
|
+
if (toolName === "addSubIssue" && typeof subIssueRepo === "string") await requireRole(resolve, login, toolName, {
|
|
422
|
+
owner,
|
|
423
|
+
repo: subIssueRepo
|
|
424
|
+
}, "read");
|
|
425
|
+
return resolve(call);
|
|
426
|
+
}
|
|
427
|
+
if (toolName === "resolveReviewThread") {
|
|
428
|
+
const { threadId } = call.input;
|
|
429
|
+
const repository = await reviewThreadRepository(await resolve({
|
|
430
|
+
...call,
|
|
431
|
+
...caller.repository
|
|
432
|
+
}), threadId);
|
|
433
|
+
if (!repository) throw refusal(`The review thread can't be found, so ${login}'s role on its repository can't be checked.`);
|
|
434
|
+
await requireRole(resolve, login, toolName, repository, "write");
|
|
435
|
+
return resolve({
|
|
436
|
+
...call,
|
|
437
|
+
...repository
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
if (SEARCH_TOOLS.has(toolName) && caller.repository) {
|
|
441
|
+
const { owner, repo } = caller.repository;
|
|
442
|
+
await requireRole(resolve, login, toolName, caller.repository, "read");
|
|
443
|
+
const scoped = await resolve({
|
|
444
|
+
...call,
|
|
445
|
+
owner,
|
|
446
|
+
repo
|
|
447
|
+
});
|
|
448
|
+
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.`);
|
|
449
|
+
return scoped;
|
|
450
|
+
}
|
|
451
|
+
throw refusal(`\`${toolName}\` names no repository, so ${login}'s role can't be checked for it.`);
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
export { MISSING_EVE_MESSAGE as _, buildEveToolMap as a, listEveToolDescriptors as c, formatGithubEveToolOutput as d, hasGithubEveToolModelOutput as f, resolveEveToolApproval as g, resolveEveApproval as h, buildEveToolDefinition as i, listResolvedEveToolNames as l, mapEveApprovalValue as m, githubRoleRank as n, createEveGithubToolsDynamic as o, isEveApprovalDisabled as p, withGithubCallerAccess as r, executeGithubEveTool as s, GITHUB_ROLES as t, githubGuardrailViolation as u };
|
|
312
455
|
|
|
313
|
-
//# sourceMappingURL=eve-runtime-
|
|
456
|
+
//# sourceMappingURL=eve-runtime-DM9yjOsG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"eve-runtime-DM9yjOsG.mjs","names":[],"sources":["../src/eve/load-eve.ts","../src/eve/approval.ts","../src/eve/registry.ts","../src/eve/steps.ts","../src/eve/build.ts","../src/core/caller-access.ts"],"sourcesContent":["import * as eveTools from 'eve/tools'\nimport * as eveApproval from 'eve/tools/approval'\n\n/**\n * Static ESM imports so bundlers (eve/Nitro/Vercel) can resolve `eve` when it is\n * compiled into the output rather than left as `node_modules/eve` at runtime.\n * Runtime `createRequire(\"eve/tools\")` fails in those targets.\n */\nexport type EveToolsModule = typeof import('eve/tools')\nexport type EveApprovalModule = typeof import('eve/tools/approval')\n\n/**\n * @deprecated Never thrown since eve moved to static ESM imports — a missing\n * `eve` package now fails at module resolution with the bundler/runtime's own\n * error. Kept only for backward compatibility of the public export; do not\n * match on it. Will be removed in the next major.\n */\nexport const MISSING_EVE_MESSAGE =\n 'The \"eve\" package is required to use @github-tools/sdk/eve. Install it with: pnpm add eve'\n\nexport function getEveTools(): EveToolsModule {\n return eveTools\n}\n\nexport function getEveApprovalHelpers(): EveApprovalModule {\n return eveApproval\n}\n","import type { Approval, ApprovalPolicy } from 'eve/tools/approval'\nimport type { GithubWriteToolName } from '../core/write-tools'\nimport { getEveApprovalHelpers } from './load-eve'\nimport type { EveApprovalConfig, EveApprovalValue } from './types'\n\n/**\n * `false` / `'never'` should omit the tool `approval` field entirely.\n * eve treats a missing `approval` like `never()`; attaching `never()` is\n * redundant and has caused approval UI noise on some channels.\n */\nexport function isEveApprovalDisabled(value: EveApprovalValue | undefined): boolean {\n return value === false || value === 'never'\n}\n\nexport function mapEveApprovalValue(value: EveApprovalValue): ApprovalPolicy {\n if (typeof value === 'function') return value\n // Object-shaped eve `ApprovalConfiguration` — the request-time policy lives on `request`.\n if (typeof value === 'object') return value.request\n\n const { always, never, once } = getEveApprovalHelpers()\n\n if (value === true || value === 'always') return always()\n if (value === false || value === 'never') return never()\n return once()\n}\n\nexport function resolveEveApproval(\n toolName: GithubWriteToolName,\n config: EveApprovalConfig | undefined,\n): ApprovalPolicy {\n if (config === undefined) return getEveApprovalHelpers().always()\n if (config === true) return getEveApprovalHelpers().always()\n if (config === false) return getEveApprovalHelpers().never()\n\n const value = config[toolName]\n if (value === undefined) return getEveApprovalHelpers().always()\n\n return mapEveApprovalValue(value)\n}\n\n/**\n * Approval to attach on a write tool, or `undefined` to omit the field.\n * Prefer this when building `defineTool` values so `false` / `'never'` do not\n * attach a redundant `never()` handler.\n */\nexport function resolveEveToolApproval(\n toolName: GithubWriteToolName,\n config: EveApprovalConfig | undefined,\n override?: EveApprovalValue,\n): Approval | undefined {\n const value = override !== undefined\n ? override\n : typeof config === 'object' && config !== null\n ? config[toolName]\n : config\n\n if (value === undefined) return getEveApprovalHelpers().always()\n if (isEveApprovalDisabled(value)) return undefined\n // Pass policies and `ApprovalConfiguration` objects through unchanged so a\n // response-time authorizer (`response`) survives onto `defineTool`.\n if (typeof value === 'function' || typeof value === 'object') return value\n return mapEveApprovalValue(value)\n}\n","import type { ToolModelOutput } from 'eve/tools'\nimport type { z } from 'zod'\nimport type { CommitIdentity } from '../types'\nimport { GITHUB_TOOL_CATALOG, isGithubWriteToolName } from '../core/catalog'\nimport { GITHUB_TOOL_CORES } from '../core/cores'\nimport { mergeContextArgs, softenContextSchema, type GithubToolsContext } from '../core/context'\nimport {\n compareCommitsToModelOutput,\n getCommitToModelOutput,\n getFileContentToModelOutput,\n getPullRequestContextToModelOutput,\n getRepositoryTreeToModelOutput,\n listPullRequestFilesToModelOutput,\n} from '../core/model-output'\nimport { stripRateLimit } from '../core/rate-limit'\nimport { resolveGithubToken, type GithubTokenInput } from '../core/token'\nimport type { GithubGuardrails } from '../core/guardrails'\nimport type { GithubDryRunApproval } from '../core/dry-run'\nimport type { GithubWriteToolName } from '../core/write-tools'\nimport { ALL_GITHUB_TOOL_NAMES, type GithubToolName } from '../core/tool-names'\nexport type { GithubToolName } from '../core/tool-names'\nexport { ALL_GITHUB_TOOL_NAMES } from '../core/tool-names'\n\nexport type ToolBuildContext = {\n token: GithubTokenInput\n context?: GithubToolsContext\n author?: CommitIdentity\n committer?: CommitIdentity\n coAuthors?: CommitIdentity[]\n guardrails?: GithubGuardrails\n dryRun?: boolean\n dryRunApproval?: GithubDryRunApproval\n}\n\ntype ToolRegistryEntry = {\n name: GithubToolName\n writeTool?: GithubWriteToolName\n description: string\n inputSchema: z.ZodType\n execute: (args: Record<string, unknown>) => Promise<unknown>\n toModelOutput?: (output: unknown) => ToolModelOutput\n}\n\nfunction withToken<T extends Record<string, unknown>>(\n core: (args: T & { token: string }) => Promise<unknown>,\n ctx: ToolBuildContext,\n extra?: Record<string, unknown>,\n guard?: Record<string, unknown>,\n) {\n return async (input: Record<string, unknown>) =>\n core({\n token: await resolveGithubToken(ctx.token),\n ...extra,\n ...mergeContextArgs(input, ctx.context ?? {}),\n ...guard,\n } as T & { token: string })\n}\n\nfunction modelOutputAdapter(\n fn: (options: { toolCallId: string, input: unknown, output: unknown }) => { type: 'json' | 'text', value: unknown },\n) {\n return (output: unknown) => fn({ toolCallId: '', input: {}, output }) as ToolModelOutput\n}\n\nconst GITHUB_EVE_TOOL_MODEL_OUTPUT = {\n getFileContent: modelOutputAdapter(getFileContentToModelOutput),\n getRepositoryTree: modelOutputAdapter(getRepositoryTreeToModelOutput),\n listPullRequestFiles: modelOutputAdapter(listPullRequestFilesToModelOutput),\n getPullRequestContext: modelOutputAdapter(getPullRequestContextToModelOutput),\n getCommit: modelOutputAdapter(getCommitToModelOutput),\n compareCommits: modelOutputAdapter(compareCommitsToModelOutput),\n} satisfies Partial<Record<GithubToolName, (output: unknown) => ToolModelOutput>>\n\nconst EVE_TOOL_MODEL_OUTPUTS: Partial<Record<GithubToolName, (output: unknown) => ToolModelOutput>> = GITHUB_EVE_TOOL_MODEL_OUTPUT\n\n/** Whether a GitHub tool has a built-in eve `toModelOutput` projection. */\nexport function hasGithubEveToolModelOutput(name: GithubToolName): boolean {\n return Object.hasOwn(GITHUB_EVE_TOOL_MODEL_OUTPUT, name)\n}\n\n/**\n * Apply the built-in eve `toModelOutput` projection for a tool.\n * Strips `rateLimit` so it never reaches the model. Tools without a dedicated\n * formatter get `{ type: 'json', value }` of the remaining payload.\n * Used by `@github-tools/eve-extension` so the callback only closes over a serializable tool name.\n */\nexport function formatGithubEveToolOutput(name: GithubToolName, output: unknown): ToolModelOutput {\n const stripped = stripRateLimit(output)\n // `runGithubToolStep` returns `{ error }` when execute throws. The per-tool\n // formatters assume the success shape (e.g. `listPullRequestFilesToModelOutput`\n // calls `.map` on the payload), so dispatching an error payload would throw a\n // second time inside model-output formatting and re-break the tool loop.\n if (isErrorPayload(stripped)) {\n return { type: 'json', value: stripped }\n }\n const format = GITHUB_EVE_TOOL_MODEL_OUTPUT[name as keyof typeof GITHUB_EVE_TOOL_MODEL_OUTPUT]\n if (!format) {\n return { type: 'json', value: stripped }\n }\n return format(stripped)\n}\n\nfunction isErrorPayload(output: unknown): output is { error: string | Record<string, string> } {\n if (output == null || typeof output !== 'object' || Array.isArray(output)) return false\n const { error } = output as { error?: unknown }\n return typeof error === 'string' || (error != null && typeof error === 'object')\n}\n\nexport function createToolRegistry(\n ctx: ToolBuildContext,\n names: readonly GithubToolName[] = ALL_GITHUB_TOOL_NAMES,\n): ToolRegistryEntry[] {\n // Commit-identity options are session-level, not model inputs, so they ride\n // alongside the token instead of living in the tool's input schema.\n const commitExtras: Partial<Record<GithubToolName, Record<string, unknown>>> = {\n createOrUpdateFile: { author: ctx.author, committer: ctx.committer, coAuthors: ctx.coAuthors },\n editFiles: { author: ctx.author, committer: ctx.committer, coAuthors: ctx.coAuthors },\n mergePullRequest: { coAuthors: ctx.coAuthors },\n enablePullRequestAutoMerge: { coAuthors: ctx.coAuthors },\n }\n // Spread after the input, so the branches a merge or branch update may write can't come from the model.\n const branches = ctx.guardrails?.branches\n const guardExtras: Partial<Record<GithubToolName, Record<string, unknown>>> = {\n ...branches && { mergePullRequest: { branches }, enablePullRequestAutoMerge: { branches } },\n ...ctx.guardrails && { updatePullRequestBranch: { guardrails: ctx.guardrails } },\n }\n\n const entries = names.map((name): ToolRegistryEntry => {\n const descriptor = GITHUB_TOOL_CATALOG[name]\n // Argument types vary per tool; `withToken` re-narrows at the dispatch boundary.\n const core = GITHUB_TOOL_CORES[name] as (args: Record<string, unknown> & { token: string }) => Promise<unknown>\n const toModelOutput = EVE_TOOL_MODEL_OUTPUTS[name]\n return {\n name,\n ...(isGithubWriteToolName(name) && { writeTool: name }),\n description: descriptor.description,\n inputSchema: descriptor.inputSchema,\n execute: withToken(core, ctx, commitExtras[name], guardExtras[name]),\n ...(toModelOutput && { toModelOutput }),\n }\n })\n\n if (!ctx.context) return entries\n\n return entries.map(entry => ({\n ...entry,\n inputSchema: softenContextSchema(entry.inputSchema, ctx.context!),\n }))\n}\n","import { mergeContextArgs } from '../core/context'\nimport { EvlogError, githubToolsErrors, toModelErrorPayload } from '../core/errors'\nimport { guardrailViolation } from '../core/guardrails'\nimport { dryRunWrite } from '../core/dry-run'\nimport { isGithubWriteToolName } from '../core/catalog'\nimport { githubTokenCall, resolveGithubToken } from '../core/token'\nimport { ALL_GITHUB_TOOL_NAMES, createToolRegistry, type GithubToolName, type ToolBuildContext } from './registry'\n\nasync function executeGithubToolStep(\n name: GithubToolName,\n input: Record<string, unknown>,\n ctx: ToolBuildContext,\n) {\n 'use step'\n const [entry] = createToolRegistry(ctx, ALL_GITHUB_TOOL_NAMES.filter(tool => tool === name))\n if (!entry) {\n throw new Error(`Unknown GitHub tool: ${name}`)\n }\n return entry.execute(input)\n}\n\n/** Why `guardrails` block a call once `context` defaults are applied, or `undefined` when they allow it. */\nexport function githubGuardrailViolation(\n name: GithubToolName,\n input: Record<string, unknown>,\n { context, guardrails }: Pick<ToolBuildContext, 'context' | 'guardrails'>,\n) {\n return guardrailViolation(githubTokenCall(name, mergeContextArgs(input, context ?? {})), guardrails)\n}\n\nexport async function runGithubToolStep(\n name: GithubToolName,\n input: Record<string, unknown>,\n ctx: ToolBuildContext,\n) {\n try {\n // Resolve the token before entering the step so only a serializable string crosses the boundary.\n const call = githubTokenCall(name, mergeContextArgs(input, ctx.context ?? {}))\n const reason = guardrailViolation(call, ctx.guardrails)\n if (reason) throw githubToolsErrors.GUARDRAIL_BLOCKED({ reason })\n if (ctx.dryRun && isGithubWriteToolName(name)) return dryRunWrite(name, call.input as Record<string, unknown>, ctx.guardrails, () => ctx.dryRunApproval)\n const token = await resolveGithubToken(ctx.token, call)\n return await executeGithubToolStep(name, input, { ...ctx, token })\n } catch (error) {\n // Eve's tool-loop logs thrown execute errors but does not always append a\n // tool_result. Returning a payload keeps the Anthropic tool_use/tool_result pairing intact.\n // Catalog errors keep their { code, why, fix, link } structure so the model can recover.\n if (EvlogError.isEvlogError(error)) {\n return { error: toModelErrorPayload(error) }\n }\n return { error: error instanceof Error ? error.message : String(error) }\n }\n}\n","import type { ToolDefinition } from 'eve/tools'\nimport { resolvePresetTools, type CombinedPresetToolNames, type GithubToolPreset, type PresetToolName } from '../core/presets'\nimport { createGithubTokenResolver } from '../core/token'\nimport { isEveApprovalDisabled, mapEveApprovalValue, resolveEveToolApproval } from './approval'\nimport { getEveTools } from './load-eve'\nimport { ALL_GITHUB_TOOL_NAMES, createToolRegistry, formatGithubEveToolOutput, hasGithubEveToolModelOutput, type GithubToolName, type ToolBuildContext } from './registry'\nimport { runGithubToolStep } from './steps'\nimport type { EveGithubToolsOptions, EveToolFactoryOptions, EveToolOverrides } from './types'\n\ntype BuildOptions = EveGithubToolsOptions | (EveToolFactoryOptions & { preset?: EveGithubToolsOptions['preset'] })\ntype EveToolMap = Partial<Record<GithubToolName, ToolDefinition>>\n\nfunction resolveAllowedToolNames(\n options: Pick<EveGithubToolsOptions, 'preset' | 'include' | 'exclude'>,\n): (name: GithubToolName) => boolean {\n const presetAllowed = options.preset ? resolvePresetTools(options.preset) : null\n const includeAllowed = options.include ? new Set(options.include) : null\n const excluded = options.exclude ? new Set(options.exclude) : null\n\n // `preset` and `include` compose as a union (add tools a preset is missing);\n // `exclude` always subtracts from that combined set afterward.\n const allowed = presetAllowed && includeAllowed\n ? new Set([...presetAllowed, ...includeAllowed])\n : presetAllowed ?? includeAllowed\n\n return name => (!allowed || allowed.has(name)) && !excluded?.has(name)\n}\n\nfunction applyOverrides<T extends ToolDefinition>(\n tool: T,\n name: GithubToolName,\n overrides?: EveToolOverrides,\n): T {\n const override = overrides?.[name]\n if (!override) return tool\n\n const next: T = {\n ...tool,\n ...override.description !== undefined && { description: override.description },\n ...override.toModelOutput !== undefined && { toModelOutput: override.toModelOutput },\n ...override.outputSchema !== undefined && { outputSchema: override.outputSchema },\n }\n\n if (override.approval === undefined) return next\n if (isEveApprovalDisabled(override.approval)) {\n const rest = { ...next }\n delete (rest as { approval?: unknown }).approval\n return rest\n }\n // Preserve policies and `ApprovalConfiguration` objects as-is; only literals need mapping.\n const approval = typeof override.approval === 'function' || typeof override.approval === 'object'\n ? override.approval\n : mapEveApprovalValue(override.approval)\n return { ...next, approval }\n}\n\nexport function buildEveToolDefinition(\n name: GithubToolName,\n options: BuildOptions = {},\n): ToolDefinition {\n const { defineTool } = getEveTools()\n const ctx: ToolBuildContext = {\n token: createGithubTokenResolver(options.token),\n context: options.context,\n author: options.author,\n committer: options.committer,\n coAuthors: options.coAuthors,\n guardrails: options.guardrails,\n dryRun: options.dryRun,\n dryRunApproval: options.dryRunApproval,\n }\n\n const [entry] = createToolRegistry(ctx, ALL_GITHUB_TOOL_NAMES.filter(tool => tool === name))\n if (!entry) {\n throw new Error(`Unknown GitHub tool: ${name}`)\n }\n\n const approval = entry.writeTool\n ? resolveEveToolApproval(entry.writeTool, options.requireApproval)\n : undefined\n\n // Annotated so defineTool resolves to its ToolDefinition overload — inference\n // from the bare literal picks the background-tool overload on eve 0.45+.\n const definition: ToolDefinition = {\n description: entry.description,\n inputSchema: entry.inputSchema,\n ...(approval && { approval }),\n toModelOutput: (output: unknown) => formatGithubEveToolOutput(name, output),\n execute: async (input) => runGithubToolStep(name, input as Record<string, unknown>, ctx),\n }\n\n return applyOverrides(defineTool(definition), name, options.overrides)\n}\n\nexport function buildEveToolMap(options: EveGithubToolsOptions = {}): EveToolMap {\n const { defineTool } = getEveTools()\n const ctx: ToolBuildContext = {\n token: createGithubTokenResolver(options.token),\n context: options.context,\n author: options.author,\n committer: options.committer,\n coAuthors: options.coAuthors,\n guardrails: options.guardrails,\n dryRun: options.dryRun,\n dryRunApproval: options.dryRunApproval,\n }\n\n const isAllowed = resolveAllowedToolNames(options)\n const registry = createToolRegistry(ctx)\n const tools = {} as EveToolMap\n\n for (const entry of registry) {\n if (!isAllowed(entry.name)) continue\n\n const approval = entry.writeTool\n ? resolveEveToolApproval(entry.writeTool, options.requireApproval)\n : undefined\n\n const definition: ToolDefinition = {\n description: entry.description,\n inputSchema: entry.inputSchema,\n ...(approval && { approval }),\n toModelOutput: (output: unknown) => formatGithubEveToolOutput(entry.name, output),\n execute: async (input) => runGithubToolStep(entry.name, input as Record<string, unknown>, ctx),\n }\n\n tools[entry.name] = applyOverrides(defineTool(definition), entry.name, options.overrides)\n }\n\n return tools\n}\n\nexport function createEveGithubToolsDynamic(options: EveGithubToolsOptions = {}) {\n const { defineDynamic } = getEveTools()\n\n // TODO(eve-auth): resolve token from ctx.getToken('github') when eve-managed auth lands.\n // Deferred — eve does not yet expose managed GitHub tokens on the session context.\n return defineDynamic(() => buildEveToolMap(options))\n}\n\nexport function listResolvedEveToolNames(options?: { preset?: undefined, include?: undefined, exclude?: undefined }): GithubToolName[]\nexport function listResolvedEveToolNames<P extends GithubToolPreset>(options: { preset: P, include?: undefined, exclude?: undefined }): PresetToolName<P>[]\nexport function listResolvedEveToolNames<P extends readonly GithubToolPreset[]>(options: { preset: P, include?: undefined, exclude?: undefined }): CombinedPresetToolNames<P>[]\nexport function listResolvedEveToolNames(options: Pick<EveGithubToolsOptions, 'preset' | 'include' | 'exclude'>): GithubToolName[]\nexport function listResolvedEveToolNames(options: Pick<EveGithubToolsOptions, 'preset' | 'include' | 'exclude'> = {}): GithubToolName[] {\n const isAllowed = resolveAllowedToolNames(options)\n return ALL_GITHUB_TOOL_NAMES.filter(isAllowed)\n}\n\n/**\n * Tool descriptors (no `execute`) for authored eve `defineTool` loops.\n * Prefer this when registering tools outside the SDK package so durable transforms can hoist inline execute.\n */\nexport function listEveToolDescriptors(options: EveGithubToolsOptions = {}) {\n const ctx: ToolBuildContext = {\n token: createGithubTokenResolver(options.token),\n context: options.context,\n author: options.author,\n committer: options.committer,\n coAuthors: options.coAuthors,\n guardrails: options.guardrails,\n dryRun: options.dryRun,\n dryRunApproval: options.dryRunApproval,\n }\n\n const names = listResolvedEveToolNames(options)\n return createToolRegistry(ctx, names)\n .map(entry => ({\n name: entry.name,\n description: entry.description,\n inputSchema: entry.inputSchema,\n writeTool: entry.writeTool,\n toModelOutput: entry.toModelOutput,\n }))\n}\n\nexport { formatGithubEveToolOutput, hasGithubEveToolModelOutput }\n\n/**\n * Execute a GitHub tool by name with the given eve options (token/context/attribution).\n * Used by `@github-tools/eve-extension` so `execute` only closes over a serializable tool name.\n */\nexport async function executeGithubEveTool(\n name: GithubToolName,\n input: Record<string, unknown>,\n options: EveGithubToolsOptions = {},\n) {\n const ctx: ToolBuildContext = {\n token: createGithubTokenResolver(options.token),\n context: options.context,\n author: options.author,\n committer: options.committer,\n coAuthors: options.coAuthors,\n guardrails: options.guardrails,\n dryRun: options.dryRun,\n dryRunApproval: options.dryRunApproval,\n }\n return runGithubToolStep(name, input, ctx)\n}\n","import { createOctokit } from '../client'\nimport { isGithubWriteToolName } from './catalog'\nimport { EvlogError, githubToolsErrors } from './errors'\nimport { getCollaboratorPermissionCore } from './repository'\nimport { createGithubTokenResolver, type GithubTokenInput, type GithubTokenResolver } from './token'\nimport type { GithubToolName } from './tool-names'\n\n/** GitHub's repository roles, lowest first. */\nexport const GITHUB_ROLES = ['read', 'triage', 'write', 'maintain', 'admin'] as const\n\nexport type GithubRole = typeof GITHUB_ROLES[number]\n\n/**\n * Rank of an answer from GitHub's collaborator permission endpoint in {@link GITHUB_ROLES}, or `-1`\n * without access. A custom role ranks as the base permission GitHub reports for it.\n */\nexport function githubRoleRank({ permission, roleName }: { permission: string, roleName?: string }): number {\n const role = GITHUB_ROLES.indexOf(roleName as GithubRole)\n return role >= 0 ? role : GITHUB_ROLES.indexOf(permission as GithubRole)\n}\n\ntype Repository = { owner: string, repo: string }\n\n/** A person the tools act for with a token that isn't theirs, such as a GitHub App's. */\nexport type GithubCaller = {\n /** Their GitHub login. */\n login: string\n /** The repository they asked from. A search runs only when its token reaches this repository and no other. */\n repository?: Repository\n}\n\n// A role is read on every call, so an agent turn would otherwise ask GitHub the same question many times.\nconst ROLE_TTL_MS = 60_000\nconst MAX_CACHED_ROLES = 500\nconst roles = new Map<string, { expires: number, rank: Promise<number> }>()\n\nfunction callerRank(resolve: GithubTokenResolver, login: string, { owner, repo }: Repository): Promise<number> {\n const key = `${login}\\n${owner}/${repo}`.toLowerCase()\n const cached = roles.get(key)\n if (cached && cached.expires > Date.now()) return cached.rank\n const input = { owner, repo, username: login }\n const rank = resolve({ toolName: 'getCollaboratorPermission', input, owner, repo })\n .then(token => getCollaboratorPermissionCore({ token, ...input }))\n .then(githubRoleRank)\n roles.set(key, { expires: Date.now() + ROLE_TTL_MS, rank })\n rank.catch(() => roles.delete(key))\n if (roles.size > MAX_CACHED_ROLES) roles.delete(roles.keys().next().value!)\n return rank\n}\n\nconst refusal = (reason: string) => githubToolsErrors.CALLER_FORBIDDEN({ reason })\n\nasync function requireRole(resolve: GithubTokenResolver, login: string, toolName: GithubToolName, repository: Repository, role: GithubRole) {\n const rank = await callerRank(resolve, login, repository)\n if (rank < GITHUB_ROLES.indexOf(role)) {\n throw refusal(`${login} has ${rank < 0 ? 'no' : GITHUB_ROLES[rank]} access to ${repository.owner}/${repository.repo}, and \\`${toolName}\\` needs ${role} access.`)\n }\n}\n\nconst REVIEW_THREAD_REPOSITORY = /* GraphQL */ `\n query ReviewThreadRepository($threadId: ID!) {\n node(id: $threadId) {\n ... on PullRequestReviewThread {\n repository {\n name\n owner {\n login\n }\n }\n }\n }\n }\n`\n\nasync function reviewThreadRepository(token: string, threadId: unknown): Promise<Repository | undefined> {\n const data = await createOctokit(token).graphql<{ node: { repository?: { name: string, owner: { login: string } } } | null }>(REVIEW_THREAD_REPOSITORY, { threadId })\n const repository = data.node?.repository\n return repository && { owner: repository.owner.login, repo: repository.name }\n}\n\n// A search has no target to check a role on, so it may only run with a token that sees one repository.\n// Only an installation token can list what it reaches: GitHub answers 403 or 404 to any other.\nasync function reachesOnly(token: string, { owner, repo }: Repository): Promise<boolean> {\n try {\n const { data } = await createOctokit(token).rest.apps.listReposAccessibleToInstallation({ per_page: 2 })\n return data.total_count === 1 && data.repositories[0]?.full_name.toLowerCase() === `${owner}/${repo}`.toLowerCase()\n } catch (error) {\n if (EvlogError.isEvlogError(error) && (error.status === 403 || error.status === 404)) return false\n throw error\n }\n}\n\nconst SEARCH_TOOLS: ReadonlySet<GithubToolName> = new Set(['searchCode', 'searchIssues', 'searchRepositories'])\n\n/**\n * Wrap a token so every call it resolves for is first checked against what `caller` may do, read\n * from GitHub with that same token. Use it when the tools run with a GitHub App's token for a person\n * who can't get their own, such as someone commenting on GitHub: the App then does nothing that\n * person couldn't. A refused call throws `github_tools.CALLER_FORBIDDEN` before it reaches GitHub.\n *\n * - A call on a repository needs the Read role there for a read and Write for a write, which is\n * stricter than GitHub for the writes a reader can make, such as a comment. `addSubIssue` also\n * needs Read on the sub-issue's repository.\n * - `resolveReviewThread` needs Write on the repository the thread is in.\n * - A search needs `caller.repository`, the Read role there, and a token that reaches that\n * repository and no other, so it can't return results from one the caller can't see.\n * - Every other call without a repository is refused, since no role on a repository covers it:\n * gists, notifications, `createRepository` and `forkRepository`.\n */\nexport function withGithubCallerAccess(token: GithubTokenInput | undefined, caller: GithubCaller): GithubTokenResolver {\n const resolve = createGithubTokenResolver(token)\n const { login } = caller\n return async (call) => {\n if (!call) throw new Error('`withGithubCallerAccess` needs the tool call to check the caller\\'s access.')\n const { toolName } = call\n if (toolName === 'createRepository' || toolName === 'forkRepository') {\n throw refusal(`\\`${toolName}\\` creates a repository, which no role on a repository allows, so it can't run for ${login}.`)\n }\n if (call.owner && call.repo) {\n const { owner } = call\n await requireRole(resolve, login, toolName, { owner, repo: call.repo }, isGithubWriteToolName(toolName) ? 'write' : 'read')\n const { subIssueRepo } = call.input as Record<string, unknown>\n if (toolName === 'addSubIssue' && typeof subIssueRepo === 'string') await requireRole(resolve, login, toolName, { owner, repo: subIssueRepo }, 'read')\n return resolve(call)\n }\n if (toolName === 'resolveReviewThread') {\n const { threadId } = call.input as Record<string, unknown>\n const repository = await reviewThreadRepository(await resolve({ ...call, ...caller.repository }), threadId)\n if (!repository) throw refusal(`The review thread can't be found, so ${login}'s role on its repository can't be checked.`)\n await requireRole(resolve, login, toolName, repository, 'write')\n return resolve({ ...call, ...repository })\n }\n if (SEARCH_TOOLS.has(toolName) && caller.repository) {\n const { owner, repo } = caller.repository\n await requireRole(resolve, login, toolName, caller.repository, 'read')\n const scoped = await resolve({ ...call, owner, repo })\n if (!await reachesOnly(scoped, caller.repository)) {\n 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.`)\n }\n return scoped\n }\n throw refusal(`\\`${toolName}\\` names no repository, so ${login}'s role can't be checked for it.`)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,sBACX;AAEF,SAAgB,cAA8B;CAC5C,OAAO;AACT;AAEA,SAAgB,wBAA2C;CACzD,OAAO;AACT;;;;;;;AChBA,SAAgB,sBAAsB,OAA8C;CAClF,OAAO,UAAU,SAAS,UAAU;AACtC;AAEA,SAAgB,oBAAoB,OAAyC;CAC3E,IAAI,OAAO,UA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AAM,YAAY,SAAS,OAAO,UAAU;IAAE;IAAO,MAAM;GAAa,GAAG,MAAM;GACrJ,OAAO,QAAQ,IAAI;EACrB;EACA,IAAI,aAAa,uBAAuB;GACtC,MAAM,EAAE,aAAa,KAAK;GAC1B,MAAM,aAAa,MAAM,uBAAuB,MAAM,QAAQ;IAAE,GAAG;IAAM,GAAG,OAAO;GAAW,CAAC,GAAG,QAAQ;GAC1G,IAAI,CAAC,YAAY,MAAM,QAAQ,wCAAwC,MAAM,4CAA4C;GACzH,MAAM,YAAY,SAAS,OAAO,UAAU,YAAY,OAAO;GAC/D,OAAO,QAAQ;IAAE,GAAG;IAAM,GAAG;GAAW,CAAC;EAC3C;EACA,IAAI,aAAa,IAAI,QAAQ,KAAK,OAAO,YAAY;GACnD,MAAM,EAAE,OAAO,SAAS,OAAO;GAC/B,MAAM,YAAY,SAAS,OAAO,UAAU,OAAO,YAAY,MAAM;GACrE,MAAM,SAAS,MAAM,QAAQ;IAAE,GAAG;IAAM;IAAO;GAAK,CAAC;GACrD,IAAI,CAAC,MAAM,YAAY,QAAQ,OAAO,UAAU,GAC9C,MAAM,QAAQ,KAAK,SAAS,uEAAuE,MAAM,GAAG,KAAK,QAAQ,MAAM,yCAAyC;GAE1K,OAAO;EACT;EACA,MAAM,QAAQ,KAAK,SAAS,6BAA6B,MAAM,iCAAiC;CAClG;AACF"}
|
package/dist/eve-runtime.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as
|
|
2
|
-
import { a as EveToolOverrides, i as EveToolFactoryOptions, n as EveApprovalValue, r as EveGithubToolsOptions, t as EveApprovalConfig } from "./types-
|
|
3
|
-
import { $t as resolveToolGuidance, a as GithubRateLimit, i as githubToolsErrors } from "./index-
|
|
4
|
-
import { a as
|
|
5
|
-
export { AUTO_APPROVAL_TOOLS, type AllGithubTools, type AutoApprovalDecision, type CombinedPresetToolNames, type CommitIdentity, type EveApprovalConfig, type EveApprovalValue, type EveGithubToolsOptions, type EveToolFactoryOptions, type EveToolOverrides, GITHUB_TOOL_NAMES, GITHUB_WRITE_TOOLS, type GithubDryRunApproval, type GithubDryRunResult, type GithubEvaluationOptions, type GithubGuardrails, type GithubRateLimit, type GithubTokenCall, type GithubToolName, type GithubToolPreset, type GithubToolsForPreset, type GithubWriteToolName, MISSING_EVE_MESSAGE, PRESET_TOOLS, type PickGithubTools, type PresetToolName, autoApprovalDecision, buildEveToolDefinition, buildEveToolMap, createEveGithubToolsDynamic, evaluatePresets, evaluateTools, executeGithubEveTool, fallbackPresets, fallbackTools, formatGithubEveToolOutput, githubGuardrailViolation, githubToolsErrors, hasGithubEveToolModelOutput, isEveApprovalDisabled, latestUserText, listEveToolDescriptors, listResolvedEveToolNames, mapEveApprovalValue, needsAutoApproval, resolveEveApproval, resolveEveToolApproval, resolveGithubToken, resolveToolGuidance, selectPresets, selectTools };
|
|
1
|
+
import { B as GithubToolPreset, C as fallbackTools, D as selectTools, E as selectPresets, F as resolveGithubToken, G as GithubToolName, H as PresetToolName, K as GithubWriteToolName, L as GithubGuardrails, M as GithubTokenCall, O as GITHUB_WRITE_TOOLS, S as fallbackPresets, T as needsAutoApproval, U as GITHUB_TOOL_NAMES, V as PRESET_TOOLS, _ as AutoApprovalDecision, a as GithubToolsForPreset, b as evaluatePresets, c as CommitIdentity, k as AUTO_APPROVAL_TOOLS, n as GithubDryRunResult, o as PickGithubTools, r as AllGithubTools, t as GithubDryRunApproval, v as GithubEvaluationOptions, w as latestUserText, x as evaluateTools, y as autoApprovalDecision, z as CombinedPresetToolNames } from "./dry-run-BAbes7Mv.mjs";
|
|
2
|
+
import { a as EveToolOverrides, i as EveToolFactoryOptions, n as EveApprovalValue, r as EveGithubToolsOptions, t as EveApprovalConfig } from "./types-C-BIKmas.mjs";
|
|
3
|
+
import { $t as resolveToolGuidance, a as GithubRateLimit, i as githubToolsErrors } from "./index-DgCZi9Ns.mjs";
|
|
4
|
+
import { _ as listResolvedEveToolNames, a as githubRoleRank, c as isEveApprovalDisabled, d as resolveEveToolApproval, f as buildEveToolDefinition, g as listEveToolDescriptors, h as executeGithubEveTool, i as GithubRole, l as mapEveApprovalValue, m as createEveGithubToolsDynamic, n as GITHUB_ROLES, o as withGithubCallerAccess, p as buildEveToolMap, r as GithubCaller, s as githubGuardrailViolation, t as MISSING_EVE_MESSAGE, u as resolveEveApproval, v as formatGithubEveToolOutput, y as hasGithubEveToolModelOutput } from "./eve-runtime-Bmdw1C-K.mjs";
|
|
5
|
+
export { AUTO_APPROVAL_TOOLS, type AllGithubTools, type AutoApprovalDecision, type CombinedPresetToolNames, type CommitIdentity, type EveApprovalConfig, type EveApprovalValue, type EveGithubToolsOptions, type EveToolFactoryOptions, type EveToolOverrides, GITHUB_ROLES, GITHUB_TOOL_NAMES, GITHUB_WRITE_TOOLS, type GithubCaller, type GithubDryRunApproval, type GithubDryRunResult, type GithubEvaluationOptions, type GithubGuardrails, type GithubRateLimit, type GithubRole, type GithubTokenCall, type GithubToolName, type GithubToolPreset, type GithubToolsForPreset, type GithubWriteToolName, MISSING_EVE_MESSAGE, PRESET_TOOLS, type PickGithubTools, type PresetToolName, autoApprovalDecision, buildEveToolDefinition, buildEveToolMap, createEveGithubToolsDynamic, evaluatePresets, evaluateTools, executeGithubEveTool, fallbackPresets, fallbackTools, formatGithubEveToolOutput, githubGuardrailViolation, githubRoleRank, githubToolsErrors, hasGithubEveToolModelOutput, isEveApprovalDisabled, latestUserText, listEveToolDescriptors, listResolvedEveToolNames, mapEveApprovalValue, needsAutoApproval, resolveEveApproval, resolveEveToolApproval, resolveGithubToken, resolveToolGuidance, selectPresets, selectTools, withGithubCallerAccess };
|
package/dist/eve-runtime.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as resolveGithubToken, Za as githubToolsErrors, c as AUTO_APPROVAL_TOOLS, g as GITHUB_TOOL_NAMES, r as resolveToolGuidance, t as GITHUB_WRITE_TOOLS, v as PRESET_TOOLS } from "./write-tools-
|
|
2
|
-
import { c as latestUserText, d as selectTools, i as evaluateTools, l as needsAutoApproval, n as autoApprovalDecision, o as fallbackPresets, r as evaluatePresets, s as fallbackTools, u as selectPresets } from "./evaluation-
|
|
3
|
-
import { a as
|
|
4
|
-
export { AUTO_APPROVAL_TOOLS, GITHUB_TOOL_NAMES, GITHUB_WRITE_TOOLS, MISSING_EVE_MESSAGE, PRESET_TOOLS, autoApprovalDecision, buildEveToolDefinition, buildEveToolMap, createEveGithubToolsDynamic, evaluatePresets, evaluateTools, executeGithubEveTool, fallbackPresets, fallbackTools, formatGithubEveToolOutput, githubGuardrailViolation, githubToolsErrors, hasGithubEveToolModelOutput, isEveApprovalDisabled, latestUserText, listEveToolDescriptors, listResolvedEveToolNames, mapEveApprovalValue, needsAutoApproval, resolveEveApproval, resolveEveToolApproval, resolveGithubToken, resolveToolGuidance, selectPresets, selectTools };
|
|
1
|
+
import { S as resolveGithubToken, Za as githubToolsErrors, c as AUTO_APPROVAL_TOOLS, g as GITHUB_TOOL_NAMES, r as resolveToolGuidance, t as GITHUB_WRITE_TOOLS, v as PRESET_TOOLS } from "./write-tools-BR29EOoM.mjs";
|
|
2
|
+
import { c as latestUserText, d as selectTools, i as evaluateTools, l as needsAutoApproval, n as autoApprovalDecision, o as fallbackPresets, r as evaluatePresets, s as fallbackTools, u as selectPresets } from "./evaluation-DskA4Lzk.mjs";
|
|
3
|
+
import { _ as MISSING_EVE_MESSAGE, a as buildEveToolMap, c as listEveToolDescriptors, d as formatGithubEveToolOutput, f as hasGithubEveToolModelOutput, g as resolveEveToolApproval, h as resolveEveApproval, i as buildEveToolDefinition, l as listResolvedEveToolNames, m as mapEveApprovalValue, n as githubRoleRank, o as createEveGithubToolsDynamic, p as isEveApprovalDisabled, r as withGithubCallerAccess, s as executeGithubEveTool, t as GITHUB_ROLES, u as githubGuardrailViolation } from "./eve-runtime-DM9yjOsG.mjs";
|
|
4
|
+
export { AUTO_APPROVAL_TOOLS, GITHUB_ROLES, GITHUB_TOOL_NAMES, GITHUB_WRITE_TOOLS, MISSING_EVE_MESSAGE, PRESET_TOOLS, autoApprovalDecision, buildEveToolDefinition, buildEveToolMap, createEveGithubToolsDynamic, evaluatePresets, evaluateTools, executeGithubEveTool, fallbackPresets, fallbackTools, formatGithubEveToolOutput, githubGuardrailViolation, githubRoleRank, githubToolsErrors, hasGithubEveToolModelOutput, isEveApprovalDisabled, latestUserText, listEveToolDescriptors, listResolvedEveToolNames, mapEveApprovalValue, needsAutoApproval, resolveEveApproval, resolveEveToolApproval, resolveGithubToken, resolveToolGuidance, selectPresets, selectTools, withGithubCallerAccess };
|