@fastagent-sh/fastagent 0.24.0 → 0.24.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.
@@ -10,6 +10,7 @@ import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
10
10
  import { resolveModel } from "./config.js";
11
11
  import { activePath, resolveSessionSettings } from "./session-settings.js";
12
12
  import { DEFAULT_THINKING_LEVEL, withModelRegistration } from "./models.js";
13
+ import { registerAccountModels } from "./openai-account-models.js";
13
14
  import { agentSessionManager, sessionToolActivation, turnContext } from "./tool-context.js";
14
15
  /** fastagent's tools as pi tool definitions, bound to ONE session. */
15
16
  function toolDefinitions(tools, bound, sessionId) {
@@ -275,6 +276,10 @@ export async function definitionServices(options) {
275
276
  }),
276
277
  extensionsOverride: admissionFirst,
277
278
  },
279
+ }).then((services) => {
280
+ // AFTER the extensions: one that re-registers `openai` replaced the account-catalog wrapper.
281
+ registerAccountModels(modelRuntime);
282
+ return services;
278
283
  }));
279
284
  reportExtensionDiagnostics(services);
280
285
  return services;
@@ -13,9 +13,13 @@ import { ModelRuntime } from "@earendil-works/pi-coding-agent";
13
13
  import { AGENT_MODEL_CATALOG_FILE, AGENT_MODELS_FILE, globalHome, resolveOverridePath } from "../../paths.js";
14
14
  import { writeFileAtomic } from "../../atomic-write.js";
15
15
  import { withLockedFile } from "./locked-file.js";
16
+ import { OPENAI_PROVIDER, registerAccountModels, withAccountModels } from "./openai-account-models.js";
16
17
  /** The built-ins plus `providers` (a same id replaces a built-in), over any credential store. */
17
18
  export function piModelsOver(credentials, providers = []) {
18
19
  const models = builtinModels({ credentials, authContext: defaultProviderAuthContext() });
20
+ const openai = models.getProvider(OPENAI_PROVIDER);
21
+ if (openai)
22
+ models.setProvider(withAccountModels(openai));
19
23
  for (const provider of providers)
20
24
  models.setProvider(provider);
21
25
  return models;
@@ -281,6 +285,8 @@ export async function machineModelRuntime(options = {}) {
281
285
  const error = runtime.getError();
282
286
  if (error)
283
287
  throw new Error(error);
288
+ // A machine catalog refresh may refresh an OAuth token, which must carry the account's catalog over.
289
+ await withModelRegistration(runtime, async () => registerAccountModels(runtime));
284
290
  return runtime;
285
291
  }
286
292
  /** How long a catalog refresh may take, as `pi update --models` allows. */
@@ -383,6 +389,7 @@ export async function createPiModelRuntime(options) {
383
389
  throw new Error(`${error}${origin}`);
384
390
  }
385
391
  await withModelRegistration(runtime, async () => {
392
+ registerAccountModels(runtime);
386
393
  for (const provider of options.providers ?? [])
387
394
  runtime.registerNativeProvider(provider);
388
395
  });
@@ -101,9 +101,12 @@ export declare function assembleFront(front: AgentAssembly, extra?: {
101
101
  * `models.json`, and what its `extensions/` declare) filtered to the providers whose credentials are configured. The
102
102
  * directory needs no model set, and the same placement and credential layers as the opener apply, so a listed spec
103
103
  * authenticates there. Configuration is checked, not validity: no OAuth token is refreshed and no provider is called.
104
+ * A Sign in with ChatGPT on `openai` lists the account's own models (openai-account-models.ts), not pi's built-ins.
104
105
  *
105
106
  * `warn` reaches the credential store. An unreadable or corrupt credentials file otherwise reads as "nothing
106
- * configured", so a client that must not show that as an empty list passes a sink that throws.
107
+ * configured", so a client that must not show that as an empty list passes a sink that throws. A ChatGPT sign-in that
108
+ * carries no catalog is a normal, recoverable state (signed in before the catalog was read), not that: it is logged,
109
+ * never sent to `warn`, so a throwing sink does not fail the whole listing for it.
107
110
  */
108
111
  export declare function availableModelsFromDir(dir: string, options?: FastagentAuthOptions & CredentialSourceOptions): Promise<ModelDescriptor[]>;
109
112
  /**
@@ -17,6 +17,8 @@ import { reportFindingsIfChanged } from "./report.js";
17
17
  import { readMachine, withMachine } from "./machine.js";
18
18
  import { createPiModelRuntime, globalCatalogPath, machineModelRuntime, refreshCatalog } from "./models.js";
19
19
  import { agentModels } from "./agent-models.js";
20
+ import { OPENAI_PROVIDER, missingAccountModels } from "./openai-account-models.js";
21
+ import { log } from "../../log.js";
20
22
  import { piSessionRecordStore } from "./session-store.js";
21
23
  import { gateSecrets } from "../../secrets-gate.js";
22
24
  /**
@@ -126,14 +128,21 @@ export function assembleFront(front, extra = {}) {
126
128
  * `models.json`, and what its `extensions/` declare) filtered to the providers whose credentials are configured. The
127
129
  * directory needs no model set, and the same placement and credential layers as the opener apply, so a listed spec
128
130
  * authenticates there. Configuration is checked, not validity: no OAuth token is refreshed and no provider is called.
131
+ * A Sign in with ChatGPT on `openai` lists the account's own models (openai-account-models.ts), not pi's built-ins.
129
132
  *
130
133
  * `warn` reaches the credential store. An unreadable or corrupt credentials file otherwise reads as "nothing
131
- * configured", so a client that must not show that as an empty list passes a sink that throws.
134
+ * configured", so a client that must not show that as an empty list passes a sink that throws. A ChatGPT sign-in that
135
+ * carries no catalog is a normal, recoverable state (signed in before the catalog was read), not that: it is logged,
136
+ * never sent to `warn`, so a throwing sink does not fail the whole listing for it.
132
137
  */
133
138
  export async function availableModelsFromDir(dir, options = {}) {
134
139
  const { agentDir, workspace } = resolvePlacement(dir);
135
- const models = await agentModels(agentDir, options, { cwd: workspace }).runtime();
136
- return describeModels(await models.getAvailable());
140
+ const environment = agentModels(agentDir, options, { cwd: workspace });
141
+ const available = await (await environment.runtime()).getAvailable();
142
+ const missing = missingAccountModels(await environment.credentials.read(OPENAI_PROVIDER));
143
+ if (missing)
144
+ log.warn(missing);
145
+ return describeModels(available);
137
146
  }
138
147
  /**
139
148
  * Refresh the agent's model catalog (`<agent dir>/models-store.json`) with the credentials
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The models a Sign in with ChatGPT can run on the `openai` provider: the ACCOUNT's catalog, which OpenAI publishes at
3
+ * `GET /v1/models` for the same access token, not pi's built-in list (most of which such an account is refused).
4
+ *
5
+ * pi lists a provider's models through `filterModels`, which is synchronous, so the catalog is read when there is a
6
+ * token to read it with (login and every token refresh) and kept on the credential, like the account it belongs to:
7
+ * a new account brings its own list, and nothing per-account lands in the definition's model catalog. pi's `openai`
8
+ * provider does not do this itself (checked against pi 0.99.2), so {@link withAccountModels} wraps it. An API key on the same
9
+ * provider keeps the built-in list.
10
+ */
11
+ import type { Credential, Provider } from "@earendil-works/pi-ai";
12
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
13
+ export declare const OPENAI_PROVIDER = "openai";
14
+ /**
15
+ * Why the stored `openai` credential lists no models, when that is because its sign-in carries no catalog: the one
16
+ * wording a listing reports instead of falling back to every built-in model.
17
+ */
18
+ export declare function missingAccountModels(credential: Credential | undefined): string | undefined;
19
+ /**
20
+ * `provider` with the account catalog: read at login and at each token refresh, and the only models a ChatGPT
21
+ * sign-in lists. Anything without OAuth is returned as is.
22
+ */
23
+ export declare function withAccountModels(provider: Provider): Provider;
24
+ /**
25
+ * Put {@link withAccountModels} on a runtime's `openai`, over the provider the runtime composed (pi's remote catalog,
26
+ * the agent's models.json, and an extension's `registerProvider("openai", …)` included), so none of them is lost. pi
27
+ * composes a native provider with models.json once more; that second pass is idempotent today, and
28
+ * openai-account-models.test.ts holds it to that. Call it inside `withModelRegistration`, and again after extensions
29
+ * load: pi's `registerProvider` drops a native provider, and a refresh without the wrapper would store a credential
30
+ * without its catalog. Repeating it is harmless.
31
+ *
32
+ * Known ceiling: an extension that registers `openai` later than its load (from an event handler) drops the wrapper
33
+ * for that runtime.
34
+ */
35
+ export declare function registerAccountModels(runtime: ModelRuntime): void;
@@ -0,0 +1,116 @@
1
+ import { log } from "../../log.js";
2
+ export const OPENAI_PROVIDER = "openai";
3
+ const ACCOUNT_MODELS_URL = "https://api.openai.com/v1/models";
4
+ /** Where the catalog is kept on the stored credential: the model ids the account lists, in OpenAI's order. */
5
+ const ACCOUNT_MODELS_FIELD = "accountModels";
6
+ /** A token refresh is bounded at 15s by pi; the catalog read must leave it room to finish and be stored. */
7
+ const CATALOG_TIMEOUT_MS = 5_000;
8
+ /** The slugs the account lists for a picker (`visibility: "list"`), in the server's order. */
9
+ async function fetchAccountModels(access, signal) {
10
+ const timeout = AbortSignal.timeout(CATALOG_TIMEOUT_MS);
11
+ const response = await fetch(ACCOUNT_MODELS_URL, {
12
+ headers: { accept: "application/json", authorization: `Bearer ${access}` },
13
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
14
+ });
15
+ if (!response.ok) {
16
+ const body = await response.text().catch(() => "");
17
+ throw new Error(`GET ${ACCOUNT_MODELS_URL} answered ${response.status}: ${body || response.statusText}`);
18
+ }
19
+ const models = (await response.json())?.models;
20
+ if (!Array.isArray(models))
21
+ throw new Error(`GET ${ACCOUNT_MODELS_URL} answered without a "models" array`);
22
+ return models.flatMap((entry) => entry?.visibility === "list" && typeof entry.slug === "string" ? [entry.slug] : []);
23
+ }
24
+ /** The catalog a ChatGPT sign-in carries, or undefined when it carries none (signed in before it was read). */
25
+ function accountModels(credential) {
26
+ const ids = credential[ACCOUNT_MODELS_FIELD];
27
+ return Array.isArray(ids) && ids.every((id) => typeof id === "string") ? ids : undefined;
28
+ }
29
+ /**
30
+ * Why the stored `openai` credential lists no models, when that is because its sign-in carries no catalog: the one
31
+ * wording a listing reports instead of falling back to every built-in model.
32
+ */
33
+ export function missingAccountModels(credential) {
34
+ if (credential?.type !== "oauth" || accountModels(credential))
35
+ return undefined;
36
+ return ("[fastagent] the ChatGPT sign-in for openai carries no model catalog, so it lists no models: it is read at " +
37
+ "login and on each token refresh. Run `fastagent login` to read it now");
38
+ }
39
+ /**
40
+ * `provider` with the account catalog: read at login and at each token refresh, and the only models a ChatGPT
41
+ * sign-in lists. Anything without OAuth is returned as is.
42
+ */
43
+ export function withAccountModels(provider) {
44
+ const oauth = provider.auth.oauth;
45
+ if (!oauth)
46
+ return provider;
47
+ const wrapped = {
48
+ ...oauth,
49
+ async login(interaction, options) {
50
+ const credential = await oauth.login(interaction, options);
51
+ try {
52
+ return {
53
+ ...credential,
54
+ [ACCOUNT_MODELS_FIELD]: await fetchAccountModels(credential.access, interaction.signal),
55
+ };
56
+ }
57
+ catch (error) {
58
+ // The sign-in itself worked and inference needs nothing more: keep it, and say the list is empty until the
59
+ // next token refresh reads the catalog.
60
+ interaction.notify({
61
+ type: "info",
62
+ message: `could not read this ChatGPT account's model catalog (${error.message}); it lists no models until the next token refresh or login`,
63
+ });
64
+ return credential;
65
+ }
66
+ },
67
+ async refresh(credential, signal) {
68
+ const next = await oauth.refresh(credential, signal);
69
+ try {
70
+ return { ...next, [ACCOUNT_MODELS_FIELD]: await fetchAccountModels(next.access, signal) };
71
+ }
72
+ catch (error) {
73
+ // NEVER fail here: the refresh token was just rotated, and a throw would leave the new one unstored and the
74
+ // old one spent. The previous catalog stands.
75
+ log.warn(`[fastagent] could not refresh the ChatGPT account's model catalog: ${error.message}`);
76
+ const previous = accountModels(credential);
77
+ return previous ? { ...next, [ACCOUNT_MODELS_FIELD]: previous } : next;
78
+ }
79
+ },
80
+ };
81
+ return {
82
+ ...provider,
83
+ auth: { ...provider.auth, oauth: wrapped },
84
+ filterModels: (models, credential) => {
85
+ const base = provider.filterModels?.(models, credential) ?? models;
86
+ if (credential?.type !== "oauth")
87
+ return base;
88
+ const listed = new Set(accountModels(credential) ?? []);
89
+ return base.filter((model) => listed.has(model.id));
90
+ },
91
+ };
92
+ }
93
+ /** Providers this module built, so a second registration leaves them as they are instead of wrapping them again. */
94
+ const wrappedProviders = new WeakSet();
95
+ /**
96
+ * Put {@link withAccountModels} on a runtime's `openai`, over the provider the runtime composed (pi's remote catalog,
97
+ * the agent's models.json, and an extension's `registerProvider("openai", …)` included), so none of them is lost. pi
98
+ * composes a native provider with models.json once more; that second pass is idempotent today, and
99
+ * openai-account-models.test.ts holds it to that. Call it inside `withModelRegistration`, and again after extensions
100
+ * load: pi's `registerProvider` drops a native provider, and a refresh without the wrapper would store a credential
101
+ * without its catalog. Repeating it is harmless.
102
+ *
103
+ * Known ceiling: an extension that registers `openai` later than its load (from an event handler) drops the wrapper
104
+ * for that runtime.
105
+ */
106
+ export function registerAccountModels(runtime) {
107
+ const registered = runtime.getRegisteredNativeProvider(OPENAI_PROVIDER);
108
+ if (registered && wrappedProviders.has(registered))
109
+ return;
110
+ const provider = runtime.getProvider(OPENAI_PROVIDER);
111
+ if (!provider)
112
+ return;
113
+ const wrapped = withAccountModels(provider);
114
+ wrappedProviders.add(wrapped);
115
+ runtime.registerNativeProvider(wrapped);
116
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastagent-sh/fastagent",
3
- "version": "0.24.0",
3
+ "version": "0.24.1",
4
4
  "description": "Vibe first. Then FastAgent: turn a local agent directory into a live service in your app, on Telegram, Slack, Feishu, or behind any channel.",
5
5
  "keywords": [
6
6
  "agent",