@ultimat3/cli 31.37.0 → 31.38.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 (44) hide show
  1. package/package.json +29 -29
  2. package/src/cmd-planned.ts +5 -28
  3. package/src/generate-sign-in-runtime.ts +70 -0
  4. package/src/generate-sign-in.ts +19 -6
  5. package/src/generate-write.ts +12 -0
  6. package/src/island-plugin-path.ts +35 -0
  7. package/src/island-realtime.ts +11 -8
  8. package/src/island-runtime.ts +4 -1
  9. package/src/new-shapes.ts +10 -1
  10. package/src/templates/shapes/agent-actions.ts +224 -0
  11. package/src/templates/shapes/agent-job.ts +171 -0
  12. package/src/templates/shapes/agent-model.ts +271 -0
  13. package/src/templates/shapes/agent-prompt.ts +254 -0
  14. package/src/templates/shapes/agent-scripted.ts +56 -0
  15. package/src/templates/shapes/agent.ts +138 -0
  16. package/src/templates/shapes/content-admin-es.ts +95 -0
  17. package/src/templates/shapes/content-pages.ts +221 -0
  18. package/src/templates/shapes/content-site.ts +343 -0
  19. package/src/templates/shapes/content.ts +133 -0
  20. package/src/templates/shapes/index.ts +10 -0
  21. package/src/templates/shapes/offline-e2e.ts +123 -0
  22. package/src/templates/shapes/offline-form.ts +334 -0
  23. package/src/templates/shapes/offline.ts +118 -0
  24. package/src/templates/shapes/realtime-mutator.ts +136 -0
  25. package/src/templates/shapes/realtime-nodes.ts +203 -0
  26. package/src/templates/shapes/realtime-slice.ts +166 -0
  27. package/src/templates/shapes/realtime.ts +162 -0
  28. package/src/templates/shapes/saas-billing-tests.ts +135 -0
  29. package/src/templates/shapes/saas-billing.ts +137 -0
  30. package/src/templates/shapes/saas-receiver.ts +136 -0
  31. package/src/templates/shapes/saas.ts +112 -0
  32. package/src/templates/sign-in-oidc.ts +2 -4
  33. package/src/templates/sign-in-runtime.ts +172 -0
  34. package/src/templates/sign-in-shared.ts +5 -36
  35. package/wiki/Building-Your-Own-Base.md +339 -0
  36. package/wiki/CLI-Reference.md +1 -14
  37. package/wiki/Caching-And-Invalidation.md +1 -1
  38. package/wiki/Entities-And-Migrations.md +2 -2
  39. package/wiki/Known-Gaps.md +8 -2
  40. package/wiki/MCP-And-AI.md +3 -3
  41. package/wiki/Money.md +1 -1
  42. package/wiki/Shapes.md +18 -9
  43. package/wiki/Troubleshooting.md +1 -1
  44. package/wiki/Upgrading.md +1 -1
@@ -0,0 +1,171 @@
1
+ // The `agent` shape's long run: `draftPost` as an `agentJob()` — a factory over `job()` — acting as
2
+ // the org's assistant, and `queueDraft`, the action (and MCP tool) that enqueues it. Each with its
3
+ // test: the declaration in the `job` suite, the whole run through the queue in `unit`.
4
+
5
+ import type { GeneratedFile } from '../naming';
6
+ import { ASSISTANT_DIR } from './agent-model';
7
+
8
+ const ORG = '00000000-0000-4000-8000-000000000002';
9
+
10
+ const job =
11
+ (): string => `// draftPostLater: \`draftPost\` as durable background work — a model run is tens of seconds, never
12
+ // inside a client's wait. \`agentJob()\` is a factory over \`job()\`, so the queue, the retries, the
13
+ // dead-letter path and \`x jobs show\` are the framework's.
14
+ //
15
+ // A worker's own actor is nobody, so the run acts as the org's ASSISTANT: an agent actor of the org
16
+ // its input names, holding the \`assistant\` role \`shared/roles.ts\` grants — re-made on every
17
+ // attempt, never trusted from the payload. The write it makes is \`draftPost\`'s, idempotent by id.
18
+
19
+ import { agentJob } from '@ultimat3/ai';
20
+ import { agentActor } from '@ultimat3/core';
21
+ import { draftPost } from '../actions/draft-post';
22
+
23
+ /** Who a queued draft acts as: the org's assistant, and only in that org. */
24
+ export const assistantActor = (orgId: string) =>
25
+ agentActor({ id: 'assistant', orgId, roles: ['assistant'] });
26
+
27
+ export const draftPostLater = agentJob(draftPost, {
28
+ name: 'assistant.draft-post',
29
+ tenant: (input) => input.orgId,
30
+ retry: { attempts: 3, backoff: 'exponential' },
31
+ idempotencyKey: (input) => \`assistant.draft-post:\${input.id}\`,
32
+ actor: ({ input }) => assistantActor(input.orgId),
33
+ });
34
+ `;
35
+
36
+ const jobSuite =
37
+ (): string => `// draftPostLater's declaration against a real queue driver: its key, its tenant, its dedupe. The
38
+ // run itself — the agent, the tool, the write — is \`draft-post-later.test.ts\`'s.
39
+ import { memoryJobDriver } from '@ultimat3/jobs';
40
+ import { beforeAll, expect, jobTest, swapAdapter } from '@ultimat3/testing';
41
+ import { draftPostLater } from './draft-post-later';
42
+
43
+ const input = {
44
+ id: '00000000-0000-4000-8000-0000000000d1',
45
+ orgId: '${ORG}',
46
+ topic: 'How we review a pull request',
47
+ price: { minor: 0, currency: 'USD' },
48
+ };
49
+
50
+ beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
51
+
52
+ jobTest('one queued draft per post id, under the org its input names', () => {
53
+ expect(draftPostLater.name).toBe('assistant.draft-post');
54
+ expect(draftPostLater.idempotencyKeyFor(input)).toBe(\`assistant.draft-post:\${input.id}\`);
55
+ expect(draftPostLater.tenantFor(input)).toBe(input.orgId);
56
+ expect(draftPostLater.retry.attempts).toBe(3);
57
+ });
58
+
59
+ jobTest('a second enqueue of the same draft is the same row', async () => {
60
+ expect((await draftPostLater.enqueue(input)).deduped).toBe(false);
61
+ expect((await draftPostLater.enqueue(input)).deduped).toBe(true);
62
+ });
63
+ `;
64
+
65
+ const jobRunTest =
66
+ (): string => `// draftPostLater run by a worker in this process: no actor at all, so what this pins is that the
67
+ // run authorises as the org's assistant, calls its tool, and writes the post it was given the id of.
68
+ import { driver } from '@APP/db';
69
+ import { ctxOf, runWithContext } from '@ultimat3/core';
70
+ import { testActor } from '@ultimat3/policy';
71
+ import { afterEach, expect, swapAdapter, unitTest } from '@ultimat3/testing';
72
+ import '../../../api/index';
73
+ import '../../../shared/roles';
74
+ import * as repo from '../../post/repo';
75
+ import { scriptedGateway } from '../scripted-model';
76
+ import { assistantActor, draftPostLater } from './draft-post-later';
77
+
78
+ const orgId = '${ORG}';
79
+ const input = {
80
+ id: '00000000-0000-4000-8000-0000000000d1',
81
+ orgId,
82
+ topic: 'How we review a pull request',
83
+ price: { minor: 0, currency: 'USD' },
84
+ };
85
+
86
+ afterEach(() => {
87
+ driver.reset?.();
88
+ });
89
+
90
+ unitTest('the assistant is an agent of the org its input names', () => {
91
+ expect(assistantActor(orgId)).toMatchObject({ kind: 'agent', orgId, roles: ['assistant'] });
92
+ });
93
+
94
+ unitTest('a queued draft runs as the assistant and keeps the post', async ({ runJobs }) => {
95
+ const { gateway } = scriptedGateway([
96
+ { call: 'postTitles', input: {} },
97
+ { answer: { title: 'Two readers, one diff' } },
98
+ ]);
99
+ await swapAdapter('aiGateway', gateway);
100
+ const trace = await runJobs(draftPostLater, input);
101
+ expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
102
+ const reader = ctxOf({ actor: testActor('reader', { orgId }).actor });
103
+ const kept = await runWithContext(reader, () => repo.byId(input.id));
104
+ expect(kept?.title).toBe('Two readers, one diff');
105
+ });
106
+ `;
107
+
108
+ const queueDraft =
109
+ (): string => `// queueDraft: ask the assistant for a post in the background. Answers at once with the id the post
110
+ // will have; \`postList\` shows it when the run lands. The tool an MCP client calls to start a long
111
+ // agent run without waiting on it.
112
+
113
+ import { action, t } from '@ultimat3/action';
114
+ import { orgOf } from '../../post/actions/create-post';
115
+ import { canPostCreate } from '../../post/policy';
116
+ import { draftPostLater } from '../jobs/draft-post-later';
117
+
118
+ export const queueDraft = action({
119
+ input: t.object({ topic: t.string.min(1).max(200), price: t.money }),
120
+ output: t.object({ id: t.uuid, jobId: t.string }),
121
+ policy: canPostCreate,
122
+ mcp: {
123
+ expose: true,
124
+ description:
125
+ 'Draft a post about a topic in the background: the assistant titles it, and it appears in postList under the id answered',
126
+ },
127
+ async handle({ input, ctx }) {
128
+ // The id is the code's, chosen before the run: what makes a replayed run one post, not two.
129
+ const id = crypto.randomUUID();
130
+ const queued = await draftPostLater.enqueue({ id, orgId: orgOf(ctx.actor), ...input });
131
+ return { id, jobId: queued.id };
132
+ },
133
+ });
134
+ `;
135
+
136
+ const queueDraftTest =
137
+ (): string => `// queueDraft: one job enqueued under the caller's org, answered with the post's future id.
138
+ import { memoryJobDriver } from '@ultimat3/jobs';
139
+ import { testActor } from '@ultimat3/policy';
140
+ import { beforeAll, expect, swapAdapter, unitTest } from '@ultimat3/testing';
141
+ import { queueDraft } from './queue-draft';
142
+
143
+ const orgId = '${ORG}';
144
+ const target = queueDraft.named('queueDraft');
145
+ const input = { topic: 'How we review a pull request', price: { minor: 0, currency: 'USD' } };
146
+
147
+ beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
148
+
149
+ unitTest('a writer gets the id the post will have, and a job to wait on', async () => {
150
+ const writer = testActor('writer', { orgId, permissions: ['post:write'] }).actor;
151
+ const queued = await target.as(writer, input);
152
+ expect(queued.id).toMatch(/^[0-9a-f-]{36}$/);
153
+ expect(queued.jobId).not.toBe('');
154
+ });
155
+
156
+ unitTest('a reader may not ask for a post', async () => {
157
+ const reader = testActor('reader', { orgId, permissions: ['post:read'] }).actor;
158
+ await expect(target.as(reader, input)).rejects.toBeUltimateError('X_FORBIDDEN');
159
+ });
160
+ `;
161
+
162
+ export function jobFiles(scope: string): readonly GeneratedFile[] {
163
+ const own = (text: string): string => text.replaceAll('@APP/', `@${scope}/`);
164
+ return [
165
+ { path: `${ASSISTANT_DIR}/jobs/draft-post-later.ts`, contents: job() },
166
+ { path: `${ASSISTANT_DIR}/jobs/draft-post-later.job.test.ts`, contents: jobSuite() },
167
+ { path: `${ASSISTANT_DIR}/jobs/draft-post-later.test.ts`, contents: own(jobRunTest()) },
168
+ { path: `${ASSISTANT_DIR}/actions/queue-draft.ts`, contents: queueDraft() },
169
+ { path: `${ASSISTANT_DIR}/actions/queue-draft.test.ts`, contents: queueDraftTest() },
170
+ ];
171
+ }
@@ -0,0 +1,271 @@
1
+ // The `agent` shape's model half: the environment keys that name the model, the module that turns
2
+ // them into a gateway (or into none), and the scripted model every test and the eval run on. No
3
+ // model id, price or endpoint is spelled here or in what this writes — the environment holds them.
4
+
5
+ import { ENV_EXAMPLE_PATH, type EnvSchema } from '@ultimat3/core';
6
+ import type { GeneratedFile } from '../naming';
7
+ import { envExampleSource, envSchemaSource, SCAFFOLD_ENV_SCHEMA } from '../scaffold-env';
8
+ import type { ShapeEdit } from './overlay';
9
+
10
+ export const ASSISTANT_DIR = 'apps/web/app/assistant';
11
+
12
+ /**
13
+ * Every key optional at boot: an app with none of them set boots, tests and gates. `model.ts`
14
+ * requires the first eight once `LLM_MODEL` is set, so a half-named model fails the boot naming
15
+ * each missing key (`X_ENV_MISSING`) rather than at the first call. Descriptions stay under ~80
16
+ * characters, for the reason `SCAFFOLD_ENV_SCHEMA`'s do.
17
+ */
18
+ export const MODEL_ENV_SCHEMA = {
19
+ LLM_MODEL: {
20
+ type: 'string',
21
+ required: false,
22
+ description: 'The model id every agent runs on. Unset: no model, every call refused.',
23
+ },
24
+ LLM_BASE_URL: {
25
+ type: 'url',
26
+ required: false,
27
+ description: 'A chat-completions endpoint serving LLM_MODEL, e.g. http://localhost:11434/v1',
28
+ },
29
+ LLM_API_KEY: {
30
+ type: 'string',
31
+ required: false,
32
+ secret: true,
33
+ description: 'The bearer key LLM_BASE_URL takes.',
34
+ },
35
+ LLM_FALLBACK_URL: {
36
+ type: 'url',
37
+ required: false,
38
+ description: 'A second endpoint serving LLM_MODEL, asked when the first is down.',
39
+ },
40
+ LLM_FALLBACK_API_KEY: {
41
+ type: 'string',
42
+ required: false,
43
+ secret: true,
44
+ description: 'The bearer key LLM_FALLBACK_URL takes. Unset: LLM_API_KEY.',
45
+ },
46
+ LLM_CONTEXT_WINDOW: {
47
+ type: 'integer',
48
+ required: false,
49
+ min: 1,
50
+ description: 'Tokens LLM_MODEL reads per request, from its vendor page.',
51
+ },
52
+ LLM_MAX_OUTPUT: {
53
+ type: 'integer',
54
+ required: false,
55
+ min: 1,
56
+ description: 'Tokens LLM_MODEL writes per answer, from its vendor page.',
57
+ },
58
+ LLM_INPUT_PER_MILLION: {
59
+ type: 'integer',
60
+ required: false,
61
+ min: 0,
62
+ description: 'Price of a million input tokens, in integer minor units of LLM_CURRENCY.',
63
+ },
64
+ LLM_OUTPUT_PER_MILLION: {
65
+ type: 'integer',
66
+ required: false,
67
+ min: 0,
68
+ description: 'Price of a million output tokens, in integer minor units of LLM_CURRENCY.',
69
+ },
70
+ LLM_CURRENCY: {
71
+ type: 'string',
72
+ required: false,
73
+ description: 'The ISO 4217 code both prices are in, e.g. EUR.',
74
+ },
75
+ } satisfies EnvSchema;
76
+
77
+ const APP_ENV: EnvSchema = { ...SCAFFOLD_ENV_SCHEMA, ...MODEL_ENV_SCHEMA };
78
+
79
+ const model = (): string => `/**
80
+ * The model every agent in this app runs on, named by the environment and nowhere else: no model
81
+ * id, no price and no endpoint is spelled in code. \`LLM_MODEL\` unset installs no gateway, and the
82
+ * first model call is refused with X_AI_GATEWAY_MISSING and its fix — so the app boots, tests and
83
+ * gates with no key at all. The tests run on \`scripted-model.ts\`.
84
+ *
85
+ * Set, it is ONE row in the model registry, priced from the environment, served by any endpoint
86
+ * speaking the chat-completions format (\`LLM_BASE_URL\`) and, when \`LLM_FALLBACK_URL\` is set, by
87
+ * a second one the gateway falls over to when the first is down — a fallback between providers
88
+ * serving one model, never a silent swap to another model.
89
+ */
90
+
91
+ import type { AiFetch, Gateway } from '@ultimat3/ai';
92
+ import { openAiProvider, providerGateway, registerModel } from '@ultimat3/ai';
93
+ import { defineEnv, type EnvSchema, type EnvVarDecl } from '@ultimat3/core';
94
+ import { envSchema } from '../../../../app.config';
95
+
96
+ type Source = Readonly<Record<string, string | undefined>>;
97
+
98
+ /** \`app.config.ts\`'s declaration, made required: one list of keys, read twice. */
99
+ const need = <D extends EnvVarDecl>(decl: D): Omit<D, 'required'> => {
100
+ const { required: _optional, ...required } = decl;
101
+ return required;
102
+ };
103
+
104
+ const modelEnv = {
105
+ LLM_MODEL: need(envSchema.LLM_MODEL),
106
+ LLM_BASE_URL: need(envSchema.LLM_BASE_URL),
107
+ LLM_API_KEY: need(envSchema.LLM_API_KEY),
108
+ LLM_FALLBACK_URL: envSchema.LLM_FALLBACK_URL,
109
+ LLM_FALLBACK_API_KEY: envSchema.LLM_FALLBACK_API_KEY,
110
+ LLM_CONTEXT_WINDOW: need(envSchema.LLM_CONTEXT_WINDOW),
111
+ LLM_MAX_OUTPUT: need(envSchema.LLM_MAX_OUTPUT),
112
+ LLM_INPUT_PER_MILLION: need(envSchema.LLM_INPUT_PER_MILLION),
113
+ LLM_OUTPUT_PER_MILLION: need(envSchema.LLM_OUTPUT_PER_MILLION),
114
+ LLM_CURRENCY: need(envSchema.LLM_CURRENCY),
115
+ } satisfies EnvSchema;
116
+
117
+ /** \`fetch\` is the seam a test hands in, so the wiring is proved with no network. */
118
+ export interface ModelSeams {
119
+ readonly fetch?: AiFetch;
120
+ }
121
+
122
+ /**
123
+ * The endpoints serving the model, primary first: the order the gateway asks them in. A missing
124
+ * or malformed key throws X_ENV_MISSING naming every one, before anything is registered.
125
+ */
126
+ export function modelProviders(source: Source, seams: ModelSeams = {}) {
127
+ const env = defineEnv(modelEnv, { env: source });
128
+ const currency = env.LLM_CURRENCY;
129
+ const row = registerModel({
130
+ id: env.LLM_MODEL,
131
+ contextWindow: env.LLM_CONTEXT_WINDOW,
132
+ maxOutput: env.LLM_MAX_OUTPUT,
133
+ inputPerMillion: { minor: env.LLM_INPUT_PER_MILLION, currency },
134
+ outputPerMillion: { minor: env.LLM_OUTPUT_PER_MILLION, currency },
135
+ // No mark is relied on: a chat-completions host caches on its own, or not at all.
136
+ cacheMinimumTokens: 0,
137
+ // No effort or thinking control is sent: a model that takes one is a row you write by hand.
138
+ reasoning: { effort: false, adaptive: false, disableThinkingUpTo: undefined },
139
+ });
140
+ const endpoint = (name: string, baseUrl: string, apiKey: string) =>
141
+ openAiProvider({ name, baseUrl, apiKey, models: [row.id], ...seams });
142
+ const primary = endpoint('primary', env.LLM_BASE_URL, env.LLM_API_KEY);
143
+ if (env.LLM_FALLBACK_URL === undefined) return { model: row.id, providers: [primary] };
144
+ const fallbackKey = env.LLM_FALLBACK_API_KEY ?? env.LLM_API_KEY;
145
+ const fallback = endpoint('fallback', env.LLM_FALLBACK_URL, fallbackKey);
146
+ return { model: row.id, providers: [primary, fallback] };
147
+ }
148
+
149
+ /** The gateway the environment names, or \`undefined\` when \`LLM_MODEL\` names nothing. */
150
+ export function modelGateway(source: Source, seams: ModelSeams = {}): Gateway | undefined {
151
+ if ((source.LLM_MODEL ?? '') === '') return undefined;
152
+ const { model, providers } = modelProviders(source, seams);
153
+ return providerGateway({ providers, defaultModel: model });
154
+ }
155
+
156
+ /** What \`apps/web/runtime.ts\` spreads: the gateway when there is one, nothing when there is none. */
157
+ export function modelRuntime(source: Source): { readonly aiGateway?: Gateway } {
158
+ const gateway = modelGateway(source);
159
+ return gateway === undefined ? {} : { aiGateway: gateway };
160
+ }
161
+ `;
162
+
163
+ const modelTest =
164
+ (): string => `// The model the environment names: none, half of one, one, and one with a fallback endpoint.
165
+ // Every request goes to a \`fetch\` double — no network, no key.
166
+ import type { AiFetch } from '@ultimat3/ai';
167
+ import { modelSpec } from '@ultimat3/ai';
168
+ import { expect, unitTest } from '@ultimat3/testing';
169
+ import { modelGateway, modelProviders, modelRuntime } from './model';
170
+
171
+ const named = {
172
+ LLM_MODEL: 'house-model',
173
+ LLM_BASE_URL: 'http://primary.test/v1',
174
+ LLM_API_KEY: 'primary-key',
175
+ LLM_CONTEXT_WINDOW: '32000',
176
+ LLM_MAX_OUTPUT: '4096',
177
+ LLM_INPUT_PER_MILLION: '150',
178
+ LLM_OUTPUT_PER_MILLION: '600',
179
+ LLM_CURRENCY: 'EUR',
180
+ };
181
+
182
+ /** Each URL and bearer the providers sent, answered with a refusal so nothing is parsed. */
183
+ const recorder = () => {
184
+ const sent: { url: string; auth: string | null }[] = [];
185
+ const fetch: AiFetch = async (url, init) => {
186
+ sent.push({ url, auth: new Headers(init.headers).get('authorization') });
187
+ return new Response('{}', { status: 400 });
188
+ };
189
+ return { sent, fetch };
190
+ };
191
+
192
+ const ask = { model: 'house-model', messages: [{ role: 'user' as const, content: 'hi' }] };
193
+
194
+ unitTest('no LLM_MODEL is no gateway: the app boots, and the first call says what to set', () => {
195
+ expect(modelGateway({})).toBeUndefined();
196
+ expect(modelRuntime({ LLM_MODEL: '' })).toEqual({});
197
+ });
198
+
199
+ unitTest('a model named without its numbers is refused, naming every missing key', () => {
200
+ let refused: unknown;
201
+ try {
202
+ modelGateway({ LLM_MODEL: 'house-model' });
203
+ } catch (error) {
204
+ refused = error;
205
+ }
206
+ expect(refused).toBeUltimateError('X_ENV_MISSING');
207
+ expect(String((refused as { cause?: unknown }).cause)).toContain('LLM_CURRENCY');
208
+ });
209
+
210
+ unitTest('a named model is registered at the prices the environment states', () => {
211
+ expect(modelRuntime(named).aiGateway?.defaultModel).toBe('house-model');
212
+ const spec = modelSpec('house-model');
213
+ expect(spec.inputPerMillion).toEqual({ minor: 150, currency: 'EUR' });
214
+ expect(spec.outputPerMillion).toEqual({ minor: 600, currency: 'EUR' });
215
+ expect([spec.contextWindow, spec.maxOutput]).toEqual([32000, 4096]);
216
+ });
217
+
218
+ unitTest('one endpoint without a fallback, called with its own key', async () => {
219
+ const { sent, fetch } = recorder();
220
+ const { providers } = modelProviders(named, { fetch });
221
+ expect(providers.map((provider) => provider.name)).toEqual(['primary']);
222
+ await providers[0]?.generate({ ...ask, maxTokens: 16 }).catch(() => undefined);
223
+ expect(sent).toEqual([
224
+ { url: 'http://primary.test/v1/chat/completions', auth: 'Bearer primary-key' },
225
+ ]);
226
+ });
227
+
228
+ unitTest('a fallback endpoint is asked second, with its own key or the primary one', async () => {
229
+ const { sent, fetch } = recorder();
230
+ const fallback = { ...named, LLM_FALLBACK_URL: 'http://fallback.test/v1' };
231
+ const shared = modelProviders(fallback, { fetch }).providers;
232
+ expect(shared.map((provider) => provider.name)).toEqual(['primary', 'fallback']);
233
+ await shared[1]?.generate({ ...ask, maxTokens: 16 }).catch(() => undefined);
234
+ const own = modelProviders({ ...fallback, LLM_FALLBACK_API_KEY: 'fallback-key' }, { fetch });
235
+ await own.providers[1]?.generate({ ...ask, maxTokens: 16 }).catch(() => undefined);
236
+ expect(sent).toEqual([
237
+ { url: 'http://fallback.test/v1/chat/completions', auth: 'Bearer primary-key' },
238
+ { url: 'http://fallback.test/v1/chat/completions', auth: 'Bearer fallback-key' },
239
+ ]);
240
+ });
241
+ `;
242
+
243
+ /** The commented-out port the base runtime writes, replaced by the one this shape installs. */
244
+ const RUNTIME_PORT =
245
+ " // aiGateway: myGateway, // Gateway from '@ultimat3/ai/adapter'; default: none: the first model call is refused (X_AI_GATEWAY_MISSING)\n";
246
+ const RUNTIME_IMPORT = "import type { RuntimeOverrides } from '@ultimat3/cli/serve';\n";
247
+
248
+ /** `app.config.ts` declares the model keys; `runtime.ts` installs the gateway they name. */
249
+ export const modelEdits = (): readonly ShapeEdit[] => [
250
+ { path: 'app.config.ts', find: envSchemaSource(), replace: envSchemaSource(APP_ENV) },
251
+ {
252
+ path: 'apps/web/runtime.ts',
253
+ find: RUNTIME_IMPORT,
254
+ replace: `${RUNTIME_IMPORT}import { modelRuntime } from './app/assistant/model';\n`,
255
+ },
256
+ {
257
+ path: 'apps/web/runtime.ts',
258
+ find: RUNTIME_PORT,
259
+ replace:
260
+ ' // The model LLM_MODEL names, or none (app/assistant/model.ts).\n ...modelRuntime(Bun.env),\n',
261
+ },
262
+ ];
263
+
264
+ export function modelFiles(): readonly GeneratedFile[] {
265
+ return [
266
+ { path: `${ASSISTANT_DIR}/model.ts`, contents: model() },
267
+ { path: `${ASSISTANT_DIR}/model.test.ts`, contents: modelTest() },
268
+ // The same renderer `x env example` runs, over the declaration `app.config.ts` now holds.
269
+ { path: ENV_EXAMPLE_PATH, contents: envExampleSource(APP_ENV) },
270
+ ];
271
+ }