@modelprofile.com/flexharness-providers 9.2.0 → 9.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist_ts_media_openai/index.js +2 -3
  2. package/dist_ts_media_openai/plugins.d.ts +2 -0
  3. package/dist_ts_media_openai/plugins.js +5 -1
  4. package/dist_ts_openai_account/index.d.ts +1 -1
  5. package/dist_ts_openai_account/index.js +2 -2
  6. package/dist_ts_openai_account/plugins.d.ts +3 -0
  7. package/dist_ts_openai_account/plugins.js +3 -1
  8. package/dist_ts_openai_account/smartai.providers.credentials.d.ts +2 -2
  9. package/dist_ts_openai_account/smartai.providers.credentials.js +3 -4
  10. package/dist_ts_openai_account/smartai.providers.interfaces.d.ts +6 -7
  11. package/dist_ts_openai_account/smartai.providers.openai.js +15 -16
  12. package/dist_ts_openai_auth/index.d.ts +1 -1
  13. package/dist_ts_openai_auth/index.js +2 -2
  14. package/dist_ts_openai_auth/interfaces.d.ts +1 -1
  15. package/dist_ts_openai_auth/plugins.d.ts +3 -0
  16. package/dist_ts_openai_auth/plugins.js +4 -0
  17. package/dist_ts_openai_auth/smartai.auth.openai.d.ts +1 -2
  18. package/dist_ts_openai_auth/smartai.auth.openai.js +27 -27
  19. package/dist_ts_openai_auth/smartai.connection.openai.d.ts +3 -3
  20. package/dist_ts_openai_auth/smartai.connection.openai.js +6 -6
  21. package/dist_ts_openai_auth_files/index.d.ts +6 -6
  22. package/dist_ts_openai_auth_files/index.js +3 -4
  23. package/dist_ts_openai_auth_files/plugins.d.ts +3 -0
  24. package/dist_ts_openai_auth_files/plugins.js +4 -1
  25. package/dist_ts_providers/anthropic/plugins.d.ts +3 -2
  26. package/dist_ts_providers/anthropic/plugins.js +3 -3
  27. package/dist_ts_providers/anthropic/smartai.middleware.anthropic.d.ts +2 -3
  28. package/dist_ts_providers/anthropic/smartai.middleware.anthropic.js +3 -3
  29. package/dist_ts_providers/ollama/index.d.ts +2 -2
  30. package/dist_ts_providers/ollama/index.js +1 -1
  31. package/dist_ts_providers/ollama/interfaces.d.ts +2 -2
  32. package/dist_ts_providers/ollama/plugins.d.ts +2 -0
  33. package/dist_ts_providers/ollama/plugins.js +2 -0
  34. package/dist_ts_providers/ollama/smartai.provider.ollama.d.ts +2 -2
  35. package/dist_ts_providers/ollama/smartai.provider.ollama.js +1 -1
  36. package/dist_ts_providers/openai/smartai.limits.openai.d.ts +4 -1
  37. package/dist_ts_providers/openai/smartai.limits.openai.js +10 -5
  38. package/package.json +11 -11
  39. package/ts_media_openai/index.ts +1 -2
  40. package/ts_media_openai/plugins.ts +6 -0
  41. package/ts_openai_account/index.ts +1 -1
  42. package/ts_openai_account/plugins.ts +37 -0
  43. package/ts_openai_account/smartai.providers.credentials.ts +3 -5
  44. package/ts_openai_account/smartai.providers.interfaces.ts +6 -12
  45. package/ts_openai_account/smartai.providers.openai.ts +18 -31
  46. package/ts_openai_auth/index.ts +1 -1
  47. package/ts_openai_auth/interfaces.ts +1 -1
  48. package/ts_openai_auth/plugins.ts +17 -0
  49. package/ts_openai_auth/smartai.auth.openai.ts +28 -33
  50. package/ts_openai_auth/smartai.connection.openai.ts +7 -11
  51. package/ts_openai_auth_files/index.ts +19 -28
  52. package/ts_openai_auth_files/plugins.ts +10 -0
  53. package/ts_providers/anthropic/plugins.ts +10 -1
  54. package/ts_providers/anthropic/smartai.middleware.anthropic.ts +3 -5
  55. package/ts_providers/ollama/index.ts +2 -2
  56. package/ts_providers/ollama/interfaces.ts +2 -2
  57. package/ts_providers/ollama/plugins.ts +12 -0
  58. package/ts_providers/ollama/smartai.provider.ollama.ts +11 -21
  59. package/ts_providers/openai/readme.md +3 -2
  60. package/ts_providers/openai/smartai.limits.openai.ts +12 -4
@@ -14,18 +14,13 @@ import type {
14
14
  IOpenAiChatGptTokenInfo,
15
15
  TOpenAiChatGptBrowserCallback,
16
16
  } from './interfaces.js';
17
- import {
18
- OPENAI_CHATGPT_CODEX_BASE_URL,
19
- OPENAI_CHATGPT_DEFAULT_ORIGINATOR,
20
- OpenAiChatGptAuthError,
21
- type TOpenAiChatGptRequestOutcome,
22
- } from '@modelprofile.com/flexharness-providers/openai';
17
+ import * as plugins from './plugins.js';
23
18
 
24
19
  export {
25
20
  OPENAI_CHATGPT_CODEX_BASE_URL,
26
21
  OPENAI_CHATGPT_DEFAULT_ORIGINATOR,
27
22
  OpenAiChatGptAuthError,
28
- };
23
+ } from './plugins.js';
29
24
 
30
25
  export const OPENAI_CHATGPT_AUTH_ISSUER = 'https://auth.openai.com';
31
26
  export const OPENAI_CHATGPT_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
@@ -65,7 +60,7 @@ interface IOpenAiChatGptTokenResponse {
65
60
  function getFetch(options: IOpenAiChatGptAuthOptions): typeof fetch {
66
61
  const fetchFunction = options.fetch ?? globalThis.fetch;
67
62
  if (!fetchFunction) {
68
- throw new OpenAiChatGptAuthError('fetch is not available for OpenAI ChatGPT authentication.');
63
+ throw new plugins.OpenAiChatGptAuthError('fetch is not available for OpenAI ChatGPT authentication.');
69
64
  }
70
65
  return fetchFunction;
71
66
  }
@@ -74,8 +69,8 @@ function authError(
74
69
  message: string,
75
70
  options: IOpenAiChatGptAuthOptions,
76
71
  details: { status?: number; body?: string } = {},
77
- ): OpenAiChatGptAuthError {
78
- return new OpenAiChatGptAuthError(
72
+ ): plugins.OpenAiChatGptAuthError {
73
+ return new plugins.OpenAiChatGptAuthError(
79
74
  message,
80
75
  usesSafeErrors(options)
81
76
  ? { ...(details.status === undefined ? {} : { status: details.status }) }
@@ -235,7 +230,7 @@ async function runFetch<TResult>(
235
230
  timeoutMsArg = AUTH_REQUEST_TIMEOUT_MS,
236
231
  ): Promise<TResult> {
237
232
  if (options.signal?.aborted) {
238
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT authentication was aborted.', {
233
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT authentication was aborted.', {
239
234
  requestOutcome: 'notSent',
240
235
  });
241
236
  }
@@ -275,12 +270,12 @@ async function runFetch<TResult>(
275
270
  aborted,
276
271
  ]);
277
272
  } catch (error) {
278
- const requestOutcome: TOpenAiChatGptRequestOutcome = requestStarted
273
+ const requestOutcome: plugins.TOpenAiChatGptRequestOutcome = requestStarted
279
274
  ? 'outcomeUnknown'
280
275
  : 'notSent';
281
276
  const retryAfterMs = response ? parseRetryAfterMs(response.headers.get('retry-after')) : undefined;
282
- if (error instanceof OpenAiChatGptAuthError) {
283
- throw new OpenAiChatGptAuthError(error.message, {
277
+ if (error instanceof plugins.OpenAiChatGptAuthError) {
278
+ throw new plugins.OpenAiChatGptAuthError(error.message, {
284
279
  ...(error.status !== undefined ? { status: error.status }
285
280
  : response ? { status: response.status } : {}),
286
281
  ...(error.body !== undefined ? { body: error.body } : {}),
@@ -289,7 +284,7 @@ async function runFetch<TResult>(
289
284
  });
290
285
  }
291
286
  if (!usesSafeErrors(options)) throw error;
292
- throw new OpenAiChatGptAuthError(
287
+ throw new plugins.OpenAiChatGptAuthError(
293
288
  options.signal?.aborted
294
289
  ? 'OpenAI ChatGPT authentication was aborted.'
295
290
  : 'OpenAI ChatGPT authentication request failed.',
@@ -377,7 +372,7 @@ async function sleepWithAbort(
377
372
  function parseJwtPayload(jwt: string): Record<string, unknown> {
378
373
  const parts = jwt.split('.');
379
374
  if (parts.length !== 3 || !parts[1]) {
380
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT auth returned an invalid token.');
375
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT auth returned an invalid token.');
381
376
  }
382
377
 
383
378
  try {
@@ -386,7 +381,7 @@ function parseJwtPayload(jwt: string): Record<string, unknown> {
386
381
  const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
387
382
  return JSON.parse(textDecoder.decode(bytes)) as Record<string, unknown>;
388
383
  } catch (error) {
389
- throw new OpenAiChatGptAuthError(`OpenAI ChatGPT token could not be parsed: ${(error as Error).message}`);
384
+ throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT token could not be parsed: ${(error as Error).message}`);
390
385
  }
391
386
  }
392
387
 
@@ -563,7 +558,7 @@ export function ensureOpenAiChatGptWorkspaceAllowed(
563
558
  return;
564
559
  }
565
560
  if (tokenData.tokenInfo.chatgptAccountId !== forcedChatGptWorkspaceId) {
566
- throw new OpenAiChatGptAuthError(`OpenAI ChatGPT login is restricted to workspace ${forcedChatGptWorkspaceId}.`);
561
+ throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT login is restricted to workspace ${forcedChatGptWorkspaceId}.`);
567
562
  }
568
563
  }
569
564
 
@@ -617,7 +612,7 @@ const requireBase64UrlValue = (
617
612
  || value.length < minimumBytes
618
613
  || value.length > maximumBytes
619
614
  ) {
620
- throw new OpenAiChatGptAuthError(`OpenAI ChatGPT ${label} is invalid.`);
615
+ throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT ${label} is invalid.`);
621
616
  }
622
617
  return value;
623
618
  };
@@ -642,7 +637,7 @@ export async function createOpenAiChatGptBrowserAuthorization(
642
637
  const codeChallenge = encodeBase64Url(new Uint8Array(
643
638
  await webCrypto.subtle.digest('SHA-256', textEncoder.encode(codeVerifier)),
644
639
  ));
645
- const originator = options.originator ?? OPENAI_CHATGPT_DEFAULT_ORIGINATOR;
640
+ const originator = options.originator ?? plugins.OPENAI_CHATGPT_DEFAULT_ORIGINATOR;
646
641
  if (
647
642
  utf8ByteLength(originator) > 128
648
643
  || !/^[A-Za-z0-9._-]+$/.test(originator)
@@ -690,7 +685,7 @@ export function parseOpenAiChatGptBrowserCallback(
690
685
  typeof callbackUrl !== 'string'
691
686
  || utf8ByteLength(callbackUrl) > SAFE_MAX_URL_BYTES
692
687
  ) {
693
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.');
688
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.');
694
689
  }
695
690
  const expectedRedirectUri = requireBrowserRedirectUri(options.expectedRedirectUri, {});
696
691
  const expectedState = requireBase64UrlValue(options.expectedState, 'browser state', 32, 128);
@@ -698,11 +693,11 @@ export function parseOpenAiChatGptBrowserCallback(
698
693
  try {
699
694
  parsed = new URL(callbackUrl);
700
695
  } catch {
701
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.');
696
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.');
702
697
  }
703
698
  const expectedUrl = new URL(expectedRedirectUri);
704
699
  if (parsed.origin !== expectedUrl.origin || parsed.pathname !== expectedUrl.pathname) {
705
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback target is invalid.');
700
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback target is invalid.');
706
701
  }
707
702
  const allowedKeys = new Set(['code', 'state', 'error', 'error_description']);
708
703
  const keys = [...parsed.searchParams.keys()];
@@ -711,16 +706,16 @@ export function parseOpenAiChatGptBrowserCallback(
711
706
  || keys.some((key) => !allowedKeys.has(key))
712
707
  || new Set(keys).size !== keys.length
713
708
  ) {
714
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback parameters are invalid.');
709
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback parameters are invalid.');
715
710
  }
716
711
  const state = parsed.searchParams.get('state');
717
712
  if (state !== expectedState) {
718
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback state does not match.');
713
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback state does not match.');
719
714
  }
720
715
  const providerError = parsed.searchParams.get('error');
721
716
  if (providerError !== null) {
722
717
  if (!/^[A-Za-z0-9._-]{1,128}$/.test(providerError)) {
723
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser login was denied.');
718
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser login was denied.');
724
719
  }
725
720
  return { providerError };
726
721
  }
@@ -729,7 +724,7 @@ export function parseOpenAiChatGptBrowserCallback(
729
724
  !authorizationCode
730
725
  || utf8ByteLength(authorizationCode) > SAFE_MAX_AUTHORIZATION_CODE_BYTES
731
726
  ) {
732
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT browser callback has no valid code.');
727
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback has no valid code.');
733
728
  }
734
729
  return { authorizationCode };
735
730
  }
@@ -799,14 +794,14 @@ export function createOpenAiChatGptProviderSettings(credentials: IOpenAiChatGptA
799
794
  currentTokenInfo.expiresAt === undefined
800
795
  || Date.parse(currentTokenInfo.expiresAt) <= Date.now()
801
796
  ) {
802
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT access token has no valid future expiry.');
797
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT access token has no valid future expiry.');
803
798
  }
804
799
  const tokenAccountId = currentTokenInfo.chatgptAccountId;
805
800
  if (
806
801
  credentials.accountId !== undefined
807
802
  && credentials.accountId !== tokenAccountId
808
803
  ) {
809
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT account ID does not match the token claim.');
804
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT account ID does not match the token claim.');
810
805
  }
811
806
  if (
812
807
  credentials.tokenInfo !== undefined
@@ -815,7 +810,7 @@ export function createOpenAiChatGptProviderSettings(credentials: IOpenAiChatGptA
815
810
  || credentials.tokenInfo.chatgptAccountIsFedramp !== currentTokenInfo.chatgptAccountIsFedramp
816
811
  )
817
812
  ) {
818
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT token information does not match the current access token.');
813
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT token information does not match the current access token.');
819
814
  }
820
815
  if (
821
816
  credentials.isFedrampAccount !== undefined
@@ -824,12 +819,12 @@ export function createOpenAiChatGptProviderSettings(credentials: IOpenAiChatGptA
824
819
  || credentials.isFedrampAccount !== currentTokenInfo.chatgptAccountIsFedramp
825
820
  )
826
821
  ) {
827
- throw new OpenAiChatGptAuthError('OpenAI ChatGPT FedRAMP status does not match the token claim.');
822
+ throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT FedRAMP status does not match the token claim.');
828
823
  }
829
824
  const accountId = tokenAccountId;
830
825
  const isFedrampAccount = currentTokenInfo.chatgptAccountIsFedramp;
831
826
  const headers: Record<string, string> = {
832
- originator: credentials.originator ?? OPENAI_CHATGPT_DEFAULT_ORIGINATOR,
827
+ originator: credentials.originator ?? plugins.OPENAI_CHATGPT_DEFAULT_ORIGINATOR,
833
828
  };
834
829
 
835
830
  if (accountId) {
@@ -841,7 +836,7 @@ export function createOpenAiChatGptProviderSettings(credentials: IOpenAiChatGptA
841
836
 
842
837
  return {
843
838
  apiKey: credentials.accessToken,
844
- baseURL: OPENAI_CHATGPT_CODEX_BASE_URL,
839
+ baseURL: plugins.OPENAI_CHATGPT_CODEX_BASE_URL,
845
840
  headers,
846
841
  };
847
842
  }
@@ -1,8 +1,4 @@
1
- import {
2
- classifyOpenAiChatGptLimit,
3
- createOpenAiChatGptInstructionsMiddleware,
4
- type IOpenAiModelConnection,
5
- } from '@modelprofile.com/flexharness-providers/openai';
1
+ import * as plugins from './plugins.js';
6
2
  import type {
7
3
  IOpenAiChatGptAuthCredentials,
8
4
  IOpenAiChatGptDynamicModelConnectionOptions,
@@ -88,17 +84,17 @@ function applyAccessHeaders(
88
84
 
89
85
  export const createOpenAiChatGptModelConnection = (
90
86
  credentialsArg: IOpenAiChatGptAuthCredentials,
91
- ): IOpenAiModelConnection => ({
87
+ ): plugins.IOpenAiModelConnection => ({
92
88
  settings: createOpenAiChatGptProviderSettings(credentialsArg),
93
- middleware: createOpenAiChatGptInstructionsMiddleware(),
89
+ middleware: plugins.createOpenAiChatGptInstructionsMiddleware(),
94
90
  // the ChatGPT Codex backend serves the Responses API only
95
91
  apis: ['responses'],
96
- classifyLimit: classifyOpenAiChatGptLimit,
92
+ classifyLimit: plugins.classifyOpenAiChatGptLimit,
97
93
  });
98
94
 
99
95
  export const createOpenAiChatGptDynamicModelConnection = (
100
96
  optionsArg: IOpenAiChatGptDynamicModelConnectionOptions,
101
- ): IOpenAiModelConnection => {
97
+ ): plugins.IOpenAiModelConnection => {
102
98
  if (!optionsArg || typeof optionsArg.resolveAccess !== 'function') {
103
99
  throw new OpenAiChatGptAuthError('OpenAI ChatGPT access resolver is required.');
104
100
  }
@@ -144,9 +140,9 @@ export const createOpenAiChatGptDynamicModelConnection = (
144
140
  baseURL: OPENAI_CHATGPT_CODEX_BASE_URL,
145
141
  fetch: fetchWithCurrentAccess,
146
142
  },
147
- middleware: createOpenAiChatGptInstructionsMiddleware(),
143
+ middleware: plugins.createOpenAiChatGptInstructionsMiddleware(),
148
144
  // the ChatGPT Codex backend serves the Responses API only
149
145
  apis: ['responses'],
150
- classifyLimit: classifyOpenAiChatGptLimit,
146
+ classifyLimit: plugins.classifyOpenAiChatGptLimit,
151
147
  };
152
148
  };
@@ -1,13 +1,4 @@
1
1
  import * as plugins from './plugins.js';
2
- import {
3
- parseOpenAiChatGptTokenInfo,
4
- refreshOpenAiChatGptTokenData,
5
- } from '@modelprofile.com/flexharness-providers/auth';
6
- import type {
7
- IOpenAiChatGptAuthOptions,
8
- IOpenAiChatGptTokenData,
9
- IOpenAiChatGptTokenInfo,
10
- } from '@modelprofile.com/flexharness-providers/auth';
11
2
 
12
3
  export type TOpenAiChatGptAuthSource = 'smartai' | 'opencode' | 'codex';
13
4
  export type TOpenAiChatGptAuthFileFormat = TOpenAiChatGptAuthSource | 'auto';
@@ -41,13 +32,13 @@ export interface IInspectOpenAiChatGptAuthSourcesOptions {
41
32
  export interface IResolveOpenAiChatGptAuthOptions extends IInspectOpenAiChatGptAuthSourcesOptions {
42
33
  refresh?: 'ifNeeded' | false;
43
34
  writeBack?: Partial<Record<TOpenAiChatGptAuthSource, boolean>>;
44
- authOptions?: IOpenAiChatGptAuthOptions;
35
+ authOptions?: plugins.IOpenAiChatGptAuthOptions;
45
36
  }
46
37
 
47
38
  export interface IResolvedOpenAiChatGptAuth {
48
39
  source: TOpenAiChatGptAuthSource;
49
40
  filePath: string;
50
- tokenData: IOpenAiChatGptTokenData;
41
+ tokenData: plugins.IOpenAiChatGptTokenData;
51
42
  refreshed: boolean;
52
43
  }
53
44
 
@@ -140,7 +131,7 @@ export const getDefaultOpenAiChatGptAuthPath = (
140
131
  export const normalizeOpenAiChatGptAuth = (
141
132
  input: unknown,
142
133
  format: TOpenAiChatGptAuthFileFormat = 'auto',
143
- ): IOpenAiChatGptTokenData | undefined => {
134
+ ): plugins.IOpenAiChatGptTokenData | undefined => {
144
135
  if (format === 'auto') {
145
136
  return normalizeOpenAiChatGptAuth(input, 'smartai')
146
137
  ?? normalizeOpenAiChatGptAuth(input, 'opencode')
@@ -188,7 +179,7 @@ const readBoundedAuthJson = async (filePathArg: string): Promise<unknown> =>
188
179
  export const readOpenAiChatGptAuthFile = async (
189
180
  filePath: string,
190
181
  format: TOpenAiChatGptAuthFileFormat = 'auto',
191
- ): Promise<IOpenAiChatGptTokenData | undefined> => {
182
+ ): Promise<plugins.IOpenAiChatGptTokenData | undefined> => {
192
183
  const parsed = await readBoundedAuthJson(filePath);
193
184
  return normalizeOpenAiChatGptAuth(parsed, format);
194
185
  };
@@ -232,7 +223,7 @@ export const resolveOpenAiChatGptAuth = async (
232
223
  const refresh = options.refresh ?? 'ifNeeded';
233
224
 
234
225
  for (const sourceConfig of sourceConfigs) {
235
- let tokenData: IOpenAiChatGptTokenData | undefined;
226
+ let tokenData: plugins.IOpenAiChatGptTokenData | undefined;
236
227
  try {
237
228
  tokenData = await readOpenAiChatGptAuthFile(sourceConfig.filePath!, sourceConfig.format ?? sourceConfig.source);
238
229
  } catch (error) {
@@ -273,7 +264,7 @@ export const resolveOpenAiChatGptAuth = async (
273
264
  refreshed: false,
274
265
  };
275
266
  }
276
- const refreshed = await refreshOpenAiChatGptTokenData(
267
+ const refreshed = await plugins.refreshOpenAiChatGptTokenData(
277
268
  latestTokenData,
278
269
  options.authOptions ?? {},
279
270
  );
@@ -300,7 +291,7 @@ export const resolveOpenAiChatGptAuth = async (
300
291
 
301
292
  export const writeOpenAiChatGptAuthFile = async (
302
293
  filePath: string,
303
- tokenData: IOpenAiChatGptTokenData,
294
+ tokenData: plugins.IOpenAiChatGptTokenData,
304
295
  format: TOpenAiChatGptAuthFileFormat = 'smartai',
305
296
  ): Promise<void> => {
306
297
  if (format === 'auto') throw new Error('The auto auth-file format cannot be written.');
@@ -311,7 +302,7 @@ export const writeOpenAiChatGptAuthFile = async (
311
302
 
312
303
  const writeOpenAiChatGptAuthFileUnlocked = async (
313
304
  filePath: string,
314
- tokenData: IOpenAiChatGptTokenData,
305
+ tokenData: plugins.IOpenAiChatGptTokenData,
315
306
  format: TOpenAiChatGptAuthFileFormat,
316
307
  ): Promise<void> => {
317
308
  const current = await readJsonFileIfExists(filePath);
@@ -341,7 +332,7 @@ const normalizeSourceConfigs = (
341
332
  const toInspection = (
342
333
  source: TOpenAiChatGptAuthSource,
343
334
  filePath: string,
344
- tokenData: IOpenAiChatGptTokenData,
335
+ tokenData: plugins.IOpenAiChatGptTokenData,
345
336
  now: Date,
346
337
  ): IOpenAiChatGptAuthSourceInspection => {
347
338
  const expired = isExpired(tokenData, now);
@@ -358,7 +349,7 @@ const toInspection = (
358
349
  };
359
350
  };
360
351
 
361
- const normalizeTokenObject = (input: Record<string, unknown>): IOpenAiChatGptTokenData | undefined => {
352
+ const normalizeTokenObject = (input: Record<string, unknown>): plugins.IOpenAiChatGptTokenData | undefined => {
362
353
  const accessToken = stringValue(input.accessToken) ?? stringValue(input.access_token);
363
354
  const refreshToken = stringValue(input.refreshToken) ?? stringValue(input.refresh_token);
364
355
  const idToken = stringValue(input.idToken) ?? stringValue(input.id_token);
@@ -366,7 +357,7 @@ const normalizeTokenObject = (input: Record<string, unknown>): IOpenAiChatGptTok
366
357
  return createTokenDataFromValues({ accessToken, refreshToken, idToken, accountId });
367
358
  };
368
359
 
369
- const normalizeOpenCodeAuth = (input: Record<string, unknown>): IOpenAiChatGptTokenData | undefined => {
360
+ const normalizeOpenCodeAuth = (input: Record<string, unknown>): plugins.IOpenAiChatGptTokenData | undefined => {
370
361
  if (!isRecord(input.openai)) return undefined;
371
362
  const accessToken = stringValue(input.openai.access);
372
363
  const refreshToken = stringValue(input.openai.refresh);
@@ -381,7 +372,7 @@ const createTokenDataFromValues = (input: {
381
372
  idToken?: string;
382
373
  accountId?: string;
383
374
  fallbackExpiresAt?: string;
384
- }): IOpenAiChatGptTokenData | undefined => {
375
+ }): plugins.IOpenAiChatGptTokenData | undefined => {
385
376
  if (!input.accessToken || !input.refreshToken) return undefined;
386
377
  const parseToken = input.idToken ?? input.accessToken;
387
378
  const tokenInfo = parseTokenInfo(parseToken, input.accountId, input.fallbackExpiresAt);
@@ -402,9 +393,9 @@ const createTokenDataFromValues = (input: {
402
393
  };
403
394
  };
404
395
 
405
- const parseTokenInfo = (token: string, accountId?: string, fallbackExpiresAt?: string): IOpenAiChatGptTokenInfo => {
396
+ const parseTokenInfo = (token: string, accountId?: string, fallbackExpiresAt?: string): plugins.IOpenAiChatGptTokenInfo => {
406
397
  try {
407
- const tokenInfo = parseOpenAiChatGptTokenInfo(token);
398
+ const tokenInfo = plugins.parseOpenAiChatGptTokenInfo(token);
408
399
  return {
409
400
  ...tokenInfo,
410
401
  chatgptAccountId: tokenInfo.chatgptAccountId ?? accountId,
@@ -420,7 +411,7 @@ const parseTokenInfo = (token: string, accountId?: string, fallbackExpiresAt?: s
420
411
  }
421
412
  };
422
413
 
423
- const toSmartAiAuthFile = (tokenData: IOpenAiChatGptTokenData): Record<string, unknown> => ({
414
+ const toSmartAiAuthFile = (tokenData: plugins.IOpenAiChatGptTokenData): Record<string, unknown> => ({
424
415
  accessToken: tokenData.accessToken,
425
416
  refreshToken: tokenData.refreshToken,
426
417
  idToken: tokenData.idToken,
@@ -428,7 +419,7 @@ const toSmartAiAuthFile = (tokenData: IOpenAiChatGptTokenData): Record<string, u
428
419
  tokenInfo: tokenData.tokenInfo,
429
420
  });
430
421
 
431
- const toCodexAuthFile = (current: Record<string, unknown>, tokenData: IOpenAiChatGptTokenData): Record<string, unknown> => ({
422
+ const toCodexAuthFile = (current: Record<string, unknown>, tokenData: plugins.IOpenAiChatGptTokenData): Record<string, unknown> => ({
432
423
  ...current,
433
424
  OPENAI_API_KEY: current.OPENAI_API_KEY ?? null,
434
425
  tokens: {
@@ -441,7 +432,7 @@ const toCodexAuthFile = (current: Record<string, unknown>, tokenData: IOpenAiCha
441
432
  last_refresh: new Date().toISOString(),
442
433
  });
443
434
 
444
- const toOpenCodeAuthFile = (current: Record<string, unknown>, tokenData: IOpenAiChatGptTokenData): Record<string, unknown> => ({
435
+ const toOpenCodeAuthFile = (current: Record<string, unknown>, tokenData: plugins.IOpenAiChatGptTokenData): Record<string, unknown> => ({
445
436
  ...current,
446
437
  openai: {
447
438
  ...(isRecord(current.openai) ? current.openai : {}),
@@ -453,12 +444,12 @@ const toOpenCodeAuthFile = (current: Record<string, unknown>, tokenData: IOpenAi
453
444
  },
454
445
  });
455
446
 
456
- const shouldRefreshToken = (tokenData: IOpenAiChatGptTokenData, now: Date): boolean => {
447
+ const shouldRefreshToken = (tokenData: plugins.IOpenAiChatGptTokenData, now: Date): boolean => {
457
448
  if (!tokenData.tokenInfo.expiresAt) return false;
458
449
  return Date.parse(tokenData.tokenInfo.expiresAt) - now.getTime() < refreshWindowMs;
459
450
  };
460
451
 
461
- const isExpired = (tokenData: IOpenAiChatGptTokenData, now: Date): boolean => {
452
+ const isExpired = (tokenData: plugins.IOpenAiChatGptTokenData, now: Date): boolean => {
462
453
  if (!tokenData.tokenInfo.expiresAt) return false;
463
454
  return Date.parse(tokenData.tokenInfo.expiresAt) <= now.getTime();
464
455
  };
@@ -11,3 +11,13 @@ import * as properLockfile from 'proper-lockfile';
11
11
 
12
12
  export { crypto, fs, fsConstants, os, path, properLockfile };
13
13
  export type { FileHandle };
14
+
15
+ // @modelprofile.com scope
16
+ import { parseOpenAiChatGptTokenInfo, refreshOpenAiChatGptTokenData } from '@modelprofile.com/flexharness-providers/auth';
17
+
18
+ export { parseOpenAiChatGptTokenInfo, refreshOpenAiChatGptTokenData };
19
+ export type {
20
+ IOpenAiChatGptAuthOptions,
21
+ IOpenAiChatGptTokenData,
22
+ IOpenAiChatGptTokenInfo,
23
+ } from '@modelprofile.com/flexharness-providers/auth';
@@ -2,10 +2,19 @@ import { createAnthropic } from '@ai-sdk/anthropic';
2
2
  import { wrapLanguageModel } from 'ai';
3
3
  import {
4
4
  createModelLimitMiddleware,
5
+ createSmartAiCachingMiddleware,
5
6
  readEpochSeconds,
6
7
  readJsonRecord,
7
8
  } from '@modelprofile.com/flexharness-models';
8
- export { createAnthropic, createModelLimitMiddleware, readEpochSeconds, readJsonRecord, wrapLanguageModel };
9
+ export {
10
+ createAnthropic,
11
+ createModelLimitMiddleware,
12
+ createSmartAiCachingMiddleware,
13
+ readEpochSeconds,
14
+ readJsonRecord,
15
+ wrapLanguageModel,
16
+ };
17
+ export type { LanguageModelV4Middleware } from '@ai-sdk/provider';
9
18
  export type {
10
19
  IModelCallFailure,
11
20
  IModelProvider,
@@ -1,12 +1,10 @@
1
- import type { LanguageModelV4Middleware } from '@ai-sdk/provider';
2
- import { createSmartAiCachingMiddleware } from '@modelprofile.com/flexharness-models';
3
- import type { ISmartAiCacheOptions } from '@modelprofile.com/flexharness-models';
1
+ import * as plugins from './plugins.js';
4
2
 
5
3
  /**
6
4
  * Creates middleware that adds Anthropic prompt caching directives.
7
5
  * Marks the last system message and last user message with ephemeral cache control,
8
6
  * reducing input token cost and latency on repeated calls.
9
7
  */
10
- export function createAnthropicCachingMiddleware(options: ISmartAiCacheOptions = {}): LanguageModelV4Middleware {
11
- return createSmartAiCachingMiddleware({ ...options, provider: 'anthropic' });
8
+ export function createAnthropicCachingMiddleware(options: plugins.ISmartAiCacheOptions = {}): plugins.LanguageModelV4Middleware {
9
+ return plugins.createSmartAiCachingMiddleware({ ...options, provider: 'anthropic' });
12
10
  }
@@ -1,7 +1,7 @@
1
- import type { IModelProvider } from '@modelprofile.com/flexharness-models';
1
+ import type * as plugins from './plugins.js';
2
2
  import type { IOllamaModelRequest } from './interfaces.js';
3
3
  import { createOllamaModel } from './smartai.provider.ollama.js';
4
- export const createOllamaModelProvider = (): IModelProvider<IOllamaModelRequest> => ({
4
+ export const createOllamaModelProvider = (): plugins.IModelProvider<IOllamaModelRequest> => ({
5
5
  id: 'ollama', getModel: createOllamaModel,
6
6
  });
7
7
  export { createOllamaModel };
@@ -1,6 +1,6 @@
1
- import type { ISmartAiOptions } from '@modelprofile.com/flexharness-models';
1
+ import type * as plugins from './plugins.js';
2
2
 
3
- export interface IOllamaModelRequest extends ISmartAiOptions {
3
+ export interface IOllamaModelRequest extends plugins.ISmartAiOptions {
4
4
  provider: 'ollama';
5
5
  ollamaOptions?: IOllamaModelOptions;
6
6
  }
@@ -0,0 +1,12 @@
1
+ export type {
2
+ LanguageModelV3,
3
+ LanguageModelV3CallOptions,
4
+ LanguageModelV3Content,
5
+ LanguageModelV3FinishReason,
6
+ LanguageModelV3GenerateResult,
7
+ LanguageModelV3Prompt,
8
+ LanguageModelV3StreamPart,
9
+ LanguageModelV3StreamResult,
10
+ LanguageModelV3Usage,
11
+ } from '@ai-sdk/provider';
12
+ export type { IModelProvider, ISmartAiOptions } from '@modelprofile.com/flexharness-models';
@@ -1,14 +1,4 @@
1
- import type {
2
- LanguageModelV3,
3
- LanguageModelV3CallOptions,
4
- LanguageModelV3GenerateResult,
5
- LanguageModelV3StreamResult,
6
- LanguageModelV3StreamPart,
7
- LanguageModelV3Prompt,
8
- LanguageModelV3Content,
9
- LanguageModelV3Usage,
10
- LanguageModelV3FinishReason,
11
- } from '@ai-sdk/provider';
1
+ import type * as plugins from './plugins.js';
12
2
  import type { IOllamaModelRequest, IOllamaModelOptions } from './interfaces.js';
13
3
 
14
4
  interface IOllamaMessage {
@@ -33,7 +23,7 @@ interface IOllamaTool {
33
23
  /**
34
24
  * Convert AI SDK V3 prompt messages to Ollama's message format.
35
25
  */
36
- function convertPromptToOllamaMessages(prompt: LanguageModelV3Prompt): IOllamaMessage[] {
26
+ function convertPromptToOllamaMessages(prompt: plugins.LanguageModelV3Prompt): IOllamaMessage[] {
37
27
  const messages: IOllamaMessage[] = [];
38
28
 
39
29
  for (const msg of prompt) {
@@ -106,7 +96,7 @@ function convertPromptToOllamaMessages(prompt: LanguageModelV3Prompt): IOllamaMe
106
96
  /**
107
97
  * Convert AI SDK V3 tools to Ollama's tool format.
108
98
  */
109
- function convertToolsToOllamaTools(tools: LanguageModelV3CallOptions['tools']): IOllamaTool[] | undefined {
99
+ function convertToolsToOllamaTools(tools: plugins.LanguageModelV3CallOptions['tools']): IOllamaTool[] | undefined {
110
100
  if (!tools || tools.length === 0) return undefined;
111
101
 
112
102
  return tools
@@ -121,7 +111,7 @@ function convertToolsToOllamaTools(tools: LanguageModelV3CallOptions['tools']):
121
111
  }));
122
112
  }
123
113
 
124
- function makeUsage(promptTokens?: number, completionTokens?: number): LanguageModelV3Usage {
114
+ function makeUsage(promptTokens?: number, completionTokens?: number): plugins.LanguageModelV3Usage {
125
115
  return {
126
116
  inputTokens: {
127
117
  total: promptTokens,
@@ -137,7 +127,7 @@ function makeUsage(promptTokens?: number, completionTokens?: number): LanguageMo
137
127
  };
138
128
  }
139
129
 
140
- function makeFinishReason(reason?: string): LanguageModelV3FinishReason {
130
+ function makeFinishReason(reason?: string): plugins.LanguageModelV3FinishReason {
141
131
  if (reason === 'tool_calls' || reason === 'tool-calls') {
142
132
  return { unified: 'tool-calls', raw: reason };
143
133
  }
@@ -154,7 +144,7 @@ function generateId(): string {
154
144
  * Calls Ollama's native /api/chat endpoint directly to support
155
145
  * think, num_ctx, temperature, and other model options.
156
146
  */
157
- export function createOllamaModel(options: IOllamaModelRequest): LanguageModelV3 {
147
+ export function createOllamaModel(options: IOllamaModelRequest): plugins.LanguageModelV3 {
158
148
  const baseUrl = options.baseUrl ?? 'http://localhost:11434';
159
149
  const modelId = options.model;
160
150
  const ollamaOpts: IOllamaModelOptions = { ...options.ollamaOptions };
@@ -164,13 +154,13 @@ export function createOllamaModel(options: IOllamaModelRequest): LanguageModelV3
164
154
  ollamaOpts.temperature = 0.55;
165
155
  }
166
156
 
167
- const model: LanguageModelV3 = {
157
+ const model: plugins.LanguageModelV3 = {
168
158
  specificationVersion: 'v3',
169
159
  provider: 'ollama',
170
160
  modelId,
171
161
  supportedUrls: {},
172
162
 
173
- async doGenerate(callOptions: LanguageModelV3CallOptions): Promise<LanguageModelV3GenerateResult> {
163
+ async doGenerate(callOptions: plugins.LanguageModelV3CallOptions): Promise<plugins.LanguageModelV3GenerateResult> {
174
164
  const messages = convertPromptToOllamaMessages(callOptions.prompt);
175
165
  const tools = convertToolsToOllamaTools(callOptions.tools);
176
166
 
@@ -215,7 +205,7 @@ export function createOllamaModel(options: IOllamaModelRequest): LanguageModelV3
215
205
  const message = result.message as Record<string, unknown>;
216
206
 
217
207
  // Build content array
218
- const content: LanguageModelV3Content[] = [];
208
+ const content: plugins.LanguageModelV3Content[] = [];
219
209
 
220
210
  // Add reasoning if present
221
211
  if (message.thinking && typeof message.thinking === 'string') {
@@ -256,7 +246,7 @@ export function createOllamaModel(options: IOllamaModelRequest): LanguageModelV3
256
246
  };
257
247
  },
258
248
 
259
- async doStream(callOptions: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
249
+ async doStream(callOptions: plugins.LanguageModelV3CallOptions): Promise<plugins.LanguageModelV3StreamResult> {
260
250
  const messages = convertPromptToOllamaMessages(callOptions.prompt);
261
251
  const tools = convertToolsToOllamaTools(callOptions.tools);
262
252
 
@@ -304,7 +294,7 @@ export function createOllamaModel(options: IOllamaModelRequest): LanguageModelV3
304
294
  let hasToolCalls = false;
305
295
  let closed = false;
306
296
 
307
- const stream = new ReadableStream<LanguageModelV3StreamPart>({
297
+ const stream = new ReadableStream<plugins.LanguageModelV3StreamPart>({
308
298
  async pull(controller) {
309
299
  if (closed) return;
310
300
 
@@ -43,8 +43,9 @@ const model = models.getModel({
43
43
  A spent API balance (`insufficient_quota`) fails as a `ModelLimitError` of kind `usage_limit`,
44
44
  and any other 429 as kind `rate_limit` with the `retry-after` delay; see the toolbox readme's
45
45
  usage and rate limits section. A `connection` can add its own limit dialect with
46
- `classifyLimit`, which is consulted first. `classifyOpenAiLimit` and `readOpenAiError` are
47
- exported for connections that extend the OpenAI dialect.
46
+ `classifyLimit`, which is consulted first. A limit a stream reports, in a `response.failed` or an
47
+ `error` event, before or after the answer began, is classified the same way. `classifyOpenAiLimit`
48
+ and `readOpenAiError` are exported for connections that extend the OpenAI dialect.
48
49
 
49
50
  ## ChatGPT with access from an account authority
50
51
 
@@ -1,19 +1,27 @@
1
1
  import * as plugins from './plugins.js';
2
2
 
3
- /** The error object of an OpenAI error body or of a Responses `response.failed` stream frame. */
3
+ /**
4
+ * The error object of an OpenAI error body, of a Responses `response.failed` stream frame or of a
5
+ * Responses `error` stream frame.
6
+ */
4
7
  export interface IOpenAiErrorDetails {
5
8
  /** The error's `type` and `code`; HTTP bodies name the error in `type`, stream frames in `code`. */
6
9
  readonly identifiers: readonly string[];
7
10
  readonly fields: Readonly<Record<string, unknown>>;
8
11
  }
9
12
 
13
+ function readIdentifiers(...values: unknown[]): string[] {
14
+ return values.filter((value): value is string => typeof value === 'string');
15
+ }
16
+
10
17
  export function readOpenAiError(body: unknown): IOpenAiErrorDetails | undefined {
11
18
  const envelope = plugins.readJsonRecord(body);
12
19
  const fields = plugins.readJsonRecord(envelope?.error)
13
20
  ?? plugins.readJsonRecord(plugins.readJsonRecord(envelope?.response)?.error);
14
- if (!fields) return undefined;
15
- const identifiers = [fields.type, fields.code].filter((value): value is string => typeof value === 'string');
16
- return { identifiers, fields };
21
+ if (fields) return { identifiers: readIdentifiers(fields.type, fields.code), fields };
22
+ // an `error` stream frame may carry its fields beside `type: 'error'`, which names the frame, not the error
23
+ if (envelope?.type === 'error') return { identifiers: readIdentifiers(envelope.code), fields: envelope };
24
+ return undefined;
17
25
  }
18
26
 
19
27
  /** OpenAI API limits: `insufficient_quota` is an exhausted balance, any other 429 a rate limit. */