-
Notifications
You must be signed in to change notification settings - Fork 0
feat(routes): generate typed provider declarations and augment the runtime (#95) #382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| --- | ||
| "@agent-bundle/runtime": minor | ||
| "agent-bundle": minor | ||
| --- | ||
|
|
||
| Type project-defined context providers without a compiler change per | ||
| provider. `AgentProviderValues` is now an augmentable interface (string index | ||
| of `unknown` plus the optional framework-owned `processLifetime`, exported as | ||
| `AgentProcessLifetime`), and the generated `.agent-bundle/routes.d.ts` | ||
| declares `AgentBundleProviders` / `ProviderKey` / `ProviderValue<Key>` from | ||
| each conventional `src/providers/*` factory's awaited return type and augments | ||
| `@agent-bundle/runtime` so `(await agent()).providers.<key>` observes that | ||
| type. Provider-free graphs emit no augmentation; a graph with providers but no | ||
| executable routes keeps the declaration file. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'; | ||
| import { tmpdir } from 'node:os'; | ||
| import { dirname, join } from 'node:path'; | ||
|
|
||
| import { afterEach, expect, it } from '@rstest/core'; | ||
| import ts from 'typescript-5'; | ||
|
|
||
| import { inspect } from '../src/api.ts'; | ||
|
|
||
| const roots: string[] = []; | ||
|
|
||
| afterEach(async () => { | ||
| await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true }))); | ||
| }); | ||
|
|
||
| const writeProjectFile = async (root: string, path: string, contents: string): Promise<void> => { | ||
| const output = join(root, path); | ||
| await mkdir(dirname(output), { recursive: true }); | ||
| await writeFile(output, contents); | ||
| }; | ||
|
|
||
| const typecheck = (root: string, entry: string): readonly string[] => { | ||
| const program = ts.createProgram([join(root, entry), join(root, '.agent-bundle', 'routes.d.ts')], { | ||
| exactOptionalPropertyTypes: true, | ||
| module: ts.ModuleKind.NodeNext, | ||
| moduleResolution: ts.ModuleResolutionKind.NodeNext, | ||
| noEmit: true, | ||
| skipLibCheck: true, | ||
| strict: true, | ||
| target: ts.ScriptTarget.ES2022, | ||
| }); | ||
| return ts.getPreEmitDiagnostics(program) | ||
| .map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); | ||
| }; | ||
|
|
||
| /** | ||
| * #95 acceptance: a project-defined provider adds a typed context property | ||
| * without a compiler change. The compiler publishes `.agent-bundle/routes.d.ts` | ||
| * with `AgentBundleProviders` and a `@agent-bundle/runtime` augmentation, so | ||
| * `(await agent()).providers.<key>` observes the provider factory's resolved | ||
| * return type against the real published runtime declarations. | ||
| */ | ||
| it('types (await agent()).providers.<key> from the generated provider declarations', { timeout: 60_000 }, async () => { | ||
| const root = await mkdtemp(join(tmpdir(), 'agent-bundle-provider-typegen-')); | ||
| roots.push(root); | ||
| // The audiobook example's installed tree supplies the built @agent-bundle/runtime and zod. | ||
| await symlink(join(process.cwd(), 'examples', 'audiobook-curator', 'node_modules'), join(root, 'node_modules'), 'dir'); | ||
| await Promise.all([ | ||
| writeProjectFile(root, 'package.json', JSON.stringify({ | ||
| dependencies: { '@agent-bundle/runtime': 'workspace:*', zod: '4.4.3' }, | ||
| name: 'provider-typegen-fixture', | ||
| type: 'module', | ||
| version: '1.0.0', | ||
| })), | ||
| writeProjectFile(root, 'agent-bundle.config.ts', [ | ||
| "import { defineConfig } from 'agent-bundle/config';", | ||
| 'export default defineConfig({', | ||
| " plugin: { name: 'provider-typegen-fixture', version: '1.0.0' },", | ||
| " targets: ['portable'],", | ||
| '});', | ||
| '', | ||
| ].join('\n')), | ||
| writeProjectFile(root, 'src/providers/library.ts', [ | ||
| "import type { AgentProviderContext } from 'agent-bundle';", | ||
| 'export interface LibraryContext { readonly stages: readonly string[]; readonly surface: string; }', | ||
| 'export default async function library({ invocation }: AgentProviderContext): Promise<LibraryContext> {', | ||
| " return { stages: ['discover'], surface: invocation.kind };", | ||
| '}', | ||
| '', | ||
| ].join('\n')), | ||
| writeProjectFile(root, 'src/providers/build-number.ts', [ | ||
| 'export default function buildNumber(): number {', | ||
| ' return 7;', | ||
| '}', | ||
| '', | ||
| ].join('\n')), | ||
| writeProjectFile(root, 'src/mcp/curator/tools/status.ts', [ | ||
| "import { z } from 'zod';", | ||
| 'export const inputSchema = z.object({}).strict();', | ||
| "export const resultSchema = z.object({ status: z.literal('ready') }).strict();", | ||
| "export default async function Status() { return { status: 'ready' as const }; }", | ||
| '', | ||
| ].join('\n')), | ||
| writeProjectFile(root, 'assertions.ts', [ | ||
| "import { agent } from '@agent-bundle/runtime';", | ||
| "import type { ProviderKey, ProviderValue } from './.agent-bundle/routes.js';", | ||
| "import type { LibraryContext } from './src/providers/library.js';", | ||
| '', | ||
| 'type Equal<Left, Right> =', | ||
| ' (<Value>() => Value extends Left ? 1 : 2) extends', | ||
| ' (<Value>() => Value extends Right ? 1 : 2) ? true : false;', | ||
| 'type Assert<Value extends true> = Value;', | ||
| '', | ||
| "export type Keys = Assert<Equal<ProviderKey, 'buildNumber' | 'library'>>;", | ||
| "export type Library = Assert<Equal<ProviderValue<'library'>, LibraryContext>>;", | ||
| "export type Sync = Assert<Equal<ProviderValue<'buildNumber'>, number>>;", | ||
| '', | ||
| 'export const stages = async (): Promise<readonly string[]> => {', | ||
| ' const context = await agent();', | ||
| ' // Augmented: no cast, no runtime guard needed for declared providers.', | ||
| ' const library: LibraryContext = context.providers.library;', | ||
| ' const build: number = context.providers.buildNumber;', | ||
| ' const lifetime: number | undefined = context.providers.processLifetime?.hits;', | ||
| ' // Undeclared keys stay unknown.', | ||
| ' const unknownValue: unknown = context.providers.somethingElse;', | ||
| ' void build; void lifetime; void unknownValue;', | ||
| ' return library.stages;', | ||
| '};', | ||
| '', | ||
| ].join('\n')), | ||
| writeProjectFile(root, 'mismatch.ts', [ | ||
| "import { agent } from '@agent-bundle/runtime';", | ||
| 'export const wrong = async (): Promise<number> => (await agent()).providers.library;', | ||
| '', | ||
| ].join('\n')), | ||
| ]); | ||
|
|
||
| const result = await inspect({ root }); | ||
| expect(result.state).toBe('ready'); | ||
| const declarations = await readFile(join(root, '.agent-bundle', 'routes.d.ts'), 'utf8'); | ||
| expect(declarations).toContain('readonly "buildNumber": ProviderValueOf<typeof provider0.default>;'); | ||
| expect(declarations).toContain('readonly "library": ProviderValueOf<typeof provider1.default>;'); | ||
| expect(declarations).toContain("declare module '@agent-bundle/runtime'"); | ||
|
|
||
| expect(typecheck(root, 'assertions.ts')).toEqual([]); | ||
| const mismatch = typecheck(root, 'mismatch.ts'); | ||
| expect(mismatch).toHaveLength(1); | ||
| expect(mismatch[0]).toContain("Type 'LibraryContext' is not assignable to type 'number'"); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the generated declaration is included, this required member merges globally into
AgentProviderValues, butAgentRequestInit.providersremains optional andrunAgentRequestconverts an omission to{}(packages/rsc-runtime/src/agent-request.ts:184,415). Consequently, a custom invocation orrenderRoutetest can omit provider fixtures while(await agent()).providers.libraryis still typed as present, leading to an uncheckedundefineddereference at runtime. Make generated keys optional for such contexts, or distinguish generated scopes from contexts that do not install providers.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed — addressed in follow-up #409 (2d1cd86). Rather than weakening handler types, the contexts that do not run providers now carry the obligation: once the generated augmentation adds required keys to
AgentProviderValues,AgentRequestInit.providers(AgentRequestProvidersInit), the harnessoptionsargument (HarnessOptionsArguments) andcontext(RenderRouteContextInit) become required in that program.provider-typegen.test.tsproves omittingproviders, a declared key, or the options argument is a compile error while a complete custom scope typechecks; provider-free projects and generated scopes are unchanged.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed on main by #409 (62138ef, the #95/#100 follow-up lane): harness and test contexts that do not run providers now require the provider fixtures the augmentation declares, and
docs/framework-mode.md/docs/entry-conventions.mddocument the contract; #408 had only clarified the docs and dropped that change in favour of #409 during rebase.