File size: 12,498 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/** Resolves credentials for an immutable prepared runtime route. */
import { toErrorObject } from "../../infra/errors.js";
import { SecretSurfaceUnavailableError } from "../../secrets/runtime-degraded-state.js";
import { OAuthRefreshFailureError } from "../auth-profiles/oauth-refresh-failure.js";
import type { AuthProfileStore } from "../auth-profiles/types.js";
import { isProfileInCooldown } from "../auth-profiles/usage-state.js";
import { getApiKeyForModelCore } from "../model-auth.js";
import { providerModelRouteAcceptsAuthMode } from "../provider-model-route-auth.js";
import { shouldForceDirectAuthFallbackModelResolve } from "./credential-scoped-model.js";
import { sameAgentRuntimeAuthModelRoute } from "./model-route.js";
import {
  canRunPreparedAgentRuntimeAuthAttempt,
  preparedAgentRuntimeProfileAttemptHasCandidate,
  type PreparedAgentRuntimeAuthAttempt,
} from "./prepare-auth.js";
import type { AgentRuntimeAuthPlan } from "./types.js";

type PreparedRuntimeModelAuthResolution = Readonly<{
  auth: Awaited<ReturnType<typeof getApiKeyForModelCore>>;
  plan: AgentRuntimeAuthPlan;
}>;

type PreparedRuntimeAuthAttemptResolution<Model, Auth> = Readonly<{
  model: Model;
  plan: AgentRuntimeAuthPlan;
  auth: Auth;
}>;

function listDistinctPreparedRuntimeAuthAttempts(
  attempts: readonly PreparedAgentRuntimeAuthAttempt[],
): PreparedAgentRuntimeAuthAttempt[] {
  return attempts.filter((attempt, index) => {
    const route = attempt.plan.modelRoute;
    return !attempts.slice(0, index).some((previous) => {
      // Same-route profile candidates resolve as one tier. Direct auth remains
      // distinct because it must never be swallowed by profile fallback.
      if (
        (previous.allowAuthProfileFallback === false) !==
        (attempt.allowAuthProfileFallback === false)
      ) {
        return false;
      }
      const previousRoute = previous.plan.modelRoute;
      if (!route || !previousRoute) {
        return !route && !previousRoute;
      }
      return sameAgentRuntimeAuthModelRoute(route, previousRoute);
    });
  });
}

/** Resolves one complete prepared route/profile tuple without crossing retries mid-flight. */
export async function resolvePreparedRuntimeAuthAttempts<Model, Auth>(params: {
  attempts: readonly PreparedAgentRuntimeAuthAttempt[];
  store: AuthProfileStore;
  modelId: string;
  model: Model;
  materializeModel(input: {
    plan: AgentRuntimeAuthPlan;
    model: Model;
    forceResolve?: boolean;
  }): Promise<Model>;
  resolveAuth(input: {
    attempt: PreparedAgentRuntimeAuthAttempt;
    model: Model;
  }): Promise<{ plan: AgentRuntimeAuthPlan; auth: Auth }>;
  forceCredentialScopedDirectModelResolve?: boolean;
  errorMessage: string;
}): Promise<PreparedRuntimeAuthAttemptResolution<Model, Auth>> {
  let firstError: unknown;
  let priorProfileAttempted = false;
  for (const attempt of listDistinctPreparedRuntimeAuthAttempts(params.attempts)) {
    if (
      !canRunPreparedAgentRuntimeAuthAttempt({
        attempt,
        priorProfileAttempted,
      })
    ) {
      firstError ??= new Error("Prepared direct auth cannot bypass unavailable profiles.");
      continue;
    }
    if (
      attempt.kind === "profile" &&
      !preparedAgentRuntimeProfileAttemptHasCandidate({
        attempt,
        store: params.store,
        modelId: params.modelId,
      })
    ) {
      firstError ??= new Error("Prepared runtime auth candidates are temporarily unavailable.");
      continue;
    }
    try {
      let model = await params.materializeModel({
        plan: attempt.plan,
        model: params.model,
        forceResolve:
          (params.forceCredentialScopedDirectModelResolve === true &&
            attempt.kind === "direct" &&
            Boolean(attempt.plan.selectedAuthMode)) ||
          shouldForceDirectAuthFallbackModelResolve({
            attempt,
            priorProfileAttempted,
          }),
      });
      if (
        attempt.kind === "profile" &&
        !preparedAgentRuntimeProfileAttemptHasCandidate({
          attempt,
          store: params.store,
          modelId: params.modelId,
        })
      ) {
        throw new Error("Prepared runtime auth candidates are temporarily unavailable.");
      }
      // Direct fallback unlocks only after credential resolution really ran;
      // cooldown skips and route-materialization failures do not count.
      const resolution = params.resolveAuth({ attempt, model });
      priorProfileAttempted ||= attempt.kind === "profile";
      const resolved = await resolution;
      if (resolved.plan.forwardedAuthProfileId !== attempt.plan.forwardedAuthProfileId) {
        model = await params.materializeModel({
          plan: resolved.plan,
          model,
          forceResolve: true,
        });
      }
      // Model, physical route, and credential become active together.
      return { model, plan: resolved.plan, auth: resolved.auth };
    } catch (error) {
      if (
        error instanceof SecretSurfaceUnavailableError ||
        error instanceof OAuthRefreshFailureError
      ) {
        throw error;
      }
      firstError ??= error;
    }
  }
  throw toErrorObject(firstError, params.errorMessage);
}

function scopeAuthStoreToPreparedCandidates(
  store: AuthProfileStore,
  profileIds: readonly string[],
): AuthProfileStore {
  const profileIdSet = new Set(profileIds);
  const profiles: AuthProfileStore["profiles"] = {};
  for (const profileId of profileIds) {
    const profile = store.profiles[profileId];
    if (profile) {
      profiles[profileId] = profile;
    }
  }
  const order = store.order
    ? Object.fromEntries(
        Object.entries(store.order).map(([provider, ids]) => [
          provider,
          ids.filter((profileId) => profileIdSet.has(profileId)),
        ]),
      )
    : undefined;
  const lastGood = store.lastGood
    ? Object.fromEntries(
        Object.entries(store.lastGood).filter(([, profileId]) => profileIdSet.has(profileId)),
      )
    : undefined;
  const usageStats = store.usageStats
    ? Object.fromEntries(
        Object.entries(store.usageStats).filter(([profileId]) => profileIdSet.has(profileId)),
      )
    : undefined;
  const runtimePersistedProfileIds = store.runtimePersistedProfileIds?.filter((profileId) =>
    profileIdSet.has(profileId),
  );
  const runtimeExternalProfileIds = store.runtimeExternalProfileIds?.filter((profileId) =>
    profileIdSet.has(profileId),
  );
  return {
    version: store.version,
    profiles,
    ...(order ? { order } : {}),
    ...(lastGood ? { lastGood } : {}),
    ...(usageStats ? { usageStats } : {}),
    ...(runtimePersistedProfileIds ? { runtimePersistedProfileIds } : {}),
    ...(runtimeExternalProfileIds || store.runtimeExternalProfileIdsAuthoritative === true
      ? {
          runtimeExternalProfileIds: runtimeExternalProfileIds ?? [],
          ...(store.runtimeExternalProfileIdsAuthoritative === true
            ? { runtimeExternalProfileIdsAuthoritative: true }
            : {}),
        }
      : {}),
  };
}

/** Restricts a native auth consumer to the profiles selected for one physical route. */
export function scopeAuthProfileStoreToPreparedPlan(
  store: AuthProfileStore,
  plan: AgentRuntimeAuthPlan,
): AuthProfileStore {
  const profileIds =
    plan.modelRoute?.authRequirement === "api-key"
      ? []
      : [plan.forwardedAuthProfileId, ...(plan.forwardedAuthProfileCandidateIds ?? [])].filter(
          (profileId, index, values): profileId is string => {
            return Boolean(profileId?.trim()) && values.indexOf(profileId) === index;
          },
        );
  return scopeAuthStoreToPreparedCandidates(store, profileIds);
}

function applyResolvedAuthToPlan(params: {
  plan: AgentRuntimeAuthPlan;
  auth: Awaited<ReturnType<typeof getApiKeyForModelCore>>;
  candidates: string[];
}): AgentRuntimeAuthPlan {
  const profileId = params.auth.profileId?.trim();
  if (!profileId) {
    return {
      ...params.plan,
      forwardedAuthProfileId: undefined,
      forwardedAuthProfileSource: undefined,
      forwardedAuthProfileCandidateIds: undefined,
      selectedAuthMode: params.auth.mode,
    };
  }
  const resolvedIndex = params.candidates.indexOf(profileId);
  const remainingCandidates =
    resolvedIndex >= 0 ? params.candidates.slice(resolvedIndex) : [profileId];
  const source = params.plan.forwardedAuthProfileId
    ? params.plan.forwardedAuthProfileSource
    : "auto";
  return {
    ...params.plan,
    forwardedAuthProfileId: profileId,
    forwardedAuthProfileSource: source,
    forwardedAuthProfileCandidateIds: source === "auto" ? remainingCandidates : [profileId],
    selectedAuthMode: params.auth.mode,
  };
}

function assertResolvedAuthMatchesPreparedRoute(params: {
  plan: AgentRuntimeAuthPlan;
  auth: Awaited<ReturnType<typeof getApiKeyForModelCore>>;
}): void {
  const route = params.plan.modelRoute;
  if (
    !route ||
    providerModelRouteAcceptsAuthMode({
      requirement: route.authRequirement,
      mode: params.auth.mode,
    })
  ) {
    return;
  }
  throw new Error(
    `Resolved ${params.auth.mode} credentials are incompatible with the selected ${route.authRequirement} route for ${route.provider}.`,
  );
}

/** Resolves prepared same-route candidates without pinning the first unresolved profile. */
export async function resolvePreparedRuntimeModelAuth(
  params: Omit<Parameters<typeof getApiKeyForModelCore>[0], "profileId"> & {
    plan: AgentRuntimeAuthPlan;
  },
): Promise<PreparedRuntimeModelAuthResolution> {
  const { plan, ...authParams } = params;
  const candidates = [
    plan.forwardedAuthProfileId,
    ...(plan.forwardedAuthProfileCandidateIds ?? []),
  ].filter((profileId, index, values): profileId is string => {
    return Boolean(profileId?.trim()) && values.indexOf(profileId) === index;
  });
  if (candidates.length === 0) {
    // The planner selected direct auth. Resolve only env/config material so an
    // unrelated full store cannot replace or pre-reject that immutable source.
    const auth = await getApiKeyForModelCore({
      ...authParams,
      store: { version: 1, profiles: {} },
      lockedProfile: false,
      allowAuthProfileFallback: false,
      skipSetupProviderFallback: plan.modelRoute?.provider === "openai",
    });
    assertResolvedAuthMatchesPreparedRoute({ plan, auth });
    return { auth, plan: applyResolvedAuthToPlan({ plan, auth, candidates }) };
  }
  if (plan.forwardedAuthProfileSource !== "auto") {
    const auth = await getApiKeyForModelCore({
      ...authParams,
      profileId: plan.forwardedAuthProfileId,
      lockedProfile: Boolean(plan.forwardedAuthProfileId),
    });
    assertResolvedAuthMatchesPreparedRoute({ plan, auth });
    return { auth, plan: applyResolvedAuthToPlan({ plan, auth, candidates }) };
  }

  // Prepared automatic candidates remain exhaustive, but their cooldown state
  // can change while work waits in a command lane. Recheck at credential use.
  const store = params.store;
  const currentCandidates = store
    ? candidates.filter(
        (profileId) => !isProfileInCooldown(store, profileId, undefined, params.model.id),
      )
    : candidates;
  if (currentCandidates.length === 0) {
    throw new Error("Prepared runtime auth candidates are temporarily unavailable.");
  }
  const candidateStore = store
    ? scopeAuthStoreToPreparedCandidates(store, currentCandidates)
    : undefined;

  let firstError: unknown;
  let refreshFailure: OAuthRefreshFailureError | undefined;
  for (const profileId of currentCandidates) {
    try {
      const auth = await getApiKeyForModelCore({
        ...authParams,
        profileId,
        // This loop owns fallback order. Pin each lookup so the generic auth
        // resolver cannot rescan or skip across the prepared candidate set.
        lockedProfile: true,
        ...(candidateStore ? { store: candidateStore } : {}),
      });
      assertResolvedAuthMatchesPreparedRoute({ plan, auth });
      return {
        auth,
        plan: applyResolvedAuthToPlan({ plan, auth, candidates: currentCandidates }),
      };
    } catch (error) {
      if (error instanceof SecretSurfaceUnavailableError) {
        throw error;
      }
      if (!refreshFailure && error instanceof OAuthRefreshFailureError) {
        refreshFailure = error;
      }
      firstError ??= error;
    }
  }
  if (refreshFailure) {
    throw refreshFailure;
  }
  throw toErrorObject(firstError, "Prepared runtime auth candidates could not be resolved.");
}