@gitkraken/core-gitlens 0.28.0 → 0.30.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/CHANGELOG.md +48 -1
- package/dist/git/cache.d.ts +39 -1
- package/dist/git/cache.js +108 -7
- package/dist/git/cache.js.map +1 -1
- package/dist/git/providers/branches.d.ts +17 -12
- package/dist/git/providers/revision.d.ts +4 -0
- package/dist/git/watching/worktreeSummary.d.ts +16 -7
- package/dist/git/watching/worktreeSummary.js +44 -14
- package/dist/git/watching/worktreeSummary.js.map +1 -1
- package/dist/git-cli/cliGitProvider.js +3 -3
- package/dist/git-cli/cliGitProvider.js.map +1 -1
- package/dist/git-cli/exec/exec.d.ts +2 -2
- package/dist/git-cli/exec/exec.js +2 -2
- package/dist/git-cli/exec/gitDirResolver.d.ts +6 -1
- package/dist/git-cli/exec/gitDirResolver.js +9 -4
- package/dist/git-cli/exec/gitDirResolver.js.map +1 -1
- package/dist/git-cli/providers/branches.d.ts +91 -13
- package/dist/git-cli/providers/branches.js +673 -176
- package/dist/git-cli/providers/branches.js.map +1 -1
- package/dist/git-cli/providers/config.js +1 -1
- package/dist/git-cli/providers/config.js.map +1 -1
- package/dist/git-cli/providers/revision.d.ts +4 -0
- package/dist/git-cli/providers/revision.js +64 -3
- package/dist/git-cli/providers/revision.js.map +1 -1
- package/dist/ipc/ipcServer.d.ts +6 -1
- package/dist/ipc/ipcServer.js +15 -6
- package/dist/ipc/ipcServer.js.map +1 -1
- package/dist/plus/ai/errors.js +4 -4
- package/dist/plus/ai/errors.js.map +1 -1
- package/dist/plus/ai/models/model.d.ts +1 -1
- package/dist/plus/ai/models/model.js.map +1 -1
- package/dist/plus/ai/models/promptTemplates.d.ts +45 -2
- package/dist/plus/ai/models/results.d.ts +41 -0
- package/dist/plus/ai/models/results.js +14 -0
- package/dist/plus/ai/models/results.js.map +1 -0
- package/dist/plus/ai/prompts.d.ts +6 -0
- package/dist/plus/ai/prompts.js +255 -5
- package/dist/plus/ai/prompts.js.map +1 -1
- package/dist/plus/ai/providers/gitkrakenProvider.js +2 -2
- package/dist/plus/ai/providers/gitkrakenProvider.js.map +1 -1
- package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -0
- package/dist/plus/ai/providers/openAICompatibleProviderBase.js.map +1 -1
- package/dist/plus/ai/utils/ai.utils.d.ts +4 -0
- package/dist/plus/ai/utils/ai.utils.js +8 -1
- package/dist/plus/ai/utils/ai.utils.js.map +1 -1
- package/dist/plus/ai/utils/results.utils.d.ts +15 -1
- package/dist/plus/ai/utils/results.utils.js +80 -4
- package/dist/plus/ai/utils/results.utils.js.map +1 -1
- package/dist/plus/integrations/authentication/integrationAuthenticationService.js +2 -0
- package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
- package/dist/plus/integrations/authentication/models.d.ts +1 -1
- package/dist/plus/integrations/authentication/models.js +2 -0
- package/dist/plus/integrations/authentication/models.js.map +1 -1
- package/dist/plus/integrations/constants.d.ts +2 -1
- package/dist/plus/integrations/constants.js +12 -2
- package/dist/plus/integrations/constants.js.map +1 -1
- package/dist/plus/integrations/fieldPresence.js +17 -1
- package/dist/plus/integrations/fieldPresence.js.map +1 -1
- package/dist/plus/integrations/integrationService.d.ts +1 -1
- package/dist/plus/integrations/integrationService.js +8 -2
- package/dist/plus/integrations/integrationService.js.map +1 -1
- package/dist/plus/integrations/lite.js +5 -6
- package/dist/plus/integrations/lite.js.map +1 -1
- package/dist/plus/integrations/models/gitHostIntegration.d.ts +11 -1
- package/dist/plus/integrations/models/gitHostIntegration.js.map +1 -1
- package/dist/plus/integrations/providers/asana.d.ts +91 -0
- package/dist/plus/integrations/providers/asana.js +344 -0
- package/dist/plus/integrations/providers/asana.js.map +1 -0
- package/dist/plus/integrations/providers/azure/azure.js +3 -2
- package/dist/plus/integrations/providers/azure/azure.js.map +1 -1
- package/dist/plus/integrations/providers/azure/models.js +3 -2
- package/dist/plus/integrations/providers/azure/models.js.map +1 -1
- package/dist/plus/integrations/providers/azureDevOps.d.ts +7 -1
- package/dist/plus/integrations/providers/azureDevOps.js +9 -1
- package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
- package/dist/plus/integrations/providers/bitbucket-server/discovery.js +2 -1
- package/dist/plus/integrations/providers/bitbucket-server/discovery.js.map +1 -1
- package/dist/plus/integrations/providers/bitbucket-server/models.js.map +1 -1
- package/dist/plus/integrations/providers/github.d.ts +2 -2
- package/dist/plus/integrations/providers/github.js +2 -2
- package/dist/plus/integrations/providers/github.js.map +1 -1
- package/dist/plus/integrations/providers/issueSorts.d.ts +5 -0
- package/dist/plus/integrations/providers/issueSorts.js +6 -1
- package/dist/plus/integrations/providers/issueSorts.js.map +1 -1
- package/dist/plus/integrations/providers/jiraIssueByKey.js +2 -1
- package/dist/plus/integrations/providers/jiraIssueByKey.js.map +1 -1
- package/dist/plus/integrations/providers/models.d.ts +19 -3
- package/dist/plus/integrations/providers/models.js +12 -1
- package/dist/plus/integrations/providers/models.js.map +1 -1
- package/dist/plus/integrations/providers/providerApiClient.d.ts +0 -3
- package/dist/plus/integrations/providers/providerApiClient.js +1 -3
- package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
- package/dist/plus/integrations/providers/providersApi.d.ts +22 -1
- package/dist/plus/integrations/providers/providersApi.js +63 -12
- package/dist/plus/integrations/providers/providersApi.js.map +1 -1
- package/dist/plus/integrations/providers/utils.d.ts +1 -0
- package/dist/plus/integrations/providers/utils.js +8 -2
- package/dist/plus/integrations/providers/utils.js.map +1 -1
- package/dist/plus/integrations/reads/hierarchy.utils.d.ts +3 -3
- package/dist/plus/integrations/reads/hierarchy.utils.js +4 -4
- package/dist/plus/integrations/reads/hierarchy.utils.js.map +1 -1
- package/dist/plus/integrations/reads/resolveRepository.js +29 -21
- package/dist/plus/integrations/reads/resolveRepository.js.map +1 -1
- package/dist/plus/integrations/results.d.ts +18 -10
- package/dist/plus/integrations/results.js.map +1 -1
- package/dist/plus/integrations/utils/domain.utils.js +2 -1
- package/dist/plus/integrations/utils/domain.utils.js.map +1 -1
- package/dist/plus/integrations/utils/integration.utils.js +5 -13
- package/dist/plus/integrations/utils/integration.utils.js.map +1 -1
- package/dist/utils/diff.d.ts +19 -0
- package/dist/utils/diff.js +121 -3
- package/dist/utils/diff.js.map +1 -1
- package/dist/utils/env/node/exec.d.ts +0 -1
- package/dist/utils/env/node/exec.js +2 -14
- package/dist/utils/env/node/exec.js.map +1 -1
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +7 -1
- package/dist/utils/path.js.map +1 -1
- package/docs/integrations.md +72 -43
- package/package.json +2 -2
|
@@ -3,7 +3,7 @@ import { trace } from "../../../utils/decorators/log.js";
|
|
|
3
3
|
import __decorate from "../../../_virtual/@oxc-project+runtime/helpers/esm/decorate.js";
|
|
4
4
|
import { gitKrakenProviderDescriptor } from "../constants.js";
|
|
5
5
|
import { AIError, AuthenticationRequiredError } from "../errors.js";
|
|
6
|
-
import { getReducedMaxInputTokens } from "../utils/ai.utils.js";
|
|
6
|
+
import { getBackendActionType, getReducedMaxInputTokens } from "../utils/ai.utils.js";
|
|
7
7
|
import { OpenAICompatibleProviderBase } from "./openAICompatibleProviderBase.js";
|
|
8
8
|
//#region ../plus/ai/src/providers/gitkrakenProvider.ts
|
|
9
9
|
/** Opt-out flag the models endpoint reports in `disabledAttributes` for models whose upstream
|
|
@@ -67,7 +67,7 @@ var GitKrakenProvider = class extends OpenAICompatibleProviderBase {
|
|
|
67
67
|
return {
|
|
68
68
|
Accept: "application/json",
|
|
69
69
|
Authorization: `Bearer ${apiKey}`,
|
|
70
|
-
"GK-Action": action,
|
|
70
|
+
"GK-Action": getBackendActionType(action),
|
|
71
71
|
...conversationId ? { "GK-Conversation-ID": conversationId } : {}
|
|
72
72
|
};
|
|
73
73
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gitkrakenProvider.js","names":["provider"],"sources":["../../../../../plus/ai/src/providers/gitkrakenProvider.ts"],"sourcesContent":["import { trace } from '@gitlens/utils/decorators/log.js';\nimport { getScopedLogger } from '@gitlens/utils/logger.scoped.js';\nimport { gitKrakenProviderDescriptor as provider } from '../constants.js';\nimport { AIError, AIErrorReason, AuthenticationRequiredError } from '../errors.js';\nimport type { AIActionType, AIModel } from '../models/model.js';\nimport { getReducedMaxInputTokens } from '../utils/ai.utils.js';\nimport { OpenAICompatibleProviderBase } from './openAICompatibleProviderBase.js';\n\ntype GitKrakenModel = AIModel<typeof provider.id>;\n\n/** Opt-out flag the models endpoint reports in `disabledAttributes` for models whose upstream\n * translation doesn't cover native structured outputs */\nconst structuredOutputAttribute = 'structured_output';\n\nexport class GitKrakenProvider extends OpenAICompatibleProviderBase<typeof provider.id> {\n\treadonly id = provider.id;\n\treadonly name = provider.name;\n\treadonly supportsTools = true;\n\tprotected readonly descriptor = provider;\n\tprotected readonly config = {};\n\n\toverride async getApiKey(silent: boolean): Promise<string | undefined> {\n\t\treturn this.context.getApiKey(\n\t\t\t{\n\t\t\t\tid: this.id,\n\t\t\t\tname: this.name,\n\t\t\t\trequiresAccount: this.descriptor.requiresAccount,\n\t\t\t\tvalidator: () => true,\n\t\t\t},\n\t\t\tsilent,\n\t\t);\n\t}\n\n\t@trace()\n\tasync getModels(): Promise<readonly AIModel<typeof provider.id>[]> {\n\t\tconst scope = getScopedLogger();\n\n\t\ttry {\n\t\t\tconst rsp = await this.context.fetch('providers/message-prompt', {\n\t\t\t\theaders: { Accept: 'application/json' },\n\t\t\t});\n\t\t\tif (!rsp.ok) {\n\t\t\t\tthrow new Error(`Getting models failed: ${rsp.status} (${rsp.statusText})`);\n\t\t\t}\n\n\t\t\tinterface ModelsResponse {\n\t\t\t\tdata: {\n\t\t\t\t\tproviderId: string;\n\t\t\t\t\tproviderName: string;\n\t\t\t\t\tmodelId: string;\n\t\t\t\t\tmodelName: string;\n\t\t\t\t\tpreferred: boolean;\n\t\t\t\t\tmaxInputTokens: number;\n\t\t\t\t\tmaxOutputTokens: number;\n\t\t\t\t\tdisabledAttributes?: string[];\n\t\t\t\t\tconsumptionRateLabel?: string;\n\t\t\t\t}[];\n\t\t\t\terror?: null;\n\t\t\t}\n\n\t\t\tconst result = (await rsp.json()) as ModelsResponse;\n\t\t\tif (result.error != null) {\n\t\t\t\tthrow new Error(`Getting models failed: ${String(result.error)}`);\n\t\t\t}\n\n\t\t\tconst models = result.data.map<GitKrakenModel>(\n\t\t\t\tm =>\n\t\t\t\t\t({\n\t\t\t\t\t\tid: m.modelId,\n\t\t\t\t\t\tname: m.modelName,\n\t\t\t\t\t\tmaxTokens: { input: m.maxInputTokens, output: m.maxOutputTokens },\n\t\t\t\t\t\tprovider: provider,\n\t\t\t\t\t\tdefault: m.preferred,\n\t\t\t\t\t\ttemperature: null,\n\t\t\t\t\t\tconsumptionRateLabel: m.consumptionRateLabel,\n\t\t\t\t\t\t// The backend owns the per-upstream `response_format` translation, so it's the\n\t\t\t\t\t\t// authority on which models it covers. A schema an upstream's converter still\n\t\t\t\t\t\t// rejects is recovered per-request via isResponseFormatRejection below\n\t\t\t\t\t\tsupportsStructuredOutputs: !m.disabledAttributes?.includes(structuredOutputAttribute),\n\t\t\t\t\t}) satisfies GitKrakenModel,\n\t\t\t);\n\t\t\treturn models;\n\t\t} catch (ex) {\n\t\t\tif (!(ex instanceof AuthenticationRequiredError)) {\n\t\t\t\tdebugger;\n\t\t\t\tscope?.error(ex, `Unable to get models`);\n\t\t\t}\n\t\t}\n\n\t\treturn [];\n\t}\n\n\tprotected getUrl(_model: AIModel<typeof provider.id>): string {\n\t\treturn 'chat/completions';\n\t}\n\n\tprotected override isToolsRejection(status: number, message: string | undefined): boolean {\n\t\tif (super.isToolsRejection(status, message)) return true;\n\t\tif (message == null) return false;\n\n\t\t// The backend forwards an upstream refusal as its own envelope carrying only \"upstream AI provider\n\t\t// error (<provider> HTTP 400)\", naming neither \"tool\" nor \"function\" — so the base's text match can\n\t\t// never fire here. Treat any wrapped upstream 400 as a candidate and let the retry decide: `tools`\n\t\t// is the only field a tool-using request sends that a plain completion doesn't, the probe costs one\n\t\t// request, and the caller latches the rejection only when dropping tools actually fixes it. A\n\t\t// misread therefore self-corrects — the same bargain `isResponseFormatRejection` below makes.\n\t\treturn getWrappedUpstreamStatus(message) === 400;\n\t}\n\n\tprotected override isResponseFormatRejection(status: number, body: string): boolean {\n\t\tif (super.isResponseFormatRejection(status, body)) return true;\n\n\t\t// The backend wraps upstream schema rejections in its own envelope, carrying only the upstream\n\t\t// status (e.g. its Gemini schema converter mangles null-union types → Gemini 400s). Match on the\n\t\t// wrapper, NOT the envelope code — that varies by backend (500.1 on prod, 400.1 seen on staging),\n\t\t// and keying off it means the probe silently stops firing. A non-schema upstream 400 also matches,\n\t\t// which is fine: the strip-and-resend probe is cheap and rejection is only memoized when the\n\t\t// resend succeeds, so misclassification self-corrects.\n\t\treturn getWrappedUpstreamStatus(body) === 400;\n\t}\n\n\tprotected override getHeaders<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tapiKey: string,\n\t\t_model: AIModel<typeof provider.id>,\n\t\t_url: string,\n\t\tconversationId?: string,\n\t): Record<string, string> {\n\t\treturn {\n\t\t\tAccept: 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t'GK-Action': action,\n\t\t\t// Scopes the backend's once-per-conversation feature fee — without it every request in a\n\t\t\t// multi-call session (e.g. conflict resolution) is charged the full flat fee.\n\t\t\t...(conversationId ? { 'GK-Conversation-ID': conversationId } : {}),\n\t\t};\n\t}\n\n\tprotected override async handleFetchFailure<TAction extends AIActionType>(\n\t\trsp: Response,\n\t\t_action: TAction,\n\t\t_model: AIModel<typeof provider.id>,\n\t\tretries: number,\n\t\tmaxInputTokens: number,\n\t\tbody?: string,\n\t\tsentTools?: boolean,\n\t): Promise<{ retry: true; maxInputTokens: number; withoutTools?: boolean }> {\n\t\ttype ErrorResponse = {\n\t\t\terror?: { code: string; message: string; data?: any };\n\t\t};\n\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = (body != null ? JSON.parse(body) : await rsp.json()) as ErrorResponse | undefined;\n\t\t} catch {}\n\n\t\t// The backend's own prose says only \"upstream AI provider error (<provider> HTTP <status>)\" and\n\t\t// puts the provider's actual complaint in `data`. Dropping it (as every branch but the\n\t\t// entitlement one did) leaves nothing naming a cause, so a request the upstream rejected is\n\t\t// indistinguishable from any other 400 — and the only way to find out is to guess.\n\t\tlet message = json?.error?.message || rsp.statusText;\n\t\tconst detail = formatErrorData(json?.error?.data);\n\t\tif (detail != null) {\n\t\t\tmessage += `; ${detail}`;\n\t\t}\n\n\t\tlet status: string | number;\n\t\tlet code: string | number;\n\t\t[status, code] = json?.error?.code?.split('.') ?? [];\n\n\t\tstatus = status ? parseInt(status, 10) : rsp.status;\n\t\tcode = code ? parseInt(code, 10) : 0;\n\n\t\t// Classify a wrapped upstream failure by the status it carries, not by the envelope's own code:\n\t\t// prod reports these as 500.1, but staging has been seen using 400.1, and keying off the outer\n\t\t// code means an upstream rate limit arrives as a bare Error with no reason — so no \"Switch\n\t\t// Model\" action and no retry, just an opaque message.\n\t\tconst upstreamStatus = getWrappedUpstreamStatus(message);\n\t\tif (upstreamStatus != null) {\n\t\t\tconst wrapped = new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tswitch (upstreamStatus) {\n\t\t\t\tcase 429:\n\t\t\t\t\tthrow new AIError(AIErrorReason.RateLimitExceeded, wrapped);\n\t\t\t\tcase 413:\n\t\t\t\t\tthrow new AIError(AIErrorReason.RequestTooLarge, wrapped);\n\t\t\t\tcase 401:\n\t\t\t\tcase 403:\n\t\t\t\t\tthrow new AIError(AIErrorReason.Unauthorized, wrapped);\n\t\t\t\t// Anything else is the upstream refusing the request itself. There's nothing to recover\n\t\t\t\t// automatically, so fall through and surface it with the detail folded in above.\n\t\t\t}\n\t\t}\n\n\t\t// Recover a tools rejection BEFORE the switch below. This override owns the 400 case and throws,\n\t\t// so it never reaches `super.handleFetchFailure` — which is the only place the base's\n\t\t// retry-without-tools fallback lives, leaving it unreachable for this provider.\n\t\tif (sentTools && this.isToolsRejection(status, message)) {\n\t\t\treturn { retry: true, maxInputTokens: maxInputTokens, withoutTools: true };\n\t\t}\n\n\t\tswitch (status) {\n\t\t\tcase 400: // Bad Request\n\t\t\t\t// CodeValidation = \"400.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 401:\n\t\t\t\t// CodeAuthentication = \"401.1\"\n\t\t\t\tthrow new AuthenticationRequiredError();\n\t\t\tcase 403:\n\t\t\t\t// CodeAuthorization = \"403.1\"\n\t\t\t\t// CodeEntitlement = \"403.2\"\n\t\t\t\t// CodeFeatureDisabled = \"403.3\"\n\n\t\t\t\t// Entitlement Error\n\t\t\t\tif (code === 2) {\n\t\t\t\t\ttype EntitlementErrorData = {\n\t\t\t\t\t\tentitlementId?: string;\n\t\t\t\t\t\tentitlementValue?: string | number;\n\t\t\t\t\t\tcurrentValue?: string | number;\n\t\t\t\t\t};\n\n\t\t\t\t\tconst data = json?.error?.data as EntitlementErrorData;\n\t\t\t\t\tconst entitlementId = data?.entitlementId;\n\t\t\t\t\tif (entitlementId != null) {\n\t\t\t\t\t\tmessage += `; entitlement=${data.entitlementId} ${JSON.stringify(data)}`;\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\t// If there is an `entitlementValue` then we are over the limit, otherwise it is an entitlement error\n\t\t\t\t\t\tdata?.entitlementValue ? AIErrorReason.UserQuotaExceeded : AIErrorReason.NoEntitlement,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (code === 3) {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.DeniedByOrganization,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new AIError(\n\t\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t);\n\t\t\tcase 404:\n\t\t\t\t// CodeNotFound = \"404.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 408:\n\t\t\t\t// CodeTimeout = \"408.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 413:\n\t\t\t\t// CodeRequestTooLarge = \"413.1\"\n\n\t\t\t\t// Request too large\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tif (retries < 3) {\n\t\t\t\t\t\treturn { retry: true, maxInputTokens: getReducedMaxInputTokens(maxInputTokens, retries + 1) };\n\t\t\t\t\t}\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RequestTooLarge,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 429:\n\t\t\t\t// CodeTooManyRequests = \"429.1\"\n\n\t\t\t\t// Too many requests\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RateLimitExceeded,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 499:\n\t\t\t\t// CodeRequestCanceled = \"499.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 500: {\n\t\t\t\t// CodeServerError = \"500.1\"\n\t\t\t\t// Wrapped upstream failures are classified above, before this switch — the backend has\n\t\t\t\t// used more than one envelope code for them, so that can't key off `status`.\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\t}\n\t\t\tcase 503:\n\t\t\t\t// CodeServiceUnavailable = \"503.1\"\n\n\t\t\t\t// Service unavailable\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tif (message === 'Agent Error: too many requests') {\n\t\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\t\tAIErrorReason.ServiceCapacityExceeded,\n\t\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t}\n\t}\n}\n\n/** Max characters of `error.data` folded into a message — enough to name a cause, bounded so a large\n * payload can't dominate a notification or a log line. */\nconst maxErrorDetailLength = 500;\n\n/**\n * Renders the backend's `error.data` as a short detail string. This is where the upstream provider's\n * own complaint arrives, so it's the difference between \"upstream AI provider error (OpenAI HTTP 400)\"\n * and knowing which field it rejected.\n *\n * Strings pass through; objects are JSON-encoded. A common shape is the upstream's own error envelope,\n * so a nested `message` is preferred when present rather than dumping the whole object.\n */\nfunction formatErrorData(data: unknown): string | undefined {\n\tif (data == null) return undefined;\n\n\tlet text: string | undefined;\n\tif (typeof data === 'string') {\n\t\ttext = data;\n\t} else if (typeof data === 'object') {\n\t\tconst nested =\n\t\t\t(data as { error?: { message?: unknown }; message?: unknown }).error?.message ??\n\t\t\t(data as { message?: unknown }).message;\n\t\tif (typeof nested === 'string' && nested) {\n\t\t\ttext = nested;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\ttext = JSON.stringify(data);\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t} else if (typeof data === 'number' || typeof data === 'boolean') {\n\t\ttext = String(data);\n\t}\n\n\ttext = text?.trim();\n\tif (!text || text === '{}' || text === 'null') return undefined;\n\n\treturn text.length > maxErrorDetailLength ? `${text.slice(0, maxErrorDetailLength)}…` : text;\n}\n\n/** Extracts the upstream HTTP status from the backend's upstream-error prose wrapper. The envelope code\n * varies (500.1 on prod, 400.1 seen on staging), so callers must key off this, not the outer code. */\nfunction getWrappedUpstreamStatus(text: string): number | undefined {\n\tconst status = /upstream ai provider error[\\s\\S]*?http (\\d{3})/i.exec(text)?.[1];\n\treturn status != null ? parseInt(status, 10) : undefined;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,4BAA4B;AAElC,IAAa,oBAAb,cAAuC,6BAAiD;CACvF,KAAcA,4BAAS;CACvB,OAAgBA,4BAAS;CACzB,gBAAyB;CACzB,aAAgCA;CAChC,SAA4B,CAAC;CAE7B,MAAe,UAAU,QAA8C;EACtE,OAAO,KAAK,QAAQ,UACnB;GACC,IAAI,KAAK;GACT,MAAM,KAAK;GACX,iBAAiB,KAAK,WAAW;GACjC,iBAAiB;EAClB,GACA,MACD;CACD;CAEA,MACM,YAA6D;EAClE,MAAM,QAAQ,gBAAgB;EAE9B,IAAI;GACH,MAAM,MAAM,MAAM,KAAK,QAAQ,MAAM,4BAA4B,EAChE,SAAS,EAAE,QAAQ,mBAAmB,EACvC,CAAC;GACD,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,MAAM,0BAA0B,IAAI,OAAO,IAAI,IAAI,WAAW,EAAE;GAkB3E,MAAM,SAAU,MAAM,IAAI,KAAK;GAC/B,IAAI,OAAO,SAAS,MACnB,MAAM,IAAI,MAAM,0BAA0B,OAAO,OAAO,KAAK,GAAG;GAmBjE,OAhBe,OAAO,KAAK,KAC1B,OACE;IACA,IAAI,EAAE;IACN,MAAM,EAAE;IACR,WAAW;KAAE,OAAO,EAAE;KAAgB,QAAQ,EAAE;IAAgB;IAChE,UAAUA;IACV,SAAS,EAAE;IACX,aAAa;IACb,sBAAsB,EAAE;IAIxB,2BAA2B,CAAC,EAAE,oBAAoB,SAAS,yBAAyB;GACrF,EAEU;EACb,SAAS,IAAI;GACZ,IAAI,EAAE,cAAc,8BAA8B;IACjD;IACA,OAAO,MAAM,IAA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EACD;CAEF,OAAO,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,WACtD,OAAO,OAAO,IAAI;CAGnB,OAAO,MAAM,KAAK;CAClB,IAAI,CAAC,QAAQ,SAAS,QAAQ,SAAS,QAAQ,OAAO,KAAA;CAEtD,OAAO,KAAK,SAAS,uBAAuB,GAAG,KAAK,MAAM,GAAG,oBAAoB,EAAE,KAAK;AACzF;;;AAIA,SAAS,yBAAyB,MAAkC;CACnE,MAAM,SAAS,kDAAkD,KAAK,IAAI,CAAC,GAAG;CAC9E,OAAO,UAAU,OAAO,SAAS,QAAQ,EAAE,IAAI,KAAA;AAChD"}
|
|
1
|
+
{"version":3,"file":"gitkrakenProvider.js","names":["provider"],"sources":["../../../../../plus/ai/src/providers/gitkrakenProvider.ts"],"sourcesContent":["import { trace } from '@gitlens/utils/decorators/log.js';\nimport { getScopedLogger } from '@gitlens/utils/logger.scoped.js';\nimport { gitKrakenProviderDescriptor as provider } from '../constants.js';\nimport { AIError, AIErrorReason, AuthenticationRequiredError } from '../errors.js';\nimport type { AIActionType, AIModel } from '../models/model.js';\nimport { getBackendActionType, getReducedMaxInputTokens } from '../utils/ai.utils.js';\nimport { OpenAICompatibleProviderBase } from './openAICompatibleProviderBase.js';\n\ntype GitKrakenModel = AIModel<typeof provider.id>;\n\n/** Opt-out flag the models endpoint reports in `disabledAttributes` for models whose upstream\n * translation doesn't cover native structured outputs */\nconst structuredOutputAttribute = 'structured_output';\n\nexport class GitKrakenProvider extends OpenAICompatibleProviderBase<typeof provider.id> {\n\treadonly id = provider.id;\n\treadonly name = provider.name;\n\treadonly supportsTools = true;\n\tprotected readonly descriptor = provider;\n\tprotected readonly config = {};\n\n\toverride async getApiKey(silent: boolean): Promise<string | undefined> {\n\t\treturn this.context.getApiKey(\n\t\t\t{\n\t\t\t\tid: this.id,\n\t\t\t\tname: this.name,\n\t\t\t\trequiresAccount: this.descriptor.requiresAccount,\n\t\t\t\tvalidator: () => true,\n\t\t\t},\n\t\t\tsilent,\n\t\t);\n\t}\n\n\t@trace()\n\tasync getModels(): Promise<readonly AIModel<typeof provider.id>[]> {\n\t\tconst scope = getScopedLogger();\n\n\t\ttry {\n\t\t\tconst rsp = await this.context.fetch('providers/message-prompt', {\n\t\t\t\theaders: { Accept: 'application/json' },\n\t\t\t});\n\t\t\tif (!rsp.ok) {\n\t\t\t\tthrow new Error(`Getting models failed: ${rsp.status} (${rsp.statusText})`);\n\t\t\t}\n\n\t\t\tinterface ModelsResponse {\n\t\t\t\tdata: {\n\t\t\t\t\tproviderId: string;\n\t\t\t\t\tproviderName: string;\n\t\t\t\t\tmodelId: string;\n\t\t\t\t\tmodelName: string;\n\t\t\t\t\tpreferred: boolean;\n\t\t\t\t\tmaxInputTokens: number;\n\t\t\t\t\tmaxOutputTokens: number;\n\t\t\t\t\tdisabledAttributes?: string[];\n\t\t\t\t\tconsumptionRateLabel?: string;\n\t\t\t\t}[];\n\t\t\t\terror?: null;\n\t\t\t}\n\n\t\t\tconst result = (await rsp.json()) as ModelsResponse;\n\t\t\tif (result.error != null) {\n\t\t\t\tthrow new Error(`Getting models failed: ${String(result.error)}`);\n\t\t\t}\n\n\t\t\tconst models = result.data.map<GitKrakenModel>(\n\t\t\t\tm =>\n\t\t\t\t\t({\n\t\t\t\t\t\tid: m.modelId,\n\t\t\t\t\t\tname: m.modelName,\n\t\t\t\t\t\tmaxTokens: { input: m.maxInputTokens, output: m.maxOutputTokens },\n\t\t\t\t\t\tprovider: provider,\n\t\t\t\t\t\tdefault: m.preferred,\n\t\t\t\t\t\ttemperature: null,\n\t\t\t\t\t\tconsumptionRateLabel: m.consumptionRateLabel,\n\t\t\t\t\t\t// The backend owns the per-upstream `response_format` translation, so it's the\n\t\t\t\t\t\t// authority on which models it covers. A schema an upstream's converter still\n\t\t\t\t\t\t// rejects is recovered per-request via isResponseFormatRejection below\n\t\t\t\t\t\tsupportsStructuredOutputs: !m.disabledAttributes?.includes(structuredOutputAttribute),\n\t\t\t\t\t}) satisfies GitKrakenModel,\n\t\t\t);\n\t\t\treturn models;\n\t\t} catch (ex) {\n\t\t\tif (!(ex instanceof AuthenticationRequiredError)) {\n\t\t\t\tdebugger;\n\t\t\t\tscope?.error(ex, `Unable to get models`);\n\t\t\t}\n\t\t}\n\n\t\treturn [];\n\t}\n\n\tprotected getUrl(_model: AIModel<typeof provider.id>): string {\n\t\treturn 'chat/completions';\n\t}\n\n\tprotected override isToolsRejection(status: number, message: string | undefined): boolean {\n\t\tif (super.isToolsRejection(status, message)) return true;\n\t\tif (message == null) return false;\n\n\t\t// The backend forwards an upstream refusal as its own envelope carrying only \"upstream AI provider\n\t\t// error (<provider> HTTP 400)\", naming neither \"tool\" nor \"function\" — so the base's text match can\n\t\t// never fire here. Treat any wrapped upstream 400 as a candidate and let the retry decide: `tools`\n\t\t// is the only field a tool-using request sends that a plain completion doesn't, the probe costs one\n\t\t// request, and the caller latches the rejection only when dropping tools actually fixes it. A\n\t\t// misread therefore self-corrects — the same bargain `isResponseFormatRejection` below makes.\n\t\treturn getWrappedUpstreamStatus(message) === 400;\n\t}\n\n\tprotected override isResponseFormatRejection(status: number, body: string): boolean {\n\t\tif (super.isResponseFormatRejection(status, body)) return true;\n\n\t\t// The backend wraps upstream schema rejections in its own envelope, carrying only the upstream\n\t\t// status (e.g. its Gemini schema converter mangles null-union types → Gemini 400s). Match on the\n\t\t// wrapper, NOT the envelope code — that varies by backend (500.1 on prod, 400.1 seen on staging),\n\t\t// and keying off it means the probe silently stops firing. A non-schema upstream 400 also matches,\n\t\t// which is fine: the strip-and-resend probe is cheap and rejection is only memoized when the\n\t\t// resend succeeds, so misclassification self-corrects.\n\t\treturn getWrappedUpstreamStatus(body) === 400;\n\t}\n\n\tprotected override getHeaders<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tapiKey: string,\n\t\t_model: AIModel<typeof provider.id>,\n\t\t_url: string,\n\t\tconversationId?: string,\n\t): Record<string, string> {\n\t\treturn {\n\t\t\tAccept: 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t'GK-Action': getBackendActionType(action),\n\t\t\t// Scopes the backend's once-per-conversation feature fee — without it every request in a\n\t\t\t// multi-call session (e.g. conflict resolution) is charged the full flat fee.\n\t\t\t...(conversationId ? { 'GK-Conversation-ID': conversationId } : {}),\n\t\t};\n\t}\n\n\tprotected override async handleFetchFailure<TAction extends AIActionType>(\n\t\trsp: Response,\n\t\t_action: TAction,\n\t\t_model: AIModel<typeof provider.id>,\n\t\tretries: number,\n\t\tmaxInputTokens: number,\n\t\tbody?: string,\n\t\tsentTools?: boolean,\n\t): Promise<{ retry: true; maxInputTokens: number; withoutTools?: boolean }> {\n\t\ttype ErrorResponse = {\n\t\t\terror?: { code: string; message: string; data?: any };\n\t\t};\n\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = (body != null ? JSON.parse(body) : await rsp.json()) as ErrorResponse | undefined;\n\t\t} catch {}\n\n\t\t// The backend's own prose says only \"upstream AI provider error (<provider> HTTP <status>)\" and\n\t\t// puts the provider's actual complaint in `data`. Dropping it (as every branch but the\n\t\t// entitlement one did) leaves nothing naming a cause, so a request the upstream rejected is\n\t\t// indistinguishable from any other 400 — and the only way to find out is to guess.\n\t\tlet message = json?.error?.message || rsp.statusText;\n\t\tconst detail = formatErrorData(json?.error?.data);\n\t\tif (detail != null) {\n\t\t\tmessage += `; ${detail}`;\n\t\t}\n\n\t\tlet status: string | number;\n\t\tlet code: string | number;\n\t\t[status, code] = json?.error?.code?.split('.') ?? [];\n\n\t\tstatus = status ? parseInt(status, 10) : rsp.status;\n\t\tcode = code ? parseInt(code, 10) : 0;\n\n\t\t// Classify a wrapped upstream failure by the status it carries, not by the envelope's own code:\n\t\t// prod reports these as 500.1, but staging has been seen using 400.1, and keying off the outer\n\t\t// code means an upstream rate limit arrives as a bare Error with no reason — so no \"Switch\n\t\t// Model\" action and no retry, just an opaque message.\n\t\tconst upstreamStatus = getWrappedUpstreamStatus(message);\n\t\tif (upstreamStatus != null) {\n\t\t\tconst wrapped = new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tswitch (upstreamStatus) {\n\t\t\t\tcase 429:\n\t\t\t\t\tthrow new AIError(AIErrorReason.RateLimitExceeded, wrapped);\n\t\t\t\tcase 413:\n\t\t\t\t\tthrow new AIError(AIErrorReason.RequestTooLarge, wrapped);\n\t\t\t\tcase 401:\n\t\t\t\tcase 403:\n\t\t\t\t\tthrow new AIError(AIErrorReason.Unauthorized, wrapped);\n\t\t\t\t// Anything else is the upstream refusing the request itself. There's nothing to recover\n\t\t\t\t// automatically, so fall through and surface it with the detail folded in above.\n\t\t\t}\n\t\t}\n\n\t\t// Recover a tools rejection BEFORE the switch below. This override owns the 400 case and throws,\n\t\t// so it never reaches `super.handleFetchFailure` — which is the only place the base's\n\t\t// retry-without-tools fallback lives, leaving it unreachable for this provider.\n\t\tif (sentTools && this.isToolsRejection(status, message)) {\n\t\t\treturn { retry: true, maxInputTokens: maxInputTokens, withoutTools: true };\n\t\t}\n\n\t\tswitch (status) {\n\t\t\tcase 400: // Bad Request\n\t\t\t\t// CodeValidation = \"400.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 401:\n\t\t\t\t// CodeAuthentication = \"401.1\"\n\t\t\t\tthrow new AuthenticationRequiredError();\n\t\t\tcase 403:\n\t\t\t\t// CodeAuthorization = \"403.1\"\n\t\t\t\t// CodeEntitlement = \"403.2\"\n\t\t\t\t// CodeFeatureDisabled = \"403.3\"\n\n\t\t\t\t// Entitlement Error\n\t\t\t\tif (code === 2) {\n\t\t\t\t\ttype EntitlementErrorData = {\n\t\t\t\t\t\tentitlementId?: string;\n\t\t\t\t\t\tentitlementValue?: string | number;\n\t\t\t\t\t\tcurrentValue?: string | number;\n\t\t\t\t\t};\n\n\t\t\t\t\tconst data = json?.error?.data as EntitlementErrorData;\n\t\t\t\t\tconst entitlementId = data?.entitlementId;\n\t\t\t\t\tif (entitlementId != null) {\n\t\t\t\t\t\tmessage += `; entitlement=${data.entitlementId} ${JSON.stringify(data)}`;\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\t// If there is an `entitlementValue` then we are over the limit, otherwise it is an entitlement error\n\t\t\t\t\t\tdata?.entitlementValue ? AIErrorReason.UserQuotaExceeded : AIErrorReason.NoEntitlement,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (code === 3) {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.DeniedByOrganization,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new AIError(\n\t\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t);\n\t\t\tcase 404:\n\t\t\t\t// CodeNotFound = \"404.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 408:\n\t\t\t\t// CodeTimeout = \"408.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 413:\n\t\t\t\t// CodeRequestTooLarge = \"413.1\"\n\n\t\t\t\t// Request too large\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tif (retries < 3) {\n\t\t\t\t\t\treturn { retry: true, maxInputTokens: getReducedMaxInputTokens(maxInputTokens, retries + 1) };\n\t\t\t\t\t}\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RequestTooLarge,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 429:\n\t\t\t\t// CodeTooManyRequests = \"429.1\"\n\n\t\t\t\t// Too many requests\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RateLimitExceeded,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 499:\n\t\t\t\t// CodeRequestCanceled = \"499.1\"\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tcase 500: {\n\t\t\t\t// CodeServerError = \"500.1\"\n\t\t\t\t// Wrapped upstream failures are classified above, before this switch — the backend has\n\t\t\t\t// used more than one envelope code for them, so that can't key off `status`.\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\t}\n\t\t\tcase 503:\n\t\t\t\t// CodeServiceUnavailable = \"503.1\"\n\n\t\t\t\t// Service unavailable\n\t\t\t\tif (code === 1) {\n\t\t\t\t\tif (message === 'Agent Error: too many requests') {\n\t\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\t\tAIErrorReason.ServiceCapacityExceeded,\n\t\t\t\t\t\t\tnew Error(`(${this.name}) ${status}.${code}: ${message}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`(${this.name}) ${status}.${code}: ${message}`);\n\t\t}\n\t}\n}\n\n/** Max characters of `error.data` folded into a message — enough to name a cause, bounded so a large\n * payload can't dominate a notification or a log line. */\nconst maxErrorDetailLength = 500;\n\n/**\n * Renders the backend's `error.data` as a short detail string. This is where the upstream provider's\n * own complaint arrives, so it's the difference between \"upstream AI provider error (OpenAI HTTP 400)\"\n * and knowing which field it rejected.\n *\n * Strings pass through; objects are JSON-encoded. A common shape is the upstream's own error envelope,\n * so a nested `message` is preferred when present rather than dumping the whole object.\n */\nfunction formatErrorData(data: unknown): string | undefined {\n\tif (data == null) return undefined;\n\n\tlet text: string | undefined;\n\tif (typeof data === 'string') {\n\t\ttext = data;\n\t} else if (typeof data === 'object') {\n\t\tconst nested =\n\t\t\t(data as { error?: { message?: unknown }; message?: unknown }).error?.message ??\n\t\t\t(data as { message?: unknown }).message;\n\t\tif (typeof nested === 'string' && nested) {\n\t\t\ttext = nested;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\ttext = JSON.stringify(data);\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t} else if (typeof data === 'number' || typeof data === 'boolean') {\n\t\ttext = String(data);\n\t}\n\n\ttext = text?.trim();\n\tif (!text || text === '{}' || text === 'null') return undefined;\n\n\treturn text.length > maxErrorDetailLength ? `${text.slice(0, maxErrorDetailLength)}…` : text;\n}\n\n/** Extracts the upstream HTTP status from the backend's upstream-error prose wrapper. The envelope code\n * varies (500.1 on prod, 400.1 seen on staging), so callers must key off this, not the outer code. */\nfunction getWrappedUpstreamStatus(text: string): number | undefined {\n\tconst status = /upstream ai provider error[\\s\\S]*?http (\\d{3})/i.exec(text)?.[1];\n\treturn status != null ? parseInt(status, 10) : undefined;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,4BAA4B;AAElC,IAAa,oBAAb,cAAuC,6BAAiD;CACvF,KAAcA,4BAAS;CACvB,OAAgBA,4BAAS;CACzB,gBAAyB;CACzB,aAAgCA;CAChC,SAA4B,CAAC;CAE7B,MAAe,UAAU,QAA8C;EACtE,OAAO,KAAK,QAAQ,UACnB;GACC,IAAI,KAAK;GACT,MAAM,KAAK;GACX,iBAAiB,KAAK,WAAW;GACjC,iBAAiB;EAClB,GACA,MACD;CACD;CAEA,MACM,YAA6D;EAClE,MAAM,QAAQ,gBAAgB;EAE9B,IAAI;GACH,MAAM,MAAM,MAAM,KAAK,QAAQ,MAAM,4BAA4B,EAChE,SAAS,EAAE,QAAQ,mBAAmB,EACvC,CAAC;GACD,IAAI,CAAC,IAAI,IACR,MAAM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AI,OAAO,GAAG,KAAK,IAAI,SAAS;GAC/D,SACC,MAAM,IAAI,MAAM,IAAI,KAAK,KAAK,IAAI,OAAO,GAAG,KAAK,IAAI,SAAS;EAChE;CACD;AACD;AAzQE,WAAA,CAAA,MAAM,CAAA,GAAA,kBAAA,WAAA,aAAA,IAAA;;;AA6QR,MAAM,uBAAuB;;;;;;;;;AAU7B,SAAS,gBAAgB,MAAmC;CAC3D,IAAI,QAAQ,MAAM,OAAO,KAAA;CAEzB,IAAI;CACJ,IAAI,OAAO,SAAS,UACnB,OAAO;MACD,IAAI,OAAO,SAAS,UAAU;EACpC,MAAM,SACJ,KAA8D,OAAO,WACrE,KAA+B;EACjC,IAAI,OAAO,WAAW,YAAY,QACjC,OAAO;OAEP,IAAI;GACH,OAAO,KAAK,UAAU,IAAI;EAC3B,QAAQ;GACP;EACD;CAEF,OAAO,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,WACtD,OAAO,OAAO,IAAI;CAGnB,OAAO,MAAM,KAAK;CAClB,IAAI,CAAC,QAAQ,SAAS,QAAQ,SAAS,QAAQ,OAAO,KAAA;CAEtD,OAAO,KAAK,SAAS,uBAAuB,GAAG,KAAK,MAAM,GAAG,oBAAoB,EAAE,KAAK;AACzF;;;AAIA,SAAS,yBAAyB,MAAkC;CACnE,MAAM,SAAS,kDAAkD,KAAK,IAAI,CAAC,GAAG;CAC9E,OAAO,UAAU,OAAO,SAAS,QAAQ,EAAE,IAAI,KAAA;AAChD"}
|
|
@@ -17,6 +17,7 @@ function getRequestErrorMessage(action, providerName, message) {
|
|
|
17
17
|
switch (action) {
|
|
18
18
|
case "explain-changes": return l10n.t("Unable to Explain Changes: ({provider}) {message}", args);
|
|
19
19
|
case "review-changes": return l10n.t("Unable to Review Changes: ({provider}) {message}", args);
|
|
20
|
+
case "review-orient": return l10n.t("Unable to Orient Changes: ({provider}) {message}", args);
|
|
20
21
|
case "generate-commitMessage": return l10n.t("Unable to Generate Commit Message: ({provider}) {message}", args);
|
|
21
22
|
case "generate-stashMessage": return l10n.t("Unable to Generate Stash Message: ({provider}) {message}", args);
|
|
22
23
|
case "generate-changelog": return l10n.t("Unable to Generate Changelog: ({provider}) {message}", args);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAICompatibleProviderBase.js","names":[],"sources":["../../../../../plus/ai/src/providers/openAICompatibleProviderBase.ts"],"sourcesContent":["import * as l10n from '@vscode/l10n';\nimport { CancellationError, isCancellationError } from '@gitlens/utils/cancellation.js';\nimport { uuid } from '@gitlens/utils/crypto.js';\nimport { getLoggableName, Logger } from '@gitlens/utils/logger.js';\nimport { maybeStartScopedLogger } from '@gitlens/utils/logger.scoped.js';\nimport type { AIProviders } from '../constants.js';\nimport { AIError, AIErrorReason } from '../errors.js';\nimport type { AIActionType, AIModel, AIProviderDescriptor } from '../models/model.js';\nimport type {\n\tAIChatMessage,\n\tAIChatMessageRole,\n\tAIFinishReason,\n\tAIProvider,\n\tAIProviderResponse,\n\tAIResponseFormat,\n\tAIToolCall,\n\tAIToolDefinition,\n\tJSONSchema,\n} from '../models/provider.js';\nimport { getActionName, getReducedMaxInputTokens, getValidatedTemperature } from '../utils/ai.utils.js';\nimport type { AIProviderContext } from './context.js';\nimport { isResponseFormatRejected, rememberResponseFormatRejection } from './responseFormatCache.js';\n\n// Native-format rejection wording varies by provider (\"response_format\", \"structured outputs\",\n// Gemini's \"Json mode is not enabled\", and its OpenAI-compat layer's `generation_config.response_schema`\n// path in INVALID_ARGUMENT bodies, ...)\nconst formatRejectionRegex =\n\t/response[_ ]?(?:format|schema)|structured[_ ]?output|output_config|json_schema|json[_ ]?mode/i;\n\nfunction getRequestErrorMessage(action: AIActionType, providerName: string, message: string): string {\n\tconst args = { provider: providerName, message: message };\n\tswitch (action) {\n\t\tcase 'explain-changes':\n\t\t\treturn l10n.t('Unable to Explain Changes: ({provider}) {message}', args);\n\t\tcase 'review-changes':\n\t\t\treturn l10n.t('Unable to Review Changes: ({provider}) {message}', args);\n\t\tcase 'generate-commitMessage':\n\t\t\treturn l10n.t('Unable to Generate Commit Message: ({provider}) {message}', args);\n\t\tcase 'generate-stashMessage':\n\t\t\treturn l10n.t('Unable to Generate Stash Message: ({provider}) {message}', args);\n\t\tcase 'generate-changelog':\n\t\t\treturn l10n.t('Unable to Generate Changelog: ({provider}) {message}', args);\n\t\tcase 'generate-create-cloudPatch':\n\t\t\treturn l10n.t('Unable to Create Cloud Patch Details: ({provider}) {message}', args);\n\t\tcase 'generate-create-pullRequest':\n\t\t\treturn l10n.t('Unable to Create Pull Request Details: ({provider}) {message}', args);\n\t\tcase 'generate-commits':\n\t\t\treturn l10n.t('Unable to Generate Commits: ({provider}) {message}', args);\n\t\tcase 'conflict-resolution':\n\t\t\treturn l10n.t('Unable to Resolve Conflicts (Preview): ({provider}) {message}', args);\n\t\tcase 'generate-searchQuery':\n\t\t\treturn l10n.t('Unable to Generate Search Query: ({provider}) {message}', args);\n\t}\n}\n\nexport abstract class OpenAICompatibleProviderBase<T extends AIProviders> implements AIProvider<T> {\n\tconstructor(protected readonly context: AIProviderContext) {}\n\n\tdispose(): void {}\n\t[Symbol.dispose](): void {\n\t\tthis.dispose();\n\t}\n\n\tabstract readonly id: T;\n\tabstract readonly name: string;\n\tprotected abstract readonly descriptor: AIProviderDescriptor<T>;\n\tprotected abstract readonly config: { keyUrl?: string; keyValidator?: RegExp };\n\n\tasync configured(silent: boolean): Promise<boolean> {\n\t\ttry {\n\t\t\tconst apiKey = await this.getApiKey(silent);\n\t\t\treturn apiKey != null;\n\t\t} catch (ex) {\n\t\t\tif (isCancellationError(ex)) return false;\n\n\t\t\tthrow ex;\n\t\t}\n\t}\n\n\tasync getApiKey(silent: boolean): Promise<string | undefined> {\n\t\tconst orgConf = this.context.getProviderConfig(this.id);\n\t\tif (!orgConf.enabled) return undefined;\n\t\tif (orgConf.key) return orgConf.key;\n\n\t\tconst { keyUrl, keyValidator } = this.config;\n\n\t\treturn this.context.getApiKey(\n\t\t\t{\n\t\t\t\tid: this.id,\n\t\t\t\tname: this.name,\n\t\t\t\trequiresAccount: this.descriptor.requiresAccount,\n\t\t\t\tvalidator: keyValidator != null ? v => keyValidator.test(v) : () => true,\n\t\t\t\turl: keyUrl,\n\t\t\t},\n\t\t\tsilent,\n\t\t);\n\t}\n\n\tabstract getModels(): Promise<readonly AIModel<T>[]>;\n\n\tprotected isResponseFormatSessionRejected(model: AIModel<T>, responseFormat: AIResponseFormat): boolean {\n\t\treturn isResponseFormatRejected(this.id, model, responseFormat);\n\t}\n\n\tprotected rememberResponseFormatRejection(model: AIModel<T>, responseFormat: AIResponseFormat): void {\n\t\trememberResponseFormatRejection(this.id, model, responseFormat);\n\t}\n\n\tprotected abstract getUrl(_model: AIModel<T>): string | undefined;\n\n\tprotected getHeaders<TAction extends AIActionType>(\n\t\t_action: TAction,\n\t\tapiKey: string,\n\t\t_model: AIModel<T>,\n\t\t_url: string,\n\t\t// Deliberately unused here: only the GitKraken provider forwards the conversation ID (as\n\t\t// `GK-Conversation-ID`); it must never reach third-party APIs.\n\t\t_conversationId?: string,\n\t): Record<string, string> | Promise<Record<string, string>> {\n\t\treturn {\n\t\t\tAccept: 'application/json',\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t};\n\t}\n\n\tasync sendRequest<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\tgetMessages: (maxInputTokens: number, retries: number) => Promise<AIChatMessage<AIChatMessageRole>[]>,\n\t\toptions: {\n\t\t\tsignal: AbortSignal;\n\t\t\tmodelOptions?: { outputTokens?: number; temperature?: number };\n\t\t\tconversationId?: string;\n\t\t\tresponseFormat?: AIResponseFormat;\n\t\t\ttools?: readonly AIToolDefinition[];\n\t\t},\n\t): Promise<AIProviderResponse<void> | undefined> {\n\t\tusing scope = maybeStartScopedLogger(`${getLoggableName(this)}.sendRequest`);\n\n\t\ttry {\n\t\t\tconst result = await this.fetch(\n\t\t\t\taction,\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\tgetMessages,\n\t\t\t\toptions.modelOptions,\n\t\t\t\toptions.responseFormat,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.conversationId,\n\t\t\t\toptions.tools,\n\t\t\t);\n\t\t\treturn result;\n\t\t} catch (ex) {\n\t\t\tif (isCancellationError(ex)) {\n\t\t\t\tscope?.error(ex, `Cancelled request to ${getActionName(action)}: (${model.provider.name})`);\n\t\t\t\tthrow ex;\n\t\t\t}\n\n\t\t\tscope?.error(ex, `Unable to ${getActionName(action)}: (${model.provider.name})`);\n\t\t\tif (ex instanceof AIError) throw ex;\n\n\t\t\tdebugger;\n\t\t\tthrow new Error(getRequestErrorMessage(action, model.provider.name, ex.message), { cause: ex });\n\t\t}\n\t}\n\n\tprotected async fetch<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\tmessages: (maxInputTokens: number, retries: number) => Promise<AIChatMessage<AIChatMessageRole>[]>,\n\t\tmodelOptions?: { outputTokens?: number; temperature?: number },\n\t\tresponseFormat?: AIResponseFormat,\n\t\tsignal?: AbortSignal,\n\t\tconversationId?: string,\n\t\ttools?: readonly AIToolDefinition[],\n\t): Promise<AIProviderResponse<void>> {\n\t\tlet retries = 0;\n\t\tlet maxInputTokens = model.maxTokens.input;\n\t\t// Latched when the provider rejects the `tools` field, so the retry drops tools entirely and\n\t\t// the caller can stop offering them for the rest of the session.\n\t\tlet toolsRejected = false;\n\n\t\twhile (true) {\n\t\t\tconst useTools = tools?.length && !toolsRejected ? tools : undefined;\n\t\t\tconst { messages: msgs, system } = this.extractSystemPrompt(await messages(maxInputTokens, retries));\n\t\t\tconst request: ChatCompletionRequest = {\n\t\t\t\tmodel: model.id,\n\t\t\t\tmessages: this.serializeMessages(msgs),\n\t\t\t\t...(system != null ? { system: system } : undefined),\n\t\t\t\t...(useTools != null ? this.serializeTools(useTools) : undefined),\n\t\t\t\tstream: false,\n\t\t\t\tmax_completion_tokens: model.maxTokens.output\n\t\t\t\t\t? Math.min(modelOptions?.outputTokens ?? Infinity, model.maxTokens.output)\n\t\t\t\t\t: modelOptions?.outputTokens,\n\t\t\t\ttemperature: getValidatedTemperature(\n\t\t\t\t\tmodel,\n\t\t\t\t\tmodelOptions?.temperature ?? model.temperature,\n\t\t\t\t\tthis.context.defaultTemperature,\n\t\t\t\t),\n\t\t\t};\n\t\t\tif (\n\t\t\t\tresponseFormat != null &&\n\t\t\t\t!this.isResponseFormatSessionRejected(model, responseFormat) &&\n\t\t\t\tthis.supportsResponseFormat(model)\n\t\t\t) {\n\t\t\t\tthis.applyResponseFormat(request, model, responseFormat);\n\t\t\t}\n\n\t\t\tlet rsp = await this.fetchCore(action, model, apiKey, request, signal, conversationId);\n\t\t\t// Read once and forward to `handleFetchFailure` so the error body isn't decoded twice\n\t\t\tlet errorBody: string | undefined;\n\t\t\tif (!rsp.ok && (request.response_format != null || request.output_config != null)) {\n\t\t\t\t// If the native format was rejected (stale model snapshot, older Azure api-version,\n\t\t\t\t// proxy converter gaps, OpenRouter's require_parameters matching no endpoint), strip\n\t\t\t\t// it and resend the same request — the prompt still describes the JSON. Resending\n\t\t\t\t// directly avoids re-running the (non-idempotent) prompt build and its side effects\n\t\t\t\t// Leave it `undefined` (not '') when the read fails, so `handleFetchFailure` falls\n\t\t\t\t// back to reading the still-unconsumed response instead of parsing an empty string\n\t\t\t\terrorBody = await rsp\n\t\t\t\t\t.clone()\n\t\t\t\t\t.text()\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t\tif (this.isResponseFormatRejection(rsp.status, errorBody ?? '')) {\n\t\t\t\t\tLogger.warn(\n\t\t\t\t\t\t`(${this.name}) ${model.id}: native response format was rejected (${rsp.status}); retrying without it`,\n\t\t\t\t\t);\n\t\t\t\t\tconst rejected = responseFormat;\n\t\t\t\t\tresponseFormat = undefined;\n\t\t\t\t\tdelete request.response_format;\n\t\t\t\t\tdelete request.output_config;\n\t\t\t\t\tdelete request.provider;\n\t\t\t\t\trsp = await this.fetchCore(action, model, apiKey, request, signal, conversationId);\n\t\t\t\t\terrorBody = undefined;\n\t\t\t\t\t// Memoize only when stripping fixed it — proof the format (not e.g. an oversized\n\t\t\t\t\t// prompt behind the same wrapped status) caused the failure\n\t\t\t\t\tif (rsp.ok && rejected != null) {\n\t\t\t\t\t\tthis.rememberResponseFormatRejection(model, rejected);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!rsp.ok) {\n\t\t\t\tconst result = await this.handleFetchFailure(\n\t\t\t\t\trsp,\n\t\t\t\t\taction,\n\t\t\t\t\tmodel,\n\t\t\t\t\tretries,\n\t\t\t\t\tmaxInputTokens,\n\t\t\t\t\terrorBody,\n\t\t\t\t\tuseTools != null,\n\t\t\t\t);\n\t\t\t\tif (result.retry) {\n\t\t\t\t\tmaxInputTokens = result.maxInputTokens;\n\t\t\t\t\tif (result.withoutTools) {\n\t\t\t\t\t\t// Say so explicitly: the caller degrades silently by design, so the only remaining\n\t\t\t\t\t\t// evidence would be `toolCalls=0` — indistinguishable from a model that simply chose\n\t\t\t\t\t\t// not to consult the repository. That ambiguity is the whole reason to log it.\n\t\t\t\t\t\tLogger.warn(\n\t\t\t\t\t\t\t`(${this.name}) ${model.id}: tools were rejected (${rsp.status}); retrying without them — repository consultation is unavailable for the rest of this session`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttoolsRejected = true;\n\t\t\t\t\t}\n\t\t\t\t\tretries++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst data: ChatCompletionResponse = (await rsp.json()) as ChatCompletionResponse;\n\t\t\tconst toolCalls = this.parseToolCalls(data);\n\t\t\t// A tool-call-only turn carries no text, which `extractContent` correctly reports as '' — it\n\t\t\t// selects the text block by type, so a `tool_use` (or thinking) block is never mistaken for one.\n\t\t\t// The calls ride alongside on `toolCalls` below.\n\t\t\tconst content = this.extractContent(data);\n\t\t\t// Some providers/proxies (e.g. OpenRouter) report upstream failures as an OK response\n\t\t\t// carrying an error envelope and no choices — surface that instead of empty content\n\t\t\tif (!content && toolCalls == null && data.error != null) {\n\t\t\t\tif (data.error.code === 429 || data.error.code === '429') {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RateLimitOrFundsExceeded,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${data.error.message || 'Rate limit exceeded'}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${data.error.message || 'Unknown error'}`);\n\t\t\t}\n\n\t\t\tconst result: AIProviderResponse<void> = {\n\t\t\t\tid: data.id ?? uuid(),\n\t\t\t\tcontent: content,\n\t\t\t\tfinishReason: this.extractFinishReason(data),\n\t\t\t\tmodel: model,\n\t\t\t\t...(toolCalls?.length ? { toolCalls: toolCalls } : undefined),\n\t\t\t\t...(toolsRejected ? { toolsRejected: true } : undefined),\n\t\t\t\tusage: {\n\t\t\t\t\tpromptTokens: data.usage?.prompt_tokens ?? data.usage?.input_tokens,\n\t\t\t\t\tcompletionTokens: data.usage?.completion_tokens ?? data.usage?.output_tokens,\n\t\t\t\t\ttotalTokens: data.usage?.total_tokens,\n\t\t\t\t\tlimits:\n\t\t\t\t\t\tdata?.usage?.gk != null\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tused: data.usage.gk.used,\n\t\t\t\t\t\t\t\t\tlimit: data.usage.gk.limit,\n\t\t\t\t\t\t\t\t\tresetsOn: new Date(data.usage.gk.resets_on),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tresult: undefined,\n\t\t\t};\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the message-related request fields. The default sends every message inline (OpenAI\n\t * Chat Completions semantics); providers whose API carries the initial system prompt separately\n\t * (e.g. Anthropic's top-level `system`) override this to extract it from the messages.\n\t */\n\tprotected extractSystemPrompt(messages: AIChatMessage<AIChatMessageRole>[]): {\n\t\tmessages: AIChatMessage<AIChatMessageRole>[];\n\t\tsystem?: string;\n\t} {\n\t\treturn { messages: messages };\n\t}\n\n\t/** Whether the given model accepts a native response-format/schema field; when false the\n\t * prompt's JSON description is the only format control (the request is unchanged).\n\t * Dynamic-catalog providers (GitKraken, OpenRouter) populate\n\t * {@link AIModel.supportsStructuredOutputs}; static providers override with id-based gates */\n\tprotected supportsResponseFormat(model: AIModel<T>): boolean {\n\t\treturn model.supportsStructuredOutputs ?? true;\n\t}\n\n\t/**\n\t * Whether a failed response reads as a rejection of the `tools` field rather than a problem with the\n\t * prompt — the trigger for one retry without tools, so a tool-using feature degrades to single-shot\n\t * instead of failing outright.\n\t *\n\t * Providers that wrap upstream rejections in their own envelope (e.g. GitKraken) must override this:\n\t * the wrapper's prose names neither \"tool\" nor \"function\", so the text match here cannot see through\n\t * it and the fallback would never fire.\n\t */\n\tprotected isToolsRejection(status: number, message: string | undefined): boolean {\n\t\tif (status !== 400 || !message) return false;\n\n\t\tconst m = message.toLowerCase();\n\t\treturn (\n\t\t\t(m.includes('tool') || m.includes('function')) &&\n\t\t\t(m.includes('unsupported') ||\n\t\t\t\tm.includes('not supported') ||\n\t\t\t\tm.includes('unknown') ||\n\t\t\t\tm.includes('unrecognized') ||\n\t\t\t\tm.includes('invalid') ||\n\t\t\t\tm.includes('unexpected'))\n\t\t);\n\t}\n\n\t/** Whether a failed response means the native response format itself was rejected — the\n\t * trigger for stripping it and retrying via the prompt-described JSON. Providers that wrap\n\t * upstream rejections in their own envelope (e.g. GitKraken) extend this */\n\tprotected isResponseFormatRejection(status: number, body: string): boolean {\n\t\treturn (\n\t\t\t(status === 400 && formatRejectionRegex.test(body)) ||\n\t\t\t// OpenRouter answers 404 when `require_parameters` matches no serving endpoint\n\t\t\t(status === 404 && /no endpoints found/i.test(body))\n\t\t);\n\t}\n\n\t/** Translates the canonical response format onto the request; called only when\n\t * {@link supportsResponseFormat} allows it. Base emits the OpenAI `response_format.json_schema`\n\t * envelope. Overrides must REPLACE this for providers with a different native field\n\t * (e.g. Anthropic `output_config`) — never leave both on the request. */\n\tprotected applyResponseFormat(\n\t\trequest: ChatCompletionRequest,\n\t\t_model: AIModel<T>,\n\t\tresponseFormat: AIResponseFormat,\n\t): void {\n\t\trequest.response_format = {\n\t\t\ttype: 'json_schema',\n\t\t\tjson_schema: {\n\t\t\t\tname: responseFormat.name,\n\t\t\t\tstrict: true,\n\t\t\t\tschema: responseFormat.schema,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Finds the text block by type rather than position — with some Anthropic models (e.g. Sonnet 5,\n\t// where thinking runs by default) a thinking block can precede the text block\n\tprotected extractContent(data: ChatCompletionResponse): string {\n\t\treturn (\n\t\t\tdata.choices?.[0]?.message?.content?.trim() ??\n\t\t\tdata.content?.find(b => b.type === 'text')?.text?.trim() ??\n\t\t\t''\n\t\t);\n\t}\n\n\t/** Normalizes abnormal completion signals (all arrive as HTTP 200) so consumers can\n\t * distinguish truncated/filtered/refused output from a malformed-but-complete reply */\n\tprotected extractFinishReason(data: ChatCompletionResponse): AIFinishReason | undefined {\n\t\tconst choice = data.choices?.[0];\n\t\tif (choice != null) {\n\t\t\t// Truthy check — some OpenAI-compatible servers serialize `\"refusal\": \"\"` on normal replies\n\t\t\tif (choice.message?.refusal) return 'refusal';\n\t\t\tif (choice.finish_reason === 'length') return 'length';\n\t\t\tif (choice.finish_reason === 'content_filter') return 'content_filter';\n\t\t\treturn undefined;\n\t\t}\n\n\t\tswitch (data.stop_reason) {\n\t\t\t// `model_context_window_exceeded` means the context filled before the output limit — the\n\t\t\t// reply is truncated all the same\n\t\t\tcase 'max_tokens':\n\t\t\tcase 'model_context_window_exceeded':\n\t\t\t\treturn 'length';\n\t\t\tcase 'refusal':\n\t\t\t\treturn 'refusal';\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Maps messages onto the provider's wire shape. The default is OpenAI Chat Completions: assistant\n\t * tool calls go in `tool_calls` with `arguments` JSON-stringified, and tool results are `tool`-role\n\t * entries keyed by `tool_call_id`. Providers with a different tool encoding (e.g. Anthropic's\n\t * content blocks) override this.\n\t */\n\tprotected serializeMessages(messages: AIChatMessage<AIChatMessageRole>[]): unknown[] {\n\t\treturn messages.map(m => {\n\t\t\tif (m.role === 'tool') {\n\t\t\t\t// A tool result is only addressable by the id of the call it answers. Without one, send it\n\t\t\t\t// as plain text — the same shape used for providers that can't carry tool calls at all —\n\t\t\t\t// rather than a `tool_call_id: undefined` the provider rejects with nothing to trace it to.\n\t\t\t\tif (m.toolCallId == null) return { role: 'user', content: m.content };\n\n\t\t\t\treturn { role: 'tool', tool_call_id: m.toolCallId, content: m.content };\n\t\t\t}\n\n\t\t\tif (m.role === 'assistant' && m.toolCalls?.length) {\n\t\t\t\treturn {\n\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t// OpenAI requires `content` to be present, but allows null on a tool-call-only turn\n\t\t\t\t\tcontent: m.content || null,\n\t\t\t\t\ttool_calls: m.toolCalls.map(c => ({\n\t\t\t\t\t\tid: c.id,\n\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\tfunction: { name: c.name, arguments: JSON.stringify(c.args) },\n\t\t\t\t\t\t// Only the GitKraken proxy mints these, so the field can only ever be present on a\n\t\t\t\t\t\t// conversation with that proxy — no other provider sees it.\n\t\t\t\t\t\t...(c.providerSignature != null ? { thought_signature: c.providerSignature } : undefined),\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn { role: m.role, content: m.content };\n\t\t});\n\t}\n\n\t/** Returns the tool-related request fields. The default is the OpenAI `function` envelope. */\n\tprotected serializeTools(tools: readonly AIToolDefinition[]): { tools: unknown[] } {\n\t\treturn {\n\t\t\ttools: tools.map(t => ({\n\t\t\t\ttype: 'function',\n\t\t\t\tfunction: { name: t.name, description: t.description, parameters: t.parameters },\n\t\t\t})),\n\t\t};\n\t}\n\n\t/**\n\t * Extracts tool calls from a response, handling both the OpenAI shape\n\t * (`choices[].message.tool_calls`, whose `arguments` is a JSON string) and the Anthropic shape\n\t * (`content[]` blocks of type `tool_use`) — mirroring how {@link fetch} already reads content\n\t * from both.\n\t */\n\tprotected parseToolCalls(data: ChatCompletionResponse): AIToolCall[] | undefined {\n\t\tconst calls: AIToolCall[] = [];\n\n\t\tfor (const call of data.choices?.[0]?.message?.tool_calls ?? []) {\n\t\t\tlet args: Record<string, unknown> = {};\n\t\t\ttry {\n\t\t\t\t// Providers can emit '' for a no-argument call\n\t\t\t\targs = call.function.arguments ? (JSON.parse(call.function.arguments) as Record<string, unknown>) : {};\n\t\t\t} catch {\n\t\t\t\t// Leave args empty — the tool dispatcher reports the resulting validation error back to\n\t\t\t\t// the model, which is more recoverable than failing the whole request here.\n\t\t\t}\n\n\t\t\tcalls.push({\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.function.name,\n\t\t\t\targs: args,\n\t\t\t\t...(call.thought_signature != null ? { providerSignature: call.thought_signature } : undefined),\n\t\t\t});\n\t\t}\n\n\t\tfor (const block of data.content ?? []) {\n\t\t\tif (block.type !== 'tool_use' || block.id == null || block.name == null) continue;\n\n\t\t\tcalls.push({ id: block.id, name: block.name, args: block.input ?? {} });\n\t\t}\n\n\t\treturn calls.length ? calls : undefined;\n\t}\n\n\tprotected async handleFetchFailure<TAction extends AIActionType>(\n\t\trsp: Response,\n\t\t_action: TAction,\n\t\tmodel: AIModel<T>,\n\t\tretries: number,\n\t\tmaxInputTokens: number,\n\t\t/** The already-read error body, when the caller had to read it (avoids a second decode) */\n\t\tbody?: string,\n\t\tsentTools?: boolean,\n\t): Promise<{ retry: true; maxInputTokens: number; withoutTools?: boolean }> {\n\t\tif (rsp.status === 404) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\tnew Error(`Your API key doesn't seem to have access to the selected '${model.id}' model`),\n\t\t\t);\n\t\t}\n\t\tif (rsp.status === 429) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.RateLimitOrFundsExceeded,\n\t\t\t\tnew Error(\n\t\t\t\t\t`(${this.name}) ${rsp.status}: Too many requests (rate limit exceeded) or your account is out of funds`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = (body != null ? JSON.parse(body) : await rsp.json()) as\n\t\t\t\t| { error?: { code: string; message: string } }\n\t\t\t\t| undefined;\n\t\t} catch {}\n\n\t\tif (Array.isArray(json)) {\n\t\t\tjson = json[0];\n\t\t}\n\n\t\t// A revoked/invalid key or no access: AI is unavailable to this user, not a one-off failure.\n\t\t// Neither retry probe below can apply — both only match a 400 (or the OpenRouter 404 handled above)\n\t\tif (rsp.status === 401 || rsp.status === 403) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\tnew Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`),\n\t\t\t);\n\t\t}\n\n\t\tif (json?.error?.code === 'context_length_exceeded') {\n\t\t\tif (retries < 3) {\n\t\t\t\treturn { retry: true, maxInputTokens: getReducedMaxInputTokens(maxInputTokens, retries + 1) };\n\t\t\t}\n\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.RequestTooLarge,\n\t\t\t\tnew Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`),\n\t\t\t);\n\t\t}\n\n\t\t// A provider that advertises the OpenAI shape but rejects `tools` (an older or partial\n\t\t// implementation) gets one retry without them, so the caller degrades to text-only instead of\n\t\t// failing outright.\n\t\tif (sentTools && this.isToolsRejection(rsp.status, json?.error?.message)) {\n\t\t\treturn { retry: true, maxInputTokens: maxInputTokens, withoutTools: true };\n\t\t}\n\n\t\tthrow new Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`);\n\t}\n\n\tprotected async fetchCore<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\trequest: object,\n\t\tsignal: AbortSignal | undefined,\n\t\tconversationId?: string,\n\t): Promise<Response> {\n\t\tconst url = this.getUrl(model);\n\t\tif (!url) {\n\t\t\tthrow new Error(`(${this.name}) ${getActionName(action)}: No URL configured`);\n\t\t}\n\n\t\tconst body = JSON.stringify(request);\n\n\t\t// A rejected request is otherwise undiagnosable: a proxying backend reports only its own\n\t\t// \"upstream AI provider error (<provider> HTTP <status>)\", so which field the upstream objected to\n\t\t// can only be inferred. Log the request's shape — which fields were sent, and how much — but not\n\t\t// the messages, which carry the user's source code.\n\t\tLogger.trace(\n\t\t\t`(${this.name}) ${getActionName(action)} → ${model.id}: fields=[${Object.keys(request)\n\t\t\t\t.sort()\n\t\t\t\t.join(',')}] bytes=${body.length}`,\n\t\t);\n\n\t\ttry {\n\t\t\treturn await this.context.fetch(url, {\n\t\t\t\theaders: await this.getHeaders(action, apiKey, model, url, conversationId),\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: body,\n\t\t\t\tsignal: signal,\n\t\t\t});\n\t\t} catch (ex) {\n\t\t\tif (ex.name === 'AbortError') throw new CancellationError(ex);\n\t\t\tthrow ex;\n\t\t}\n\t}\n}\n\nexport interface ChatCompletionRequest {\n\tmodel: string;\n\t/** Provider-shaped messages from {@link OpenAICompatibleProviderBase.serializeMessages} */\n\tmessages: unknown[];\n\n\t/** Anthropic carries the initial system prompt here instead of as a `system`-role message */\n\tsystem?: string;\n\n\t/** Tool definitions, shaped by {@link OpenAICompatibleProviderBase.serializeTools} */\n\ttools?: unknown[];\n\n\t/** @deprecated but used by Anthropic & Gemini */\n\tmax_tokens?: number;\n\t/** Currently can't be used for Anthropic & Gemini */\n\tmax_completion_tokens?: number;\n\tmetadata?: Record<string, string>;\n\tstream?: boolean;\n\ttemperature?: number;\n\ttop_p?: number;\n\n\t/** Not supported by many models/providers */\n\treasoning_effort?: 'low' | 'medium' | 'high';\n\n\t/** OpenAI-compatible structured output (set via {@link OpenAICompatibleProviderBase.applyResponseFormat}) */\n\tresponse_format?: { type: 'json_schema'; json_schema: { name: string; strict: boolean; schema: JSONSchema } };\n\t/** Anthropic-native structured output (set only by the Anthropic override) */\n\toutput_config?: { format: { type: 'json_schema'; schema: JSONSchema } };\n\t/** OpenRouter-only routing constraint (set only by the OpenRouter override) */\n\tprovider?: { require_parameters: boolean };\n}\n\nexport interface ChatCompletionResponse {\n\tid: string;\n\tmodel: string;\n\t/** OpenAI compatible output */\n\tchoices?: {\n\t\tindex: number;\n\t\tmessage: {\n\t\t\trole: string;\n\t\t\tcontent: string | null;\n\t\t\t/** OpenAI-only; most OpenAI-compatible servers omit it entirely */\n\t\t\trefusal?: string | null;\n\t\t\ttool_calls?: {\n\t\t\t\tid: string;\n\t\t\t\ttype: string;\n\t\t\t\tfunction: { name: string; arguments: string };\n\t\t\t\t/** GitKraken proxy only — an opaque provider reasoning token to round-trip */\n\t\t\t\tthought_signature?: string;\n\t\t\t}[];\n\t\t};\n\t\tfinish_reason: string;\n\t}[];\n\t/** Anthropic output (non-text blocks, e.g. thinking, carry no text). `tool_use` blocks add the\n\t * call fields, which is why `id`/`name` are optional here — {@link parseToolCalls} narrows on\n\t * `type` and then checks them. */\n\tcontent?: { type: string; text?: string; id?: string; name?: string; input?: Record<string, unknown> }[];\n\t/** Error envelope some providers/proxies return with an OK status (e.g. OpenRouter upstream failures) */\n\terror?: { message?: string; code?: number | string } | null;\n\t/** Anthropic stop reason */\n\tstop_reason?: string;\n\tusage: {\n\t\t/** OpenAI compatible */\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\ttotal_tokens?: number;\n\n\t\t/** Anthropic */\n\t\tinput_tokens?: number;\n\t\toutput_tokens?: number;\n\n\t\t/** GitKraken */\n\t\tgk: {\n\t\t\tused: number;\n\t\t\tlimit: number;\n\t\t\tresets_on: string;\n\t\t};\n\t};\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,uBACL;AAED,SAAS,uBAAuB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K;EAC7B,IAAI,CAAC,KACJ,MAAM,IAAI,MAAM,IAAI,KAAK,KAAK,IAAI,cAAc,MAAM,EAAE,oBAAoB;EAG7E,MAAM,OAAO,KAAK,UAAU,OAAO;EAMnC,QAAO,MACN,IAAI,KAAK,KAAK,IAAI,cAAc,MAAM,EAAE,KAAK,MAAM,GAAG,YAAY,OAAO,KAAK,OAAO,CAAC,CACpF,KAAK,CAAC,CACN,KAAK,GAAG,EAAE,UAAU,KAAK,QAC5B;EAEA,IAAI;GACH,OAAO,MAAM,KAAK,QAAQ,MAAM,KAAK;IACpC,SAAS,MAAM,KAAK,WAAW,QAAQ,QAAQ,OAAO,KAAK,cAAc;IACzE,QAAQ;IACF;IACE;GACT,CAAC;EACF,SAAS,IAAI;GACZ,IAAI,GAAG,SAAS,cAAc,MAAM,IAAI,kBAAkB,EAAE;GAC5D,MAAM;EACP;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"openAICompatibleProviderBase.js","names":[],"sources":["../../../../../plus/ai/src/providers/openAICompatibleProviderBase.ts"],"sourcesContent":["import * as l10n from '@vscode/l10n';\nimport { CancellationError, isCancellationError } from '@gitlens/utils/cancellation.js';\nimport { uuid } from '@gitlens/utils/crypto.js';\nimport { getLoggableName, Logger } from '@gitlens/utils/logger.js';\nimport { maybeStartScopedLogger } from '@gitlens/utils/logger.scoped.js';\nimport type { AIProviders } from '../constants.js';\nimport { AIError, AIErrorReason } from '../errors.js';\nimport type { AIActionType, AIModel, AIProviderDescriptor } from '../models/model.js';\nimport type {\n\tAIChatMessage,\n\tAIChatMessageRole,\n\tAIFinishReason,\n\tAIProvider,\n\tAIProviderResponse,\n\tAIResponseFormat,\n\tAIToolCall,\n\tAIToolDefinition,\n\tJSONSchema,\n} from '../models/provider.js';\nimport { getActionName, getReducedMaxInputTokens, getValidatedTemperature } from '../utils/ai.utils.js';\nimport type { AIProviderContext } from './context.js';\nimport { isResponseFormatRejected, rememberResponseFormatRejection } from './responseFormatCache.js';\n\n// Native-format rejection wording varies by provider (\"response_format\", \"structured outputs\",\n// Gemini's \"Json mode is not enabled\", and its OpenAI-compat layer's `generation_config.response_schema`\n// path in INVALID_ARGUMENT bodies, ...)\nconst formatRejectionRegex =\n\t/response[_ ]?(?:format|schema)|structured[_ ]?output|output_config|json_schema|json[_ ]?mode/i;\n\nfunction getRequestErrorMessage(action: AIActionType, providerName: string, message: string): string {\n\tconst args = { provider: providerName, message: message };\n\tswitch (action) {\n\t\tcase 'explain-changes':\n\t\t\treturn l10n.t('Unable to Explain Changes: ({provider}) {message}', args);\n\t\tcase 'review-changes':\n\t\t\treturn l10n.t('Unable to Review Changes: ({provider}) {message}', args);\n\t\tcase 'review-orient':\n\t\t\treturn l10n.t('Unable to Orient Changes: ({provider}) {message}', args);\n\t\tcase 'generate-commitMessage':\n\t\t\treturn l10n.t('Unable to Generate Commit Message: ({provider}) {message}', args);\n\t\tcase 'generate-stashMessage':\n\t\t\treturn l10n.t('Unable to Generate Stash Message: ({provider}) {message}', args);\n\t\tcase 'generate-changelog':\n\t\t\treturn l10n.t('Unable to Generate Changelog: ({provider}) {message}', args);\n\t\tcase 'generate-create-cloudPatch':\n\t\t\treturn l10n.t('Unable to Create Cloud Patch Details: ({provider}) {message}', args);\n\t\tcase 'generate-create-pullRequest':\n\t\t\treturn l10n.t('Unable to Create Pull Request Details: ({provider}) {message}', args);\n\t\tcase 'generate-commits':\n\t\t\treturn l10n.t('Unable to Generate Commits: ({provider}) {message}', args);\n\t\tcase 'conflict-resolution':\n\t\t\treturn l10n.t('Unable to Resolve Conflicts (Preview): ({provider}) {message}', args);\n\t\tcase 'generate-searchQuery':\n\t\t\treturn l10n.t('Unable to Generate Search Query: ({provider}) {message}', args);\n\t}\n}\n\nexport abstract class OpenAICompatibleProviderBase<T extends AIProviders> implements AIProvider<T> {\n\tconstructor(protected readonly context: AIProviderContext) {}\n\n\tdispose(): void {}\n\t[Symbol.dispose](): void {\n\t\tthis.dispose();\n\t}\n\n\tabstract readonly id: T;\n\tabstract readonly name: string;\n\tprotected abstract readonly descriptor: AIProviderDescriptor<T>;\n\tprotected abstract readonly config: { keyUrl?: string; keyValidator?: RegExp };\n\n\tasync configured(silent: boolean): Promise<boolean> {\n\t\ttry {\n\t\t\tconst apiKey = await this.getApiKey(silent);\n\t\t\treturn apiKey != null;\n\t\t} catch (ex) {\n\t\t\tif (isCancellationError(ex)) return false;\n\n\t\t\tthrow ex;\n\t\t}\n\t}\n\n\tasync getApiKey(silent: boolean): Promise<string | undefined> {\n\t\tconst orgConf = this.context.getProviderConfig(this.id);\n\t\tif (!orgConf.enabled) return undefined;\n\t\tif (orgConf.key) return orgConf.key;\n\n\t\tconst { keyUrl, keyValidator } = this.config;\n\n\t\treturn this.context.getApiKey(\n\t\t\t{\n\t\t\t\tid: this.id,\n\t\t\t\tname: this.name,\n\t\t\t\trequiresAccount: this.descriptor.requiresAccount,\n\t\t\t\tvalidator: keyValidator != null ? v => keyValidator.test(v) : () => true,\n\t\t\t\turl: keyUrl,\n\t\t\t},\n\t\t\tsilent,\n\t\t);\n\t}\n\n\tabstract getModels(): Promise<readonly AIModel<T>[]>;\n\n\tprotected isResponseFormatSessionRejected(model: AIModel<T>, responseFormat: AIResponseFormat): boolean {\n\t\treturn isResponseFormatRejected(this.id, model, responseFormat);\n\t}\n\n\tprotected rememberResponseFormatRejection(model: AIModel<T>, responseFormat: AIResponseFormat): void {\n\t\trememberResponseFormatRejection(this.id, model, responseFormat);\n\t}\n\n\tprotected abstract getUrl(_model: AIModel<T>): string | undefined;\n\n\tprotected getHeaders<TAction extends AIActionType>(\n\t\t_action: TAction,\n\t\tapiKey: string,\n\t\t_model: AIModel<T>,\n\t\t_url: string,\n\t\t// Deliberately unused here: only the GitKraken provider forwards the conversation ID (as\n\t\t// `GK-Conversation-ID`); it must never reach third-party APIs.\n\t\t_conversationId?: string,\n\t): Record<string, string> | Promise<Record<string, string>> {\n\t\treturn {\n\t\t\tAccept: 'application/json',\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t};\n\t}\n\n\tasync sendRequest<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\tgetMessages: (maxInputTokens: number, retries: number) => Promise<AIChatMessage<AIChatMessageRole>[]>,\n\t\toptions: {\n\t\t\tsignal: AbortSignal;\n\t\t\tmodelOptions?: { outputTokens?: number; temperature?: number };\n\t\t\tconversationId?: string;\n\t\t\tresponseFormat?: AIResponseFormat;\n\t\t\ttools?: readonly AIToolDefinition[];\n\t\t},\n\t): Promise<AIProviderResponse<void> | undefined> {\n\t\tusing scope = maybeStartScopedLogger(`${getLoggableName(this)}.sendRequest`);\n\n\t\ttry {\n\t\t\tconst result = await this.fetch(\n\t\t\t\taction,\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\tgetMessages,\n\t\t\t\toptions.modelOptions,\n\t\t\t\toptions.responseFormat,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.conversationId,\n\t\t\t\toptions.tools,\n\t\t\t);\n\t\t\treturn result;\n\t\t} catch (ex) {\n\t\t\tif (isCancellationError(ex)) {\n\t\t\t\tscope?.error(ex, `Cancelled request to ${getActionName(action)}: (${model.provider.name})`);\n\t\t\t\tthrow ex;\n\t\t\t}\n\n\t\t\tscope?.error(ex, `Unable to ${getActionName(action)}: (${model.provider.name})`);\n\t\t\tif (ex instanceof AIError) throw ex;\n\n\t\t\tdebugger;\n\t\t\tthrow new Error(getRequestErrorMessage(action, model.provider.name, ex.message), { cause: ex });\n\t\t}\n\t}\n\n\tprotected async fetch<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\tmessages: (maxInputTokens: number, retries: number) => Promise<AIChatMessage<AIChatMessageRole>[]>,\n\t\tmodelOptions?: { outputTokens?: number; temperature?: number },\n\t\tresponseFormat?: AIResponseFormat,\n\t\tsignal?: AbortSignal,\n\t\tconversationId?: string,\n\t\ttools?: readonly AIToolDefinition[],\n\t): Promise<AIProviderResponse<void>> {\n\t\tlet retries = 0;\n\t\tlet maxInputTokens = model.maxTokens.input;\n\t\t// Latched when the provider rejects the `tools` field, so the retry drops tools entirely and\n\t\t// the caller can stop offering them for the rest of the session.\n\t\tlet toolsRejected = false;\n\n\t\twhile (true) {\n\t\t\tconst useTools = tools?.length && !toolsRejected ? tools : undefined;\n\t\t\tconst { messages: msgs, system } = this.extractSystemPrompt(await messages(maxInputTokens, retries));\n\t\t\tconst request: ChatCompletionRequest = {\n\t\t\t\tmodel: model.id,\n\t\t\t\tmessages: this.serializeMessages(msgs),\n\t\t\t\t...(system != null ? { system: system } : undefined),\n\t\t\t\t...(useTools != null ? this.serializeTools(useTools) : undefined),\n\t\t\t\tstream: false,\n\t\t\t\tmax_completion_tokens: model.maxTokens.output\n\t\t\t\t\t? Math.min(modelOptions?.outputTokens ?? Infinity, model.maxTokens.output)\n\t\t\t\t\t: modelOptions?.outputTokens,\n\t\t\t\ttemperature: getValidatedTemperature(\n\t\t\t\t\tmodel,\n\t\t\t\t\tmodelOptions?.temperature ?? model.temperature,\n\t\t\t\t\tthis.context.defaultTemperature,\n\t\t\t\t),\n\t\t\t};\n\t\t\tif (\n\t\t\t\tresponseFormat != null &&\n\t\t\t\t!this.isResponseFormatSessionRejected(model, responseFormat) &&\n\t\t\t\tthis.supportsResponseFormat(model)\n\t\t\t) {\n\t\t\t\tthis.applyResponseFormat(request, model, responseFormat);\n\t\t\t}\n\n\t\t\tlet rsp = await this.fetchCore(action, model, apiKey, request, signal, conversationId);\n\t\t\t// Read once and forward to `handleFetchFailure` so the error body isn't decoded twice\n\t\t\tlet errorBody: string | undefined;\n\t\t\tif (!rsp.ok && (request.response_format != null || request.output_config != null)) {\n\t\t\t\t// If the native format was rejected (stale model snapshot, older Azure api-version,\n\t\t\t\t// proxy converter gaps, OpenRouter's require_parameters matching no endpoint), strip\n\t\t\t\t// it and resend the same request — the prompt still describes the JSON. Resending\n\t\t\t\t// directly avoids re-running the (non-idempotent) prompt build and its side effects\n\t\t\t\t// Leave it `undefined` (not '') when the read fails, so `handleFetchFailure` falls\n\t\t\t\t// back to reading the still-unconsumed response instead of parsing an empty string\n\t\t\t\terrorBody = await rsp\n\t\t\t\t\t.clone()\n\t\t\t\t\t.text()\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t\tif (this.isResponseFormatRejection(rsp.status, errorBody ?? '')) {\n\t\t\t\t\tLogger.warn(\n\t\t\t\t\t\t`(${this.name}) ${model.id}: native response format was rejected (${rsp.status}); retrying without it`,\n\t\t\t\t\t);\n\t\t\t\t\tconst rejected = responseFormat;\n\t\t\t\t\tresponseFormat = undefined;\n\t\t\t\t\tdelete request.response_format;\n\t\t\t\t\tdelete request.output_config;\n\t\t\t\t\tdelete request.provider;\n\t\t\t\t\trsp = await this.fetchCore(action, model, apiKey, request, signal, conversationId);\n\t\t\t\t\terrorBody = undefined;\n\t\t\t\t\t// Memoize only when stripping fixed it — proof the format (not e.g. an oversized\n\t\t\t\t\t// prompt behind the same wrapped status) caused the failure\n\t\t\t\t\tif (rsp.ok && rejected != null) {\n\t\t\t\t\t\tthis.rememberResponseFormatRejection(model, rejected);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!rsp.ok) {\n\t\t\t\tconst result = await this.handleFetchFailure(\n\t\t\t\t\trsp,\n\t\t\t\t\taction,\n\t\t\t\t\tmodel,\n\t\t\t\t\tretries,\n\t\t\t\t\tmaxInputTokens,\n\t\t\t\t\terrorBody,\n\t\t\t\t\tuseTools != null,\n\t\t\t\t);\n\t\t\t\tif (result.retry) {\n\t\t\t\t\tmaxInputTokens = result.maxInputTokens;\n\t\t\t\t\tif (result.withoutTools) {\n\t\t\t\t\t\t// Say so explicitly: the caller degrades silently by design, so the only remaining\n\t\t\t\t\t\t// evidence would be `toolCalls=0` — indistinguishable from a model that simply chose\n\t\t\t\t\t\t// not to consult the repository. That ambiguity is the whole reason to log it.\n\t\t\t\t\t\tLogger.warn(\n\t\t\t\t\t\t\t`(${this.name}) ${model.id}: tools were rejected (${rsp.status}); retrying without them — repository consultation is unavailable for the rest of this session`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttoolsRejected = true;\n\t\t\t\t\t}\n\t\t\t\t\tretries++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst data: ChatCompletionResponse = (await rsp.json()) as ChatCompletionResponse;\n\t\t\tconst toolCalls = this.parseToolCalls(data);\n\t\t\t// A tool-call-only turn carries no text, which `extractContent` correctly reports as '' — it\n\t\t\t// selects the text block by type, so a `tool_use` (or thinking) block is never mistaken for one.\n\t\t\t// The calls ride alongside on `toolCalls` below.\n\t\t\tconst content = this.extractContent(data);\n\t\t\t// Some providers/proxies (e.g. OpenRouter) report upstream failures as an OK response\n\t\t\t// carrying an error envelope and no choices — surface that instead of empty content\n\t\t\tif (!content && toolCalls == null && data.error != null) {\n\t\t\t\tif (data.error.code === 429 || data.error.code === '429') {\n\t\t\t\t\tthrow new AIError(\n\t\t\t\t\t\tAIErrorReason.RateLimitOrFundsExceeded,\n\t\t\t\t\t\tnew Error(`(${this.name}) ${data.error.message || 'Rate limit exceeded'}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`(${this.name}) ${data.error.message || 'Unknown error'}`);\n\t\t\t}\n\n\t\t\tconst result: AIProviderResponse<void> = {\n\t\t\t\tid: data.id ?? uuid(),\n\t\t\t\tcontent: content,\n\t\t\t\tfinishReason: this.extractFinishReason(data),\n\t\t\t\tmodel: model,\n\t\t\t\t...(toolCalls?.length ? { toolCalls: toolCalls } : undefined),\n\t\t\t\t...(toolsRejected ? { toolsRejected: true } : undefined),\n\t\t\t\tusage: {\n\t\t\t\t\tpromptTokens: data.usage?.prompt_tokens ?? data.usage?.input_tokens,\n\t\t\t\t\tcompletionTokens: data.usage?.completion_tokens ?? data.usage?.output_tokens,\n\t\t\t\t\ttotalTokens: data.usage?.total_tokens,\n\t\t\t\t\tlimits:\n\t\t\t\t\t\tdata?.usage?.gk != null\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tused: data.usage.gk.used,\n\t\t\t\t\t\t\t\t\tlimit: data.usage.gk.limit,\n\t\t\t\t\t\t\t\t\tresetsOn: new Date(data.usage.gk.resets_on),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tresult: undefined,\n\t\t\t};\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the message-related request fields. The default sends every message inline (OpenAI\n\t * Chat Completions semantics); providers whose API carries the initial system prompt separately\n\t * (e.g. Anthropic's top-level `system`) override this to extract it from the messages.\n\t */\n\tprotected extractSystemPrompt(messages: AIChatMessage<AIChatMessageRole>[]): {\n\t\tmessages: AIChatMessage<AIChatMessageRole>[];\n\t\tsystem?: string;\n\t} {\n\t\treturn { messages: messages };\n\t}\n\n\t/** Whether the given model accepts a native response-format/schema field; when false the\n\t * prompt's JSON description is the only format control (the request is unchanged).\n\t * Dynamic-catalog providers (GitKraken, OpenRouter) populate\n\t * {@link AIModel.supportsStructuredOutputs}; static providers override with id-based gates */\n\tprotected supportsResponseFormat(model: AIModel<T>): boolean {\n\t\treturn model.supportsStructuredOutputs ?? true;\n\t}\n\n\t/**\n\t * Whether a failed response reads as a rejection of the `tools` field rather than a problem with the\n\t * prompt — the trigger for one retry without tools, so a tool-using feature degrades to single-shot\n\t * instead of failing outright.\n\t *\n\t * Providers that wrap upstream rejections in their own envelope (e.g. GitKraken) must override this:\n\t * the wrapper's prose names neither \"tool\" nor \"function\", so the text match here cannot see through\n\t * it and the fallback would never fire.\n\t */\n\tprotected isToolsRejection(status: number, message: string | undefined): boolean {\n\t\tif (status !== 400 || !message) return false;\n\n\t\tconst m = message.toLowerCase();\n\t\treturn (\n\t\t\t(m.includes('tool') || m.includes('function')) &&\n\t\t\t(m.includes('unsupported') ||\n\t\t\t\tm.includes('not supported') ||\n\t\t\t\tm.includes('unknown') ||\n\t\t\t\tm.includes('unrecognized') ||\n\t\t\t\tm.includes('invalid') ||\n\t\t\t\tm.includes('unexpected'))\n\t\t);\n\t}\n\n\t/** Whether a failed response means the native response format itself was rejected — the\n\t * trigger for stripping it and retrying via the prompt-described JSON. Providers that wrap\n\t * upstream rejections in their own envelope (e.g. GitKraken) extend this */\n\tprotected isResponseFormatRejection(status: number, body: string): boolean {\n\t\treturn (\n\t\t\t(status === 400 && formatRejectionRegex.test(body)) ||\n\t\t\t// OpenRouter answers 404 when `require_parameters` matches no serving endpoint\n\t\t\t(status === 404 && /no endpoints found/i.test(body))\n\t\t);\n\t}\n\n\t/** Translates the canonical response format onto the request; called only when\n\t * {@link supportsResponseFormat} allows it. Base emits the OpenAI `response_format.json_schema`\n\t * envelope. Overrides must REPLACE this for providers with a different native field\n\t * (e.g. Anthropic `output_config`) — never leave both on the request. */\n\tprotected applyResponseFormat(\n\t\trequest: ChatCompletionRequest,\n\t\t_model: AIModel<T>,\n\t\tresponseFormat: AIResponseFormat,\n\t): void {\n\t\trequest.response_format = {\n\t\t\ttype: 'json_schema',\n\t\t\tjson_schema: {\n\t\t\t\tname: responseFormat.name,\n\t\t\t\tstrict: true,\n\t\t\t\tschema: responseFormat.schema,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Finds the text block by type rather than position — with some Anthropic models (e.g. Sonnet 5,\n\t// where thinking runs by default) a thinking block can precede the text block\n\tprotected extractContent(data: ChatCompletionResponse): string {\n\t\treturn (\n\t\t\tdata.choices?.[0]?.message?.content?.trim() ??\n\t\t\tdata.content?.find(b => b.type === 'text')?.text?.trim() ??\n\t\t\t''\n\t\t);\n\t}\n\n\t/** Normalizes abnormal completion signals (all arrive as HTTP 200) so consumers can\n\t * distinguish truncated/filtered/refused output from a malformed-but-complete reply */\n\tprotected extractFinishReason(data: ChatCompletionResponse): AIFinishReason | undefined {\n\t\tconst choice = data.choices?.[0];\n\t\tif (choice != null) {\n\t\t\t// Truthy check — some OpenAI-compatible servers serialize `\"refusal\": \"\"` on normal replies\n\t\t\tif (choice.message?.refusal) return 'refusal';\n\t\t\tif (choice.finish_reason === 'length') return 'length';\n\t\t\tif (choice.finish_reason === 'content_filter') return 'content_filter';\n\t\t\treturn undefined;\n\t\t}\n\n\t\tswitch (data.stop_reason) {\n\t\t\t// `model_context_window_exceeded` means the context filled before the output limit — the\n\t\t\t// reply is truncated all the same\n\t\t\tcase 'max_tokens':\n\t\t\tcase 'model_context_window_exceeded':\n\t\t\t\treturn 'length';\n\t\t\tcase 'refusal':\n\t\t\t\treturn 'refusal';\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Maps messages onto the provider's wire shape. The default is OpenAI Chat Completions: assistant\n\t * tool calls go in `tool_calls` with `arguments` JSON-stringified, and tool results are `tool`-role\n\t * entries keyed by `tool_call_id`. Providers with a different tool encoding (e.g. Anthropic's\n\t * content blocks) override this.\n\t */\n\tprotected serializeMessages(messages: AIChatMessage<AIChatMessageRole>[]): unknown[] {\n\t\treturn messages.map(m => {\n\t\t\tif (m.role === 'tool') {\n\t\t\t\t// A tool result is only addressable by the id of the call it answers. Without one, send it\n\t\t\t\t// as plain text — the same shape used for providers that can't carry tool calls at all —\n\t\t\t\t// rather than a `tool_call_id: undefined` the provider rejects with nothing to trace it to.\n\t\t\t\tif (m.toolCallId == null) return { role: 'user', content: m.content };\n\n\t\t\t\treturn { role: 'tool', tool_call_id: m.toolCallId, content: m.content };\n\t\t\t}\n\n\t\t\tif (m.role === 'assistant' && m.toolCalls?.length) {\n\t\t\t\treturn {\n\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t// OpenAI requires `content` to be present, but allows null on a tool-call-only turn\n\t\t\t\t\tcontent: m.content || null,\n\t\t\t\t\ttool_calls: m.toolCalls.map(c => ({\n\t\t\t\t\t\tid: c.id,\n\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\tfunction: { name: c.name, arguments: JSON.stringify(c.args) },\n\t\t\t\t\t\t// Only the GitKraken proxy mints these, so the field can only ever be present on a\n\t\t\t\t\t\t// conversation with that proxy — no other provider sees it.\n\t\t\t\t\t\t...(c.providerSignature != null ? { thought_signature: c.providerSignature } : undefined),\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn { role: m.role, content: m.content };\n\t\t});\n\t}\n\n\t/** Returns the tool-related request fields. The default is the OpenAI `function` envelope. */\n\tprotected serializeTools(tools: readonly AIToolDefinition[]): { tools: unknown[] } {\n\t\treturn {\n\t\t\ttools: tools.map(t => ({\n\t\t\t\ttype: 'function',\n\t\t\t\tfunction: { name: t.name, description: t.description, parameters: t.parameters },\n\t\t\t})),\n\t\t};\n\t}\n\n\t/**\n\t * Extracts tool calls from a response, handling both the OpenAI shape\n\t * (`choices[].message.tool_calls`, whose `arguments` is a JSON string) and the Anthropic shape\n\t * (`content[]` blocks of type `tool_use`) — mirroring how {@link fetch} already reads content\n\t * from both.\n\t */\n\tprotected parseToolCalls(data: ChatCompletionResponse): AIToolCall[] | undefined {\n\t\tconst calls: AIToolCall[] = [];\n\n\t\tfor (const call of data.choices?.[0]?.message?.tool_calls ?? []) {\n\t\t\tlet args: Record<string, unknown> = {};\n\t\t\ttry {\n\t\t\t\t// Providers can emit '' for a no-argument call\n\t\t\t\targs = call.function.arguments ? (JSON.parse(call.function.arguments) as Record<string, unknown>) : {};\n\t\t\t} catch {\n\t\t\t\t// Leave args empty — the tool dispatcher reports the resulting validation error back to\n\t\t\t\t// the model, which is more recoverable than failing the whole request here.\n\t\t\t}\n\n\t\t\tcalls.push({\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.function.name,\n\t\t\t\targs: args,\n\t\t\t\t...(call.thought_signature != null ? { providerSignature: call.thought_signature } : undefined),\n\t\t\t});\n\t\t}\n\n\t\tfor (const block of data.content ?? []) {\n\t\t\tif (block.type !== 'tool_use' || block.id == null || block.name == null) continue;\n\n\t\t\tcalls.push({ id: block.id, name: block.name, args: block.input ?? {} });\n\t\t}\n\n\t\treturn calls.length ? calls : undefined;\n\t}\n\n\tprotected async handleFetchFailure<TAction extends AIActionType>(\n\t\trsp: Response,\n\t\t_action: TAction,\n\t\tmodel: AIModel<T>,\n\t\tretries: number,\n\t\tmaxInputTokens: number,\n\t\t/** The already-read error body, when the caller had to read it (avoids a second decode) */\n\t\tbody?: string,\n\t\tsentTools?: boolean,\n\t): Promise<{ retry: true; maxInputTokens: number; withoutTools?: boolean }> {\n\t\tif (rsp.status === 404) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\tnew Error(`Your API key doesn't seem to have access to the selected '${model.id}' model`),\n\t\t\t);\n\t\t}\n\t\tif (rsp.status === 429) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.RateLimitOrFundsExceeded,\n\t\t\t\tnew Error(\n\t\t\t\t\t`(${this.name}) ${rsp.status}: Too many requests (rate limit exceeded) or your account is out of funds`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = (body != null ? JSON.parse(body) : await rsp.json()) as\n\t\t\t\t| { error?: { code: string; message: string } }\n\t\t\t\t| undefined;\n\t\t} catch {}\n\n\t\tif (Array.isArray(json)) {\n\t\t\tjson = json[0];\n\t\t}\n\n\t\t// A revoked/invalid key or no access: AI is unavailable to this user, not a one-off failure.\n\t\t// Neither retry probe below can apply — both only match a 400 (or the OpenRouter 404 handled above)\n\t\tif (rsp.status === 401 || rsp.status === 403) {\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.Unauthorized,\n\t\t\t\tnew Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`),\n\t\t\t);\n\t\t}\n\n\t\tif (json?.error?.code === 'context_length_exceeded') {\n\t\t\tif (retries < 3) {\n\t\t\t\treturn { retry: true, maxInputTokens: getReducedMaxInputTokens(maxInputTokens, retries + 1) };\n\t\t\t}\n\n\t\t\tthrow new AIError(\n\t\t\t\tAIErrorReason.RequestTooLarge,\n\t\t\t\tnew Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`),\n\t\t\t);\n\t\t}\n\n\t\t// A provider that advertises the OpenAI shape but rejects `tools` (an older or partial\n\t\t// implementation) gets one retry without them, so the caller degrades to text-only instead of\n\t\t// failing outright.\n\t\tif (sentTools && this.isToolsRejection(rsp.status, json?.error?.message)) {\n\t\t\treturn { retry: true, maxInputTokens: maxInputTokens, withoutTools: true };\n\t\t}\n\n\t\tthrow new Error(`(${this.name}) ${rsp.status}: ${json?.error?.message || rsp.statusText}`);\n\t}\n\n\tprotected async fetchCore<TAction extends AIActionType>(\n\t\taction: TAction,\n\t\tmodel: AIModel<T>,\n\t\tapiKey: string,\n\t\trequest: object,\n\t\tsignal: AbortSignal | undefined,\n\t\tconversationId?: string,\n\t): Promise<Response> {\n\t\tconst url = this.getUrl(model);\n\t\tif (!url) {\n\t\t\tthrow new Error(`(${this.name}) ${getActionName(action)}: No URL configured`);\n\t\t}\n\n\t\tconst body = JSON.stringify(request);\n\n\t\t// A rejected request is otherwise undiagnosable: a proxying backend reports only its own\n\t\t// \"upstream AI provider error (<provider> HTTP <status>)\", so which field the upstream objected to\n\t\t// can only be inferred. Log the request's shape — which fields were sent, and how much — but not\n\t\t// the messages, which carry the user's source code.\n\t\tLogger.trace(\n\t\t\t`(${this.name}) ${getActionName(action)} → ${model.id}: fields=[${Object.keys(request)\n\t\t\t\t.sort()\n\t\t\t\t.join(',')}] bytes=${body.length}`,\n\t\t);\n\n\t\ttry {\n\t\t\treturn await this.context.fetch(url, {\n\t\t\t\theaders: await this.getHeaders(action, apiKey, model, url, conversationId),\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: body,\n\t\t\t\tsignal: signal,\n\t\t\t});\n\t\t} catch (ex) {\n\t\t\tif (ex.name === 'AbortError') throw new CancellationError(ex);\n\t\t\tthrow ex;\n\t\t}\n\t}\n}\n\nexport interface ChatCompletionRequest {\n\tmodel: string;\n\t/** Provider-shaped messages from {@link OpenAICompatibleProviderBase.serializeMessages} */\n\tmessages: unknown[];\n\n\t/** Anthropic carries the initial system prompt here instead of as a `system`-role message */\n\tsystem?: string;\n\n\t/** Tool definitions, shaped by {@link OpenAICompatibleProviderBase.serializeTools} */\n\ttools?: unknown[];\n\n\t/** @deprecated but used by Anthropic & Gemini */\n\tmax_tokens?: number;\n\t/** Currently can't be used for Anthropic & Gemini */\n\tmax_completion_tokens?: number;\n\tmetadata?: Record<string, string>;\n\tstream?: boolean;\n\ttemperature?: number;\n\ttop_p?: number;\n\n\t/** Not supported by many models/providers */\n\treasoning_effort?: 'low' | 'medium' | 'high';\n\n\t/** OpenAI-compatible structured output (set via {@link OpenAICompatibleProviderBase.applyResponseFormat}) */\n\tresponse_format?: { type: 'json_schema'; json_schema: { name: string; strict: boolean; schema: JSONSchema } };\n\t/** Anthropic-native structured output (set only by the Anthropic override) */\n\toutput_config?: { format: { type: 'json_schema'; schema: JSONSchema } };\n\t/** OpenRouter-only routing constraint (set only by the OpenRouter override) */\n\tprovider?: { require_parameters: boolean };\n}\n\nexport interface ChatCompletionResponse {\n\tid: string;\n\tmodel: string;\n\t/** OpenAI compatible output */\n\tchoices?: {\n\t\tindex: number;\n\t\tmessage: {\n\t\t\trole: string;\n\t\t\tcontent: string | null;\n\t\t\t/** OpenAI-only; most OpenAI-compatible servers omit it entirely */\n\t\t\trefusal?: string | null;\n\t\t\ttool_calls?: {\n\t\t\t\tid: string;\n\t\t\t\ttype: string;\n\t\t\t\tfunction: { name: string; arguments: string };\n\t\t\t\t/** GitKraken proxy only — an opaque provider reasoning token to round-trip */\n\t\t\t\tthought_signature?: string;\n\t\t\t}[];\n\t\t};\n\t\tfinish_reason: string;\n\t}[];\n\t/** Anthropic output (non-text blocks, e.g. thinking, carry no text). `tool_use` blocks add the\n\t * call fields, which is why `id`/`name` are optional here — {@link parseToolCalls} narrows on\n\t * `type` and then checks them. */\n\tcontent?: { type: string; text?: string; id?: string; name?: string; input?: Record<string, unknown> }[];\n\t/** Error envelope some providers/proxies return with an OK status (e.g. OpenRouter upstream failures) */\n\terror?: { message?: string; code?: number | string } | null;\n\t/** Anthropic stop reason */\n\tstop_reason?: string;\n\tusage: {\n\t\t/** OpenAI compatible */\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\ttotal_tokens?: number;\n\n\t\t/** Anthropic */\n\t\tinput_tokens?: number;\n\t\toutput_tokens?: number;\n\n\t\t/** GitKraken */\n\t\tgk: {\n\t\t\tused: number;\n\t\t\tlimit: number;\n\t\t\tresets_on: string;\n\t\t};\n\t};\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,uBACL;AAED,SAAS,uBAAuB,QAAsB,cAAsB,SAAyB;CACpG,MAAM,OAAO;EAAE,UAAU;EAAuB;CAAQ;CACxD,QAAQ,QAAR;EACC,KAAK,mBACJ,OAAO,KAAK,EAAE,qDAAqD,IAAI;EACxE,KAAK,kBACJ,OAAO,KAAK,EAAE,oDAAoD,IAAI;EACvE,KAAK,iBACJ,OAAO,KAAK,EAAE,oDAAoD,IAAI;EACvE,KAAK,0BACJ,OAAO,KAAK,EAAE,6DAA6D,IAAI;EAChF,KAAK,yBACJ,OAAO,KAAK,EAAE,4DAA4D,IAAI;EAC/E,KAAK,sBACJ,OAAO,KAAK,EAAE,wDAAwD,IAAI;EAC3E,KAAK,8BACJ,OAAO,KAAK,EAAE,gEAAgE,IAAI;EACnF,KAAK,+BACJ,OAAO,KAAK,EAAE,iEAAiE,IAAI;EACpF,KAAK,oBACJ,OAAO,KAAK,EAAE,sDAAsD,IAAI;EACzE,KAAK,uBACJ,OAAO,KAAK,EAAE,iEAAiE,IAAI;EACpF,KAAK,wBACJ,OAAO,KAAK,EAAE,2DAA2D,IAAI;CAC/E;AACD;AAEA,IAAsB,+BAAtB,MAAmG;CACnE;CAA/B,YAAY,SAA+C;EAA5B,KAAA,UAAA;CAA6B;CAE5D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2BAA2B;GACpD,IAAI,UAAU,GACb,OAAO;IAAE,OAAO;IAAM,gBAAgB,yBAAyB,gBAAgB,UAAU,CAAC;GAAE;GAG7F,MAAM,IAAI,QAAA,mBAET,IAAI,MAAM,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,IAAI,MAAM,OAAO,WAAW,IAAI,YAAY,CACpF;EACD;EAKA,IAAI,aAAa,KAAK,iBAAiB,IAAI,QAAQ,MAAM,OAAO,OAAO,GACtE,OAAO;GAAE,OAAO;GAAsB;GAAgB,cAAc;EAAK;EAG1E,MAAM,IAAI,MAAM,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,IAAI,MAAM,OAAO,WAAW,IAAI,YAAY;CAC1F;CAEA,MAAgB,UACf,QACA,OACA,QACA,SACA,QACA,gBACoB;EACpB,MAAM,MAAM,KAAK,OAAO,KAAK;EAC7B,IAAI,CAAC,KACJ,MAAM,IAAI,MAAM,IAAI,KAAK,KAAK,IAAI,cAAc,MAAM,EAAE,oBAAoB;EAG7E,MAAM,OAAO,KAAK,UAAU,OAAO;EAMnC,QAAO,MACN,IAAI,KAAK,KAAK,IAAI,cAAc,MAAM,EAAE,KAAK,MAAM,GAAG,YAAY,OAAO,KAAK,OAAO,CAAC,CACpF,KAAK,CAAC,CACN,KAAK,GAAG,EAAE,UAAU,KAAK,QAC5B;EAEA,IAAI;GACH,OAAO,MAAM,KAAK,QAAQ,MAAM,KAAK;IACpC,SAAS,MAAM,KAAK,WAAW,QAAQ,QAAQ,OAAO,KAAK,cAAc;IACzE,QAAQ;IACF;IACE;GACT,CAAC;EACF,SAAS,IAAI;GACZ,IAAI,GAAG,SAAS,cAAc,MAAM,IAAI,kBAAkB,EAAE;GAC5D,MAAM;EACP;CACD;AACD"}
|
|
@@ -4,6 +4,10 @@ import { AIFinishReason } from "../models/provider.js";
|
|
|
4
4
|
/** Whether the model declined to fulfill the request (refused or content-filtered) */
|
|
5
5
|
export declare function didModelDecline(finishReason: AIFinishReason | undefined): boolean;
|
|
6
6
|
export declare function getActionName(action: AIActionType): string;
|
|
7
|
+
/** The action name the GitKraken backend validates and bills requests under. Orient is a depth of the
|
|
8
|
+
* review feature, so it travels as `review-changes` — the backend knows no finer-grained action, and
|
|
9
|
+
* Start Review already sends one action for its overview and detail templates. */
|
|
10
|
+
export declare function getBackendActionType(action: AIActionType): AIActionType;
|
|
7
11
|
export declare const estimatedCharactersPerToken = 2.8;
|
|
8
12
|
export declare function getValidatedTemperature(model: AIModel, modelTemperature?: number | null, defaultTemperature?: number): number | undefined;
|
|
9
13
|
/**
|
|
@@ -7,6 +7,7 @@ function getActionName(action) {
|
|
|
7
7
|
switch (action) {
|
|
8
8
|
case "explain-changes": return "Explain Changes";
|
|
9
9
|
case "review-changes": return "Review Changes";
|
|
10
|
+
case "review-orient": return "Orient Changes";
|
|
10
11
|
case "generate-commitMessage": return "Generate Commit Message";
|
|
11
12
|
case "generate-stashMessage": return "Generate Stash Message";
|
|
12
13
|
case "generate-changelog": return "Generate Changelog";
|
|
@@ -17,6 +18,12 @@ function getActionName(action) {
|
|
|
17
18
|
case "generate-searchQuery": return "Generate Search Query";
|
|
18
19
|
}
|
|
19
20
|
}
|
|
21
|
+
/** The action name the GitKraken backend validates and bills requests under. Orient is a depth of the
|
|
22
|
+
* review feature, so it travels as `review-changes` — the backend knows no finer-grained action, and
|
|
23
|
+
* Start Review already sends one action for its overview and detail templates. */
|
|
24
|
+
function getBackendActionType(action) {
|
|
25
|
+
return action === "review-orient" ? "review-changes" : action;
|
|
26
|
+
}
|
|
20
27
|
const estimatedCharactersPerToken = 2.8;
|
|
21
28
|
function getValidatedTemperature(model, modelTemperature, defaultTemperature) {
|
|
22
29
|
if (model.temperature === null) return void 0;
|
|
@@ -53,6 +60,6 @@ function getReducedMaxInputTokens(maxInputTokens, retryCount, estimatedTokens) {
|
|
|
53
60
|
}
|
|
54
61
|
}
|
|
55
62
|
//#endregion
|
|
56
|
-
export { didModelDecline, estimatedCharactersPerToken, getActionName, getReducedMaxInputTokens, getValidatedTemperature, isAzureUrl };
|
|
63
|
+
export { didModelDecline, estimatedCharactersPerToken, getActionName, getBackendActionType, getReducedMaxInputTokens, getValidatedTemperature, isAzureUrl };
|
|
57
64
|
|
|
58
65
|
//# sourceMappingURL=ai.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.utils.js","names":[],"sources":["../../../../../plus/ai/src/utils/ai.utils.ts"],"sourcesContent":["import type { AIActionType, AIModel } from '../models/model.js';\nimport type { AIFinishReason } from '../models/provider.js';\n\n/** Whether the model declined to fulfill the request (refused or content-filtered) */\nexport function didModelDecline(finishReason: AIFinishReason | undefined): boolean {\n\treturn finishReason === 'refusal' || finishReason === 'content_filter';\n}\n\nexport function getActionName(action: AIActionType): string {\n\tswitch (action) {\n\t\tcase 'explain-changes':\n\t\t\treturn 'Explain Changes';\n\t\tcase 'review-changes':\n\t\t\treturn 'Review Changes';\n\t\tcase 'generate-commitMessage':\n\t\t\treturn 'Generate Commit Message';\n\t\tcase 'generate-stashMessage':\n\t\t\treturn 'Generate Stash Message';\n\t\tcase 'generate-changelog':\n\t\t\treturn 'Generate Changelog';\n\t\tcase 'generate-create-cloudPatch':\n\t\t\treturn 'Create Cloud Patch Details';\n\t\tcase 'generate-create-pullRequest':\n\t\t\treturn 'Create Pull Request Details';\n\t\tcase 'generate-commits':\n\t\t\treturn 'Generate Commits';\n\t\tcase 'conflict-resolution':\n\t\t\treturn 'Resolve Conflicts (Preview)';\n\t\tcase 'generate-searchQuery':\n\t\t\treturn 'Generate Search Query';\n\t}\n}\n\nexport const estimatedCharactersPerToken = 2.8;\n\nexport function getValidatedTemperature(\n\tmodel: AIModel,\n\tmodelTemperature?: number | null,\n\tdefaultTemperature?: number,\n): number | undefined {\n\t// `temperature: null` on the model is a capability statement, not a default: the model rejects the\n\t// parameter (reasoning models, Anthropic Opus 4.7+/Sonnet 5, Gemini 3.x) or the catalog can't\n\t// promise it accepts one (every GitKraken-proxy and OpenRouter model). It therefore has to win over\n\t// a caller-supplied value — callers merge as `modelOptions?.temperature ?? model.temperature`, and\n\t// `0 ?? null` is `0`, so an explicit 0 would otherwise defeat the opt-out and be sent anyway.\n\t// It also covers upstreams the id check below can't see: a proxy model is `openai:gpt-5.6-…`, not\n\t// `gpt-5.6-…`, so `startsWith` misses it while the upstream still 400s on a non-default value.\n\tif (model.temperature === null) return undefined;\n\tif (modelTemperature === null) return undefined;\n\t// GPT5 doesn't support anything but the default temperature\n\tif (model.id.startsWith('gpt-5')) return undefined;\n\n\tmodelTemperature ??= Math.max(0, Math.min(defaultTemperature ?? 0.7, 2));\n\treturn modelTemperature;\n}\n\n/**\n * Calculates the reduced max input tokens for retry attempts when context length is exceeded.\n *\n * If `estimatedTokens` is provided, calculates based on the actual overage ratio.\n * Otherwise, uses a hybrid strategy: conservative fixed reduction, then escalating percentages.\n *\n * @param maxInputTokens - Current max input tokens limit\n * @param retryCount - Current retry attempt (1-based, use value after incrementing)\n * @param estimatedTokens - Optional: estimated tokens in the prompt (if known)\n * @returns New max input tokens value\n */\nexport function isAzureUrl(url: string): boolean {\n\treturn url.includes('.azure.com');\n}\n\nexport function getReducedMaxInputTokens(maxInputTokens: number, retryCount: number, estimatedTokens?: number): number {\n\t// If we know the estimated tokens, calculate reduction based on overage\n\tif (estimatedTokens != null && estimatedTokens > maxInputTokens) {\n\t\tconst overageRatio = estimatedTokens / maxInputTokens;\n\t\t// Target below the limit with some buffer (5-15% below based on retry)\n\t\tconst bufferPercent = 0.05 + retryCount * 0.05;\n\t\tconst targetRatio = 1 / overageRatio - bufferPercent;\n\t\treturn Math.floor(maxInputTokens * Math.max(0.5, targetRatio));\n\t}\n\n\t// Fallback: progressive reduction without knowing exact overage\n\tswitch (retryCount) {\n\t\tcase 1:\n\t\t\t// Conservative fixed reduction for small overages\n\t\t\treturn maxInputTokens - 1000;\n\t\tcase 2:\n\t\t\t// Moderate percentage-based reduction\n\t\t\treturn Math.floor(maxInputTokens * 0.9);\n\t\tc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;CACzC;AACD"}
|
|
1
|
+
{"version":3,"file":"ai.utils.js","names":[],"sources":["../../../../../plus/ai/src/utils/ai.utils.ts"],"sourcesContent":["import type { AIActionType, AIModel } from '../models/model.js';\nimport type { AIFinishReason } from '../models/provider.js';\n\n/** Whether the model declined to fulfill the request (refused or content-filtered) */\nexport function didModelDecline(finishReason: AIFinishReason | undefined): boolean {\n\treturn finishReason === 'refusal' || finishReason === 'content_filter';\n}\n\nexport function getActionName(action: AIActionType): string {\n\tswitch (action) {\n\t\tcase 'explain-changes':\n\t\t\treturn 'Explain Changes';\n\t\tcase 'review-changes':\n\t\t\treturn 'Review Changes';\n\t\tcase 'review-orient':\n\t\t\treturn 'Orient Changes';\n\t\tcase 'generate-commitMessage':\n\t\t\treturn 'Generate Commit Message';\n\t\tcase 'generate-stashMessage':\n\t\t\treturn 'Generate Stash Message';\n\t\tcase 'generate-changelog':\n\t\t\treturn 'Generate Changelog';\n\t\tcase 'generate-create-cloudPatch':\n\t\t\treturn 'Create Cloud Patch Details';\n\t\tcase 'generate-create-pullRequest':\n\t\t\treturn 'Create Pull Request Details';\n\t\tcase 'generate-commits':\n\t\t\treturn 'Generate Commits';\n\t\tcase 'conflict-resolution':\n\t\t\treturn 'Resolve Conflicts (Preview)';\n\t\tcase 'generate-searchQuery':\n\t\t\treturn 'Generate Search Query';\n\t}\n}\n\n/** The action name the GitKraken backend validates and bills requests under. Orient is a depth of the\n * review feature, so it travels as `review-changes` — the backend knows no finer-grained action, and\n * Start Review already sends one action for its overview and detail templates. */\nexport function getBackendActionType(action: AIActionType): AIActionType {\n\treturn action === 'review-orient' ? 'review-changes' : action;\n}\n\nexport const estimatedCharactersPerToken = 2.8;\n\nexport function getValidatedTemperature(\n\tmodel: AIModel,\n\tmodelTemperature?: number | null,\n\tdefaultTemperature?: number,\n): number | undefined {\n\t// `temperature: null` on the model is a capability statement, not a default: the model rejects the\n\t// parameter (reasoning models, Anthropic Opus 4.7+/Sonnet 5, Gemini 3.x) or the catalog can't\n\t// promise it accepts one (every GitKraken-proxy and OpenRouter model). It therefore has to win over\n\t// a caller-supplied value — callers merge as `modelOptions?.temperature ?? model.temperature`, and\n\t// `0 ?? null` is `0`, so an explicit 0 would otherwise defeat the opt-out and be sent anyway.\n\t// It also covers upstreams the id check below can't see: a proxy model is `openai:gpt-5.6-…`, not\n\t// `gpt-5.6-…`, so `startsWith` misses it while the upstream still 400s on a non-default value.\n\tif (model.temperature === null) return undefined;\n\tif (modelTemperature === null) return undefined;\n\t// GPT5 doesn't support anything but the default temperature\n\tif (model.id.startsWith('gpt-5')) return undefined;\n\n\tmodelTemperature ??= Math.max(0, Math.min(defaultTemperature ?? 0.7, 2));\n\treturn modelTemperature;\n}\n\n/**\n * Calculates the reduced max input tokens for retry attempts when context length is exceeded.\n *\n * If `estimatedTokens` is provided, calculates based on the actual overage ratio.\n * Otherwise, uses a hybrid strategy: conservative fixed reduction, then escalating percentages.\n *\n * @param maxInputTokens - Current max input tokens limit\n * @param retryCount - Current retry attempt (1-based, use value after incrementing)\n * @param estimatedTokens - Optional: estimated tokens in the prompt (if known)\n * @returns New max input tokens value\n */\nexport function isAzureUrl(url: string): boolean {\n\treturn url.includes('.azure.com');\n}\n\nexport function getReducedMaxInputTokens(maxInputTokens: number, retryCount: number, estimatedTokens?: number): number {\n\t// If we know the estimated tokens, calculate reduction based on overage\n\tif (estimatedTokens != null && estimatedTokens > maxInputTokens) {\n\t\tconst overageRatio = estimatedTokens / maxInputTokens;\n\t\t// Target below the limit with some buffer (5-15% below based on retry)\n\t\tconst bufferPercent = 0.05 + retryCount * 0.05;\n\t\tconst targetRatio = 1 / overageRatio - bufferPercent;\n\t\treturn Math.floor(maxInputTokens * Math.max(0.5, targetRatio));\n\t}\n\n\t// Fallback: progressive reduction without knowing exact overage\n\tswitch (retryCount) {\n\t\tcase 1:\n\t\t\t// Conservative fixed reduction for small overages\n\t\t\treturn maxInputTokens - 1000;\n\t\tcase 2:\n\t\t\t// Moderate percentage-based reduction\n\t\t\treturn Math.floor(maxInputTokens * 0.9);\n\t\tcase 3:\n\t\tdefault:\n\t\t\t// Aggressive percentage-based reduction\n\t\t\treturn Math.floor(maxInputTokens * 0.75);\n\t}\n}\n"],"mappings":";;AAIA,SAAgB,gBAAgB,cAAmD;CAClF,OAAO,iBAAiB,aAAa,iBAAiB;AACvD;AAEA,SAAgB,cAAc,QAA8B;CAC3D,QAAQ,QAAR;EACC,KAAK,mBACJ,OAAO;EACR,KAAK,kBACJ,OAAO;EACR,KAAK,iBACJ,OAAO;EACR,KAAK,0BACJ,OAAO;EACR,KAAK,yBACJ,OAAO;EACR,KAAK,sBACJ,OAAO;EACR,KAAK,8BACJ,OAAO;EACR,KAAK,+BACJ,OAAO;EACR,KAAK,oBACJ,OAAO;EACR,KAAK,uBACJ,OAAO;EACR,KAAK,wBACJ,OAAO;CACT;AACD;;;;AAKA,SAAgB,qBAAqB,QAAoC;CACxE,OAAO,WAAW,kBAAkB,mBAAmB;AACxD;AAEA,MAAa,8BAA8B;AAE3C,SAAgB,wBACf,OACA,kBACA,oBACqB;CAQrB,IAAI,MAAM,gBAAgB,MAAM,OAAO,KAAA;CACvC,IAAI,qBAAqB,MAAM,OAAO,KAAA;CAEtC,IAAI,MAAM,GAAG,WAAW,OAAO,GAAG,OAAO,KAAA;CAEzC,qBAAqB,KAAK,IAAI,GAAG,KAAK,IAAI,sBAAsB,IAAK,CAAC,CAAC;CACvE,OAAO;AACR;;;;;;;;;;;;AAaA,SAAgB,WAAW,KAAsB;CAChD,OAAO,IAAI,SAAS,YAAY;AACjC;AAEA,SAAgB,yBAAyB,gBAAwB,YAAoB,iBAAkC;CAEtH,IAAI,mBAAmB,QAAQ,kBAAkB,gBAAgB;EAChE,MAAM,eAAe,kBAAkB;EAEvC,MAAM,gBAAgB,MAAO,aAAa;EAC1C,MAAM,cAAc,IAAI,eAAe;EACvC,OAAO,KAAK,MAAM,iBAAiB,KAAK,IAAI,IAAK,WAAW,CAAC;CAC9D;CAGA,QAAQ,YAAR;EACC,KAAK,GAEJ,OAAO,iBAAiB;EACzB,KAAK,GAEJ,OAAO,KAAK,MAAM,iBAAiB,EAAG;EAEvC,SAEC,OAAO,KAAK,MAAM,iBAAiB,GAAI;CACzC;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AIReviewDetailResult, AIReviewResult } from "../models/results.js";
|
|
1
|
+
import { AIReviewDetailResult, AIReviewFindingLocation, AIReviewOrientResult, AIReviewResult } from "../models/results.js";
|
|
2
2
|
//#region ../plus/ai/src/utils/results.utils.d.ts
|
|
3
3
|
export declare function parseSummarizeResult(result: string): {
|
|
4
4
|
readonly summary: string;
|
|
@@ -14,6 +14,13 @@ export declare function parseReviewResult(result: string, mode: 'single-pass' |
|
|
|
14
14
|
* follow-up conversation without contradicting the format the model is being asked to produce. */
|
|
15
15
|
export declare function serializeReviewResult(result: AIReviewResult): string;
|
|
16
16
|
export declare function parseReviewDetailResult(result: string, focusAreaId: string): AIReviewDetailResult;
|
|
17
|
+
interface ReviewFindingLocationJson {
|
|
18
|
+
file?: string | null;
|
|
19
|
+
lines?: {
|
|
20
|
+
start?: number;
|
|
21
|
+
end?: number;
|
|
22
|
+
} | null;
|
|
23
|
+
}
|
|
17
24
|
/** Returns the contents of the first fenced code block, or the trimmed input when unfenced */
|
|
18
25
|
export declare function stripJsonCodeFence(text: string): string;
|
|
19
26
|
/**
|
|
@@ -23,6 +30,13 @@ export declare function stripJsonCodeFence(text: string): string;
|
|
|
23
30
|
* objects inside truncated output) can't be mistaken for the payload.
|
|
24
31
|
*/
|
|
25
32
|
export declare function extractJsonObject(text: string, isExpectedShape?: (parsed: Record<string, unknown>) => boolean): Record<string, unknown> | undefined;
|
|
33
|
+
/** The finding's places, first place first: `file`/`lines` lead, then `locations` in order, each place once.
|
|
34
|
+
* A model that puts the first place only in `locations` still gets it as the finding's `filePath`. */
|
|
35
|
+
export declare function normalizeFindingLocations(finding: ReviewFindingLocationJson & {
|
|
36
|
+
locations?: readonly ReviewFindingLocationJson[] | null;
|
|
37
|
+
}): AIReviewFindingLocation[];
|
|
38
|
+
/** Parses an orient pass: a reading order, not findings. A file that appears twice keeps its first stop. */
|
|
39
|
+
export declare function parseReviewOrientJson(result: string): AIReviewOrientResult;
|
|
26
40
|
/** Parses a review result, preferring the JSON shape and falling back to the legacy XML format */
|
|
27
41
|
export declare function parseReviewResultJson(result: string, mode: 'single-pass' | 'two-pass'): AIReviewResult;
|
|
28
42
|
/** Parses a review detail result, preferring the JSON shape and falling back to the legacy XML format */
|
|
@@ -129,7 +129,14 @@ function serializeFindingJson(finding) {
|
|
|
129
129
|
lines: finding.lineRange != null ? {
|
|
130
130
|
start: finding.lineRange.start,
|
|
131
131
|
end: finding.lineRange.end
|
|
132
|
-
} : null
|
|
132
|
+
} : null,
|
|
133
|
+
locations: finding.locations != null ? finding.locations.map((l) => ({
|
|
134
|
+
file: l.filePath,
|
|
135
|
+
lines: l.lineRange != null ? {
|
|
136
|
+
start: l.lineRange.start,
|
|
137
|
+
end: l.lineRange.end
|
|
138
|
+
} : null
|
|
139
|
+
})) : null
|
|
133
140
|
};
|
|
134
141
|
}
|
|
135
142
|
/** Inverse of {@link parseReviewResultJson} — emits the same JSON shape the review prompt templates
|
|
@@ -222,16 +229,85 @@ function coerceLineNumber(value) {
|
|
|
222
229
|
if (typeof value === "number") return value;
|
|
223
230
|
if (typeof value === "string") return parseInt(value, 10);
|
|
224
231
|
}
|
|
232
|
+
function normalizeLocationJson(location) {
|
|
233
|
+
const filePath = trimmedString(location?.file) || void 0;
|
|
234
|
+
if (filePath == null) return void 0;
|
|
235
|
+
const lineRange = normalizeLineRange(coerceLineNumber(location?.lines?.start), coerceLineNumber(location?.lines?.end));
|
|
236
|
+
return lineRange != null ? {
|
|
237
|
+
filePath,
|
|
238
|
+
lineRange
|
|
239
|
+
} : { filePath };
|
|
240
|
+
}
|
|
241
|
+
/** The finding's places, first place first: `file`/`lines` lead, then `locations` in order, each place once.
|
|
242
|
+
* A model that puts the first place only in `locations` still gets it as the finding's `filePath`. */
|
|
243
|
+
function normalizeFindingLocations(finding) {
|
|
244
|
+
const out = [];
|
|
245
|
+
const seen = /* @__PURE__ */ new Set();
|
|
246
|
+
const add = (location) => {
|
|
247
|
+
if (location == null) return;
|
|
248
|
+
const key = `${location.filePath}:${location.lineRange?.start ?? ""}-${location.lineRange?.end ?? ""}`;
|
|
249
|
+
if (seen.has(key)) return;
|
|
250
|
+
seen.add(key);
|
|
251
|
+
out.push(location);
|
|
252
|
+
};
|
|
253
|
+
add(normalizeLocationJson(finding));
|
|
254
|
+
for (const location of Array.isArray(finding.locations) ? finding.locations : []) add(normalizeLocationJson(location));
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
225
257
|
function normalizeFindingJson(finding, id) {
|
|
226
258
|
const title = trimmedString(finding.title);
|
|
259
|
+
const locations = normalizeFindingLocations(finding);
|
|
260
|
+
const [first] = locations;
|
|
227
261
|
return {
|
|
228
262
|
id,
|
|
229
263
|
severity: parseSeverity(trimmedString(finding.severity)),
|
|
230
264
|
title: title || "Untitled finding",
|
|
231
265
|
...!title ? { titleIsFallback: true } : {},
|
|
232
266
|
description: trimmedString(finding.description) ?? "",
|
|
233
|
-
filePath:
|
|
234
|
-
lineRange:
|
|
267
|
+
filePath: first?.filePath,
|
|
268
|
+
lineRange: first?.lineRange,
|
|
269
|
+
...locations.length > 1 ? { locations } : {}
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function parseOrientGroupKind(value) {
|
|
273
|
+
return value === "core" || value === "supporting" || value === "mechanical" ? value : "supporting";
|
|
274
|
+
}
|
|
275
|
+
/** Parses an orient pass: a reading order, not findings. A file that appears twice keeps its first stop. */
|
|
276
|
+
function parseReviewOrientJson(result) {
|
|
277
|
+
if (!result.trim()) throw new Error(l10n.t("The AI model returned an empty response"));
|
|
278
|
+
const parsed = extractJsonObject(result, (o) => Array.isArray(o.groups));
|
|
279
|
+
if (parsed == null) throw new Error(l10n.t("Unable to parse the review response from the AI model"));
|
|
280
|
+
const seen = /* @__PURE__ */ new Set();
|
|
281
|
+
const groups = [];
|
|
282
|
+
let index = 0;
|
|
283
|
+
for (const group of parsed.groups ?? []) {
|
|
284
|
+
if (group == null || typeof group !== "object") continue;
|
|
285
|
+
const files = [];
|
|
286
|
+
for (const file of Array.isArray(group.files) ? group.files : []) {
|
|
287
|
+
if (file == null || typeof file !== "object") continue;
|
|
288
|
+
const path = trimmedString(file.path);
|
|
289
|
+
if (!path || seen.has(path)) continue;
|
|
290
|
+
seen.add(path);
|
|
291
|
+
files.push({
|
|
292
|
+
path,
|
|
293
|
+
note: trimmedString(file.note) ?? ""
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
if (files.length === 0) continue;
|
|
297
|
+
index++;
|
|
298
|
+
const label = trimmedString(group.label);
|
|
299
|
+
groups.push({
|
|
300
|
+
id: `group-${index}`,
|
|
301
|
+
label: label || "Untitled group",
|
|
302
|
+
...!label ? { labelIsFallback: true } : {},
|
|
303
|
+
kind: parseOrientGroupKind(trimmedString(group.kind)),
|
|
304
|
+
summary: trimmedString(group.summary) ?? "",
|
|
305
|
+
files
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
overview: typeof parsed.overview === "string" ? parsed.overview.trim() : "",
|
|
310
|
+
groups
|
|
235
311
|
};
|
|
236
312
|
}
|
|
237
313
|
/** Parses a review result, preferring the JSON shape and falling back to the legacy XML format */
|
|
@@ -282,6 +358,6 @@ function parseReviewDetailResultJson(result, focusAreaId) {
|
|
|
282
358
|
return { findings: parsed.findings.filter((f) => f != null && typeof f === "object").map((f, i) => normalizeFindingJson(f, `${focusAreaId}-f${i + 1}`)) };
|
|
283
359
|
}
|
|
284
360
|
//#endregion
|
|
285
|
-
export { extractJsonObject, parseReviewDetailResult, parseReviewDetailResultJson, parseReviewResult, parseReviewResultJson, parseSummarizeResult, serializeReviewResult, splitMessageIntoSummaryAndBody, stripJsonCodeFence };
|
|
361
|
+
export { extractJsonObject, normalizeFindingLocations, parseReviewDetailResult, parseReviewDetailResultJson, parseReviewOrientJson, parseReviewResult, parseReviewResultJson, parseSummarizeResult, serializeReviewResult, splitMessageIntoSummaryAndBody, stripJsonCodeFence };
|
|
286
362
|
|
|
287
363
|
//# sourceMappingURL=results.utils.js.map
|