npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nestjs-adk/core

v2.0.1

Published

NestJS-native agent framework: decorators, DI and abstract contracts over pluggable AI agent engines (Google ADK first).

Readme

@nestjs-adk/core

Build AI agents the NestJS way.

NestJS developers already know how to build good software: classes, modules, providers and dependency injection. nestjs-adk brings AI agents into that same world. An agent is a class with a decorator. A tool is a provider. Everything is injected, validated and tested like the rest of your app.

This package is the framework: the decorators, the module, the run loop and every contract. To talk to a real model you also install a provider package:

npm i @nestjs-adk/core @nestjs-adk/google

Your first agent

Register the module once, in your root module. This is where the default model lives:

import { AdkModule, Secret } from "@nestjs-adk/core";
import { GeminiModel } from "@nestjs-adk/google";

const flash = new GeminiModel("gemini-3.5-flash-lite", { apiKey: new Secret(process.env.GEMINI_API_KEY) });

@Module({
	imports: [AdkModule.forRoot({ defaultModel: flash })],
	providers: [SupportAgent, LookupOrderTool, OrdersService, ChatService],
})
export class AppModule {}

Now the agent. It is a class described by @Agent, and extending AdkAgent is what lets you inject it and ask it something:

import { AdkAgent, Agent } from "@nestjs-adk/core";

@Agent({
	name: "support",
	description: "Customer support: order status and returns.",
	prompt: "You are the store's support agent. Answer in at most two sentences.",
	tools: [LookupOrderTool],
})
export class SupportAgent extends AdkAgent {}

The agent went into providers like any other class. There is no separate registration step, and a mistake in the wiring fails at boot naming the provider rather than surfacing on a request: a tool nobody registered, a transfer target that is not an agent, a provider the container cannot hand a single instance of.

To use it, inject it. The instance is the handle:

@Injectable()
export class ChatService {
	public constructor(private readonly support: SupportAgent) {}

	public async answer(sessionId: string, message: string): Promise<string> {
		const result = await this.support.ask(message, { sessionId });
		return result.text;
	}
}

ask returns an AgentResult: the text, the session and run ids, the status, anything waiting for a human, and what the run cost. stream runs the same thing and yields the pieces as they arrive. approve and reject answer a run that stopped in front of a person, and delegate hands one task to a specialist.

An agent that already extends something else is reached by name instead:

const support = this.registry.open("support"); // AgentRegistry, injected

That is the whole mental model: configure the module once, register classes as providers, inject the agent and call it.

Options that come from the container

forRoot takes a plain object, which works while every option is a value: a model built from an environment variable, a directory name, a policy with no dependencies.

Most of what an application eventually plugs in is not. A storage holding a database client, an embedder that needs credentials, a pricing source with an HTTP client, an approval policy that reads the current tenant: those are providers, and nothing written where the module is declared can name them. forRootAsync builds the same options inside the container:

@Module({
	imports: [
		AdkModule.forRootAsync({ imports: [InfraModule], useClass: AdkOptions }),
		SupportModule,
	],
})
export class AppModule {}
@Injectable()
export class AdkOptions implements AdkOptionsFactory {
	public constructor(
		private readonly storage: PrismaSessionStorage,
		private readonly pricing: LiteLlmPricingSource,
	) {}

	public createAdkOptions(): AdkModuleOptionsInput {
		return {
			defaultModel: flash,
			storage: this.storage,
			runtime: { cost: { pricing: this.pricing } },
		};
	}
}

useExisting points at an instance another module already provides, and useFactory takes the dependencies positionally:

AdkModule.forRootAsync({
	imports: [InfraModule],
	inject: [PrismaSessionStorage],
	useFactory: (storage: PrismaSessionStorage) => ({ defaultModel: flash, storage }),
});

Prefer useClass. TypeScript cannot line an inject array up with the parameters that receive it, so two entries swapped compile and fail at boot; a constructor is checked like any other provider's. That is also why a factory's parameters have to be annotated: they are typed never rather than any, so an unannotated one carries no type into the body.

Whatever the options depend on has to be reachable through imports, and it may not be one of the tokens this module provides. Asking for SessionStorage in order to build the options that decide what SessionStorage is, is a cycle, and NestJS refuses it.

Declaring none of the three is refused, and so is declaring two: the second would be configuration nothing reads. Both fail where forRootAsync is called, before the boot they would otherwise poison.

Tools

A tool is something the model can decide to call. A shared tool is a class that extends AdkTool. The Zod schema does two jobs at once: it tells the model what arguments exist, and it types the input for you.

import { AdkTool, Tool, type ToolContext } from "@nestjs-adk/core";
import { z } from "zod";

const schema = z.object({ city: z.string().describe("City name") });

@Tool({ name: "get_weather", description: "Current weather.", schema })
export class GetWeatherTool extends AdkTool<typeof schema> {
	public constructor(private readonly weather: WeatherService) {
		super();
	}

	public execute(input: z.infer<typeof schema>, context: ToolContext): unknown {
		return this.weather.fetch(input.city);
	}
}

The tool is a normal provider, so it injects services, repositories and anything else. Whatever execute returns goes back to the model, as long as it is serializable.

The two arguments come from different places. input comes from the model, which chose the values from the schema, and it is parsed before execute runs: .default() applies, coercions happen, and keys the model invented are dropped. context comes from the runtime and carries sessionId, runId, agent, callId, signal, actor and the session's metadata.

Nothing sensitive should be in the schema, because the model would be the one filling it in. A tenant id belongs to a repository the tool injects, keyed by something the runtime knows, and never to an argument the model can write. That is also why the parse drops undeclared keys: telling you to keep a tenant id out of the schema would mean little if a { ...input } spread could carry a smuggled one into your query.

When a tool belongs to a single agent, skip the class and declare a method:

@Agent({ name: "support", description: "Customer support.", prompt: "..." })
export class SupportAgent extends AdkAgent {
	public constructor(private readonly orders: OrdersService) {
		super();
	}

	@Tool({ description: "Looks up an order by id.", schema: orderSchema })
	public lookupOrder(input: z.infer<typeof orderSchema>): unknown {
		return this.orders.find(input.orderId);
	}
}

The name defaults to the method name. Everything else works the same.

An agent lists a shared tool by its class, or by the name the tool declared:

@Agent({ name: "support", description: "Customer support.", tools: ["get_weather"] })

Both resolve to the same definition, and a name nobody declared fails the boot the way an unregistered class does. The name is for the module that cannot import the class: a tool that lives in the module that also imports the agent's module would close a cycle the decorator evaluates on load, and a string closes nothing.

Who is calling

A tool that reads a person's data has to know which person. The run does not know either, so the caller says:

await this.assistant.ask(message, { sessionId, actor: Actor.fromId(user.id, { workspaceId, role: user.role }) });

Actor is an id and a bag of claims the runtime never reads. It reaches every tool of the run as context.actor, handovers and delegations included, and it is what an access policy judges:

export class MembersOnly extends AdkAccessPolicy {
	public decide(tool: ToolDefinition, invocation: ToolInvocation, actor: Actor | undefined): ToolAccess {
		if (actor?.claims.member === true) return ToolAccess.granted();
		return ToolAccess.denied(`${tool.name} is for members`);
	}
}

AdkModule.forRoot(AdkModuleOptions.from({ defaultModel, runtime: RuntimeOptions.from({ tools: { access: new MembersOnly() } }) }));

The policy is asked before every invocation, after the arguments were parsed and before any approval is requested: nobody is asked to approve a call the actor could not make. A refusal reaches the model as the tool's answer, with the policy's reason, and the conversation goes on. Without a policy everything is granted, which is what an application that wrote none meant.

The same gate serves an MCP server exposing the same tools, which is the point of putting the rule in one object: @McpController declares what is published, exactly as @Agent declares what a model is offered, and a client calling a tool goes through the same parse and the same policy as the agent loop. See @nestjs-adk/mcp for the server.

@McpController({ tools: [ListMeetingsTool] })
export class MeetingsMcpController {
	@Tool({ name: "count_meetings", description: "Only clients count.", schema: z.object({}), effect: "read" })
	public count(_input: Record<string, never>, context: ToolContext): unknown { ... }
}

A class listed by an agent and by a controller is one tool published twice. A method on the controller is a client-only tool, and a method on the agent never reaches a client. A name two controllers publish fails the boot naming both.

Results the model has to look at

Some tools answer with something to be seen rather than read: an image, a PDF, a scanned invoice. Returning it as a normal result does not work, because a tool result is JSON and base64 inside it arrives as characters the model counts but cannot see.

Answer a ToolOutput instead, and the parts travel through the provider's own media channel:

import { AdkTool, MediaPart, Tool, ToolOutput } from "@nestjs-adk/core";

@Tool({ name: "read_invoice", description: "Loads an invoice.", schema })
export class ReadInvoiceTool extends AdkTool<typeof schema> {
	public async execute(input: z.infer<typeof schema>): Promise<ToolOutput> {
		const file = await this.files.get(input.name);
		return new ToolOutput({ name: file.name }, [MediaPart.image(file.mimeType, file.base64)]);
	}
}

The constructor takes the data first and the media second, and the media list is optional: new ToolOutput(data) is the plain form. The data still reaches the model as the tool's result; the media arrives alongside it.

The attachment reaches the model in the same turn, with the question already in context, and that ordering is the point. A description written when the file was uploaded answers "what colour is the shirt?" only if somebody guessed the question in advance, and "how many buttons?" is already lost. Letting the model look when it is asked costs one call instead of two, and those tokens land in result.cost like every other.

A model that never declared media input fails the call saying so rather than answering about nothing. The payload never enters the session history either: it is injected into the request being built and discarded with it, so a conversation with twenty attachments does not carry all twenty into every later turn. The model calls the tool again if it needs another look.

Attachments the application owns

A question can carry an image the same way a tool answer can. media takes the bytes, or a public address the provider fetches itself, and the journal keeps a name rather than a payload:

await agent.ask("what is in this photo?", {
	media: [MediaPart.image("image/png", file.base64)],
});

That shape assumes the runtime either holds the bytes or freezes an address, and a file living in your own bucket fits neither. A pre-signed URL expires, and because history is rebuilt on every turn it then expires for every turn that follows; one without expiry is a capability URL recorded forever, in the journal and in whatever the provider cached. There is no correct TTL for an address inside an append-only journal.

So a file the application owns is attached by name instead:

await agent.ask("what does the receipt say?", {
	attachments: [AttachmentReference.external(upload.id, "image/png")],
});

A file the model reads rather than looks at, a .md, a .csv, a JSON document, a log, goes in as an artifact and is read through the artifact tools instead of being pasted into the prompt:

await agent.ask("summarize the report", {
	files: [ArtifactContent.fromText(markdown, "text/markdown", ArtifactName.fromText("q3.md"))],
});

// or attach first and ask later
const reference = await agent.attachArtifact(sessionId, ArtifactContent.fromText(csv, "text/csv", name));
await agent.ask("what is the total in column b?", { sessionId, attachments: [reference] });

The model is shown [artifact a-1 "q3.md", text/markdown, 40000 characters, read with read_artifact(artifactId, offset, limit), and its shape is one the artifact exploration tools understand] and reads it with read_artifact, which every agent that has tools at all is given. The tools that outline, search, query and slice it are opt in, listed on the agent that needs them: see Artifacts. A text artifact does not need a model that sees, so an agent on a text-only model takes one; an image still does. attachArtifact refuses a conversation nobody opened, with SessionNotFoundError, so a mistyped id does not quietly store a file where nothing will find it. The name is an ArtifactName: it comes from your end user and ends up in a line the model reads, so an empty name, one over 160 characters, a control character and a square bracket are all refused with InvalidArtifactNameError. The library never sniffs a file's type from its bytes; that is your upload boundary's job, and what you declare is what the model is told.

The journal records the id and nothing else. Every time a prompt is built, including the first one, the runtime hands the reference to the AttachmentResolver declared in RuntimeOptions and asks what it becomes now. The answer is an AttachmentProjection: media(part) puts it in front of the model, note(text) puts a line of text where it stood (so "describe this image" still reads coherently when the image is not sent), omit() leaves it out, and artifact() writes the placeholder above so the artifact tools take it from there. Nothing the resolver answers is cached or recorded, which is what makes a fresh address per turn possible and lets "not any more" be a policy rather than a missing feature.

Two resolvers ship, one per environment:

// development, or private files: bytes fetched server side and inlined. No address ever travels,
// so a localhost MinIO works exactly like production S3.
attachments: new InlineAttachmentResolver(async (id) => uploads.find(id));

// production on S3: a fresh signed address per projection, TTL of minutes, never persisted.
attachments: new SignedUrlAttachmentResolver(async (id) => storage.presign(id));

SignedUrlAttachmentResolver also checks what the serving model can do. Fetching a media URL is a declared capability (MEDIA_URL), both shipped providers declare it (OpenAI through image_url, Gemini through fileUri, which takes public HTTPS and signed addresses), and a model that never declared it is given a note rather than an address it would read as text.

Declaring no resolver projects a stored image as media, a stored text artifact as its placeholder, a link as its address, and an external reference as a note saying no resolver is configured, so the wiring gap is visible in the conversation instead of silent. A resolver that throws becomes a note too; one missing file does not end a conversation that was already answered once.

One guard closes the classic development trap: MediaPart.link refuses localhost, private ranges and .local/.internal names with UnreachableMediaUrlError, because a media URL is fetched from the provider's network, where that address is a different machine or no machine at all, and the failure arrives as an opaque provider error you paid for. A self hosted model that can actually reach the address opts out with MediaLimits.allowingPrivateHosts().

Tools that arrive per run

The tools above are decided when you write the code. Some are not: if your users connect their own integrations, the set changes per person and only exists at runtime. That is what ToolSource is for.

A source declared in the module belongs to the application and opens on every run:

AdkModule.forRoot(
	AdkModuleOptions.from({
		defaultModel,
		runtime: RuntimeOptions.from({ tools: { sources: [new CompanyCatalogSource()] } }),
	}),
);

A source declared on the call belongs to that run alone, which is where a credential that is somebody's rather than the application's goes:

const result = await this.assistant.ask(message, {
	sessionId,
	sources: await this.integrationsOf(user.id),
});

Both are opened, the module's first, and both are closed when the run ends: whether it answered, threw, or was aborted mid stream. Their tools join the ones the agent declares and are indistinguishable from them downstream: they go through argument validation, offload, approvals and events like any other.

export abstract class ToolSource {
	public abstract readonly name: string;
	public abstract open(
		sessionId: SessionId,
		runId: AgentRunId,
		signal?: AbortSignal,
	): Promise<readonly ToolDefinition[]>;
	public abstract close(runId: AgentRunId): Promise<void>;
}

An approval is a new run, minutes or days later, and whatever the suspended run had open is long closed. So a held call that came from a source needs the source declared again on the decision:

await this.assistant.approve(sessionId, callId, {
	by: "gabriel",
	sources: await this.integrationsOf(user.id),
});

Two failures are expected and neither ends the run. Throw ToolSourceUnavailableError when the source is unreachable: its tools are absent and the conversation continues with what is left. Throw ToolSourceAuthError when the user has to authorize again: the run journals a reauth event naming the source, which is what an application turns into a reconnect button. The distinction matters because reconnecting fixes one and not the other.

Omitting sources is harmless: the agent runs with what it declares and nothing else. Forgetting it costs you tools, never someone else's.

@nestjs-adk/mcp implements this contract for MCP servers.

Skills

Skills are blocks of domain knowledge written as text. They exist so a prompt does not grow into one giant string. A skill is a method on the agent, decorated with @Skill:

@Agent({ name: "sales", description: "Sales department.", prompt: "..." })
export class SalesAgent extends AdkAgent {
	@Skill({ name: "tone", description: "How the salesperson talks.", mode: "always" })
	public tone(): string {
		return "Be direct and state the price with two decimal places.";
	}

	@Skill({ name: "club_policy", description: "Club and volume discount rules." })
	public clubPolicy(): string {
		return "A 10% discount applies from three copies of the same game.";
	}
}

mode: "always" puts the content in the instruction on every run, after the prompt, in the order the skills were declared. The default mode is on demand: the model sees only the names and descriptions, plus an activate_skill tool it calls when it decides it needs the content. That keeps the context small while the knowledge stays available. That name is the runtime's, on every agent, so a tool of your own called activate_skill fails the boot: see Artifacts.

A skill is read once, at boot, and never per run. It is fixed text by design: the thing that varies per run is the prompt.

Prompts

There are two ways to give an agent its instruction. Pick one per agent: declaring both fails at startup, because a precedence rule would leave one of them looking configured while the model never sees it.

The first is a fixed text on the decorator:

@Agent({ name: "support", description: "...", prompt: "You are the store's support agent." })
export class SupportAgent extends AdkAgent {}

The second is a prompt() method on the agent. Use it when the instruction depends on data. Your agent is an ordinary NestJS provider, so whatever knows that data is a constructor argument:

@Agent({ name: "support", description: "..." })
export class SupportAgent extends AdkAgent {
	public constructor(private readonly customers: FindCustomerUseCase) {
		super();
	}

	protected override async prompt(context: PromptContext): Promise<string> {
		const customer = this.customers.execute(context.metadata.find(CUSTOMER_ID) ?? "");
		return this.prompting.renderFromFileOrFail("support.md", {
			name: customer.name,
			plan: customer.plan,
		});
	}
}

The method receives a PromptContext: the session id, the run id, the agent about to answer, the session's metadata, the actor the question was asked with and the signal that stops the run.

Metadata is what your application knows about the conversation, and it is where the key you look your own data up by goes. You declare the key once so nothing reads a raw string, and you write it when the conversation starts:

export const CUSTOMER_ID = MetadataKey.fromName<string>("customerId", (v): v is string => typeof v === "string");

await support.ask("where is my order?", { metadata: { customerId: user.email } });

Every key is journaled on the same commit as the question, so it survives a restart, means the same in any process, and is lost with the turn when the run fails. Last write per key wins, so a later question that says nothing about a key keeps the value, and one that names it again replaces it. Values are JSON: a string, a number, a boolean, null, an array or a plain object, up to sixteen kibibytes serialized per key. The lib never interprets a key of yours.

Putting the customer's data in the system prompt rather than in the message is the point. Text in the message is text the model has been told to treat as somebody else's words, and a name pasted into it is a place where a user can try to give instructions. Text in the system prompt is instruction.

Three ways to get the text

this.prompting gives you:

this.prompting.render(template, vars); // text you already have
this.prompting.renderFromFile(path, vars); // undefined when there is no such prompt
this.prompting.renderFromFileOrFail(path, vars); // throws PromptNotFoundError instead

render needs no file and no source at all, so a prompt kept in your database is just a row you read and then render. Prefer renderFromFileOrFail for files: an agent answering without the instruction it was written around is worse than one that fails naming the missing file.

Variables

{{name}} is optional and renders as nothing when nothing filled it. {{{name}}} is required, and a prompt missing one throws MissingPromptVariablesError naming every missing key at once. null counts as missing for both, so a column nobody filled reads the same as an argument nobody passed.

Where the files live

By default a plain name is read from ./prompts. Point that somewhere else with prompts.dir, and build the path from the file that owns the prompts so it does not depend on where the process was started:

AdkModule.forRoot(
	AdkModuleOptions.from({
		defaultModel,
		prompts: { dir: join(dirname(fileURLToPath(import.meta.url)), "prompts") },
	}),
);

An absolute path is used as it is, and a path starting with ./ or ../ is resolved from the working directory. Each file is read once and served from memory afterwards.

Prompts that do not live on disk

To keep them anywhere else, implement PromptSource and pass it as promptSource. Your agents do not change: they pass a name, never a location, so the same renderFromFileOrFail("support.md") reads a bucket or a table depending only on what the module declared. The connection stays inside the source.

export class GcsPrompts extends PromptSource {
	// Nothing above this port caches, so the source does. It stores the read rather than the
	// result, so runs starting at once share one download.
	private readonly cache = new PromptFileCache();

	public constructor(
		private readonly storage: Storage,
		private readonly bucket: string,
	) {
		super();
	}

	public async load(name: string): Promise<string | undefined> {
		return await this.cache.through(name, async () => {
			const [body] = await this.storage.bucket(this.bucket).file(`prompts/${name}`).download();
			return body.toString("utf8");
		});
	}

	/** Ends up in the PromptNotFoundError message, so name the object and not just the file. */
	public override describe(name: string): string {
		return `gs://${this.bucket}/prompts/${name}`;
	}
}

AdkModule.forRoot(AdkModuleOptions.from({ defaultModel, promptSource: new GcsPrompts(storage, "prompts") }));

Three things are yours rather than the library's, and a remote source needs all three:

  • Caching. A prompt is resolved once per agent per run, so a source that reads the network every time puts a round trip in front of every conversation. PromptFileCache is exported for exactly this.
  • Failure. Whatever load throws ends the run. That is deliberate: an agent answering without the instruction it was written around is worse than a run that says why it stopped. If you would rather degrade than fail, answer a bundled or stale copy inside load instead of throwing.
  • Construction. promptSource takes an instance, not a provider token, so it is built before the NestJS container exists, like storage and pricing. Whatever it depends on you build by hand alongside it.

Returning undefined from load is a normal answer, not a failure: renderFromFile answers undefined in turn and renderFromFileOrFail is the one that throws.

promptSource and prompts.dir cannot be declared together, because prompts.dir configures the source that the other one replaces.

What a variable costs

A prompt built per run is a prompt the provider cannot cache. The system prompt is the head of the prefix, so anything that changes there invalidates everything after it. Measured on this project's own paid tests: 3031 of 3751 prompt tokens came back cached, which was 68% of that run's input bill.

So keep the variable part small and stable within a session. A customer name is fine. A timestamp is not. This is also why the method is called once per agent per run, before the first turn, and never once per turn.

The final instruction is always composed in the same order: the prompt, then the always skills, then the on demand catalog. Because the order is stable, the rest of your prefix stays identical between runs.

Models

A model is an object, not a string. Provider packages ship one class each, and you construct it with the options that provider understands:

import { GeminiModel } from "@nestjs-adk/google";
import { OpenAiModel } from "@nestjs-adk/openai";

const flash = new GeminiModel("gemini-3.5-flash-lite", { apiKey, temperature: 0.2, maxOutputTokens: 512 });
const luna = new OpenAiModel("gpt-5.6-luna", { apiKey, body: { reasoning_effort: "none" } });

defaultModel on the module answers for every agent that declared none. An agent that wants its own passes it in the decorator:

@Agent({ name: "reporter", description: "Builds reports.", model: luna })

OpenAiModel covers every provider that speaks the OpenAI API, which includes OpenAI itself, OpenRouter, Ollama and many others, through its baseUrl. GeminiModel adds the Vertex options.

To route by something the model cannot know (load, cost, a feature flag), implement ModelResolver and declare it as runtime.model.resolver. It is asked once per run, before the first turn, so one run never changes model halfway through by accident.

Retry, which is not failover

Before any chain is walked, the same model is asked again. A 429 carrying a Retry-After is the provider saying when, not never, and spending the failover chain on it pays a call per model to be told the same thing.

BackoffRetryPolicy is on without you declaring anything: two retries, exponential backoff with full jitter, capped at twenty seconds, and a Retry-After the provider sent wins over any calculation. Only a transient failure is retried, so a refused request, a safety block and a context overflow go straight to failover, where another model might take what this one would not.

runtime: RuntimeOptions.from({ model: { retry: new BackoffRetryPolicy(4) } });

An agent overrides it, and false is how one refuses to repeat a call at all:

@Agent({ name: "charger", description: "...", retry: false })

Retries exhausted, the failure falls through to AgentFailoverPolicy exactly as it did before, and each model in the chain gets its own attempt budget. The waiting goes through Clock.sleep, so a test on a FakeClock asserts the delay that was asked for instead of waiting for it.

Failover

A list of models is a chain walked in order when the current one fails before answering:

@Agent({ name: "support", description: "...", failover: [flash, luna] })

When the decision needs logic, implement AgentFailoverPolicy:

export class GiveUpOnBadRequests extends AgentFailoverPolicy {
	public async next(failure: ModelFailure, context: FailoverContext): Promise<LlmModel | undefined> {
		if (failure.isInvalidRequest) return undefined; // every model refuses the same request
		return context.attempts.length === 0 ? flash : luna; // one retry, then degrade
	}
}

ModelFailure is data, not an exception: RateLimitedFailure, TimeoutFailure, UnavailableFailure, ContextExceededFailure, SafetyBlockedFailure, InvalidRequestFailure and UnknownFailure, each answering isTransient and isInvalidRequest. A provider adapter classifies its own errors into these, which is why the decision reads the same whoever failed.

SequentialFailoverPolicy is the built-in walk, and it stops on a refused request: every model in the chain is sent the same thing, so paying for four models to refuse it is not resilience. Two rules hold regardless of policy: a failure after the first chunk never fails over, because part of the answer already reached the consumer, and an aborted request never fails over. When the policy runs out, the run throws ModelsExhaustedError carrying every failure it collected.

Each call is billed under the model that served it, so a reroute shows up on its own line in result.cost.byModel.

Restricting options per model

Some models reject parameters their siblings accept, and reasoning models often pin temperature. createModelSpec narrows the options at compile time from a map you own, since the library deliberately does not track per-model capabilities:

const MyGemini = createModelSpec(GeminiModel)<{
	"gemini-3.5-flash-lite": Omit<GeminiOptions, "temperature">;
}>();

new MyGemini("gemini-3.5-flash-lite", { temperature: 0.2 }); // compile error
new MyGemini("gemini-3.5-pro", { temperature: 0.2 }); // outside the map, full options

It is type-only: at runtime MyGemini is GeminiModel, with no extra behaviour.

Your own model

When no provider package fits (an internal proxy, a provider without an OpenAI-compatible API, a plain HTTP call), extend LlmModel. Two methods: what the model is, and how it answers.

export class ClaudeViaProxy extends LlmModel {
	public constructor(private readonly http: ProxyClient) {
		super();
	}

	public descriptor(): ModelDescriptor {
		return new ModelDescriptor(
			new ModelIdentity("acme", "claude-sonnet-5"),
			new ModelContextWindow(200_000, 8_000),
			ModelCapabilities.fromEntries([
				[ModelCapability.TOOLS, true],
				[ModelCapability.MEDIA_INPUT, true],
			]),
		);
	}

	public async *generate(request: ModelRequest, signal?: AbortSignal): AsyncIterable<ModelChunk> {
		const stream = await this.http.stream(toClaude(request), { signal });
		for await (const piece of stream) {
			if (piece.type === "text") yield ModelChunk.text(piece.delta);
			if (piece.type === "tool_use") {
				yield ModelChunk.toolCall(new ToolCallDelta(piece.index, piece.json, piece.id, piece.name));
			}
		}
		yield ModelChunk.usage(ModelUsage.fromReport(stream.usage.in, stream.usage.out, stream.usage.cached));
		yield ModelChunk.finish("stop");
	}
}

The ModelRequest arrives ready, with the composed instruction, the conversation as ModelMessages and the tool declarations, and you translate it to your provider's wire format. On the way back the runtime aggregates your chunks: text is a delta, tool calls accumulate by index, usage and finish reason are last one wins.

The descriptor is not decoration. The context window is what compaction measures against, and the capabilities are what the runtime checks before it accepts an attachment or offers tools: a model that never declared MEDIA_INPUT fails a question carrying an image instead of paying for a call that answers about nothing. MEDIA_URL is the second media capability, declared by a provider that fetches a remote address itself; it is what decides whether a signed URL may be handed over or a note has to stand in. UnknownContextWindow is the honest answer when you do not know the size; the runtime reports it rather than guessing.

Honour signal by stopping your upstream call when it fires. Keep the class stateless: one instance is shared by every run, and anything per request belongs inside generate, derived from the request.

Sessions

Pass a sessionId and the conversation continues; leave it out and a new one starts. Every run is journaled as events, and the history is replayed into the model's context on the next one.

const first = await support.ask("where is my order?", { metadata: { customerId: user.email } });
const second = await support.ask("and the other one?", first.sessionId);

Naming the conversation yourself

When your application already has an identifier for the conversation, usually the chat row it just wrote, open the session under that identifier instead of asking a question to find out what the runtime named it:

const chat = await this.chats.create({ userId: user.id });
await support.createSession({ sessionId: chat.id, metadata: { customerId: user.email } });

const answer = await support.ask("where is my order?", chat.id);

createSession writes the head of the conversation, and the metadata you gave it as events under the run that opened it. Nothing else: the journal's conversation still begins with the first question, which is also when a consumer sees a PublishedEvent of type "session.created". Leave sessionId out and the runtime names the conversation, which is the way to get the identifier before anything is asked.

An identifier that already names a conversation is refused with SessionAlreadyExistsError, and the existing conversation is untouched. Two requests opening the same chat is the ordinary case rather than the exotic one: one wins, the other reads the error as already done.

Asking does not change. A question naming a conversation nobody opened is still refused with SessionNotFoundError, so a stale or mistyped id fails loudly instead of quietly becoming a second conversation.

Reading a conversation by identifier comes in the two usual shapes, and both answer the head alone without replaying the journal:

const maybe = await support.findSessionById(chat.id); // Session | undefined
const session = await support.findSessionByIdOrFail(chat.id); // throws SessionNotFoundError

The head says which agent roots the conversation, where it stands and how far its journal got. It does not say who owns it: the lib never checks that, so authorizing a sessionId before you call is your application's job, and whatever identifies the person belongs in the metadata above. inspect(sessionId) answers the projected side, metadata included.

Storage goes through SessionStorage. InMemorySessionStorage is the default and is right while a process is running. SqliteSessionStorage is the same thing on disk, for development and for tests that want a conversation to survive a restart. Neither is meant to carry production traffic: for that you implement the port against the database you already run.

AdkModule.forRoot(
	AdkModuleOptions.from({
		defaultModel,
		storage: new SqliteSessionStorage(new SqliteConnection("store.db")),
	}),
);

Artifacts are the other half of a durable conversation, and they have their own port: see Artifacts for why an in memory artifact store and a durable journal together leave a conversation naming content nothing can resolve.

The journal is the source of truth. Snapshots exist only to avoid replaying a long conversation from the first event, are always disposable, and are governed by runtime.snapshots, which is RevisionBucketSnapshotPolicy.everyFiftyEvents() unless the application extends SnapshotPolicy with a rule of its own. A port that cannot do everything says so through StorageCapabilities rather than failing halfway.

Writing a storage of your own

Everything an adapter needs is published, and it is codecs rather than parts. Each one turns a domain object into a record of plain values and back, so an adapter moves rows and never builds an event, a header, a projected state or a compacted block by hand:

import { SessionStorage, StorageCodecs, StoredSessionEvent } from "@nestjs-adk/core";

class PrismaSessionStorage extends SessionStorage {
	private readonly codecs = StorageCodecs.standard();

	public async *readEvents(context: SessionContext, after: SessionRevision) {
		const sessionId = context.sessionId;
		for await (const row of this.cursorOf(sessionId, after)) {
			yield new StoredSessionEvent(sessionId, new SessionRevision(row.revision), this.codecs.journal.decode(row));
		}
	}
}

Every method of the port takes a SessionContext first, and it names the session, so nothing here is passed an id alongside one. What it adds over an id is the conversation's own metadata: an adapter that prefixes a bucket by tenant or picks a shard reads context.metadata.find(TENANT) instead of being told to guess. On a read that has not happened yet the metadata is empty, since it is the fold of the journal about to be read; a write always carries what the run already folded. ArtifactStorage is the same shape, deleteAll(context) included. Build one with SessionContext.fromSessionId(id).

decode takes the row your driver handed back, whichever shape it is in: a JSON column that arrived parsed and one that arrived as text are both accepted. What comes back is the event class the runtime decides on, which is the part that cannot be approximated. A plain object with the right fields passes every check in the runtime without matching one, and the conversation reads back as empty instead of failing.

Four codecs cover the four collections: journal, snapshot, head and checkpoint. journal.calculateFingerprint is how a retried batch is told from an event id that came back carrying something else, which is what idempotent append means. The errors the port is expected to throw ship here too: SessionNotFoundError, SessionAlreadyExistsError, SessionRevisionConflictError and JournalCorruptedError.

Then prove it, with the same cases the adapters here answer. The suite lives in @nestjs-adk/testing, because measuring an adapter is testing:

import { SessionStorageContractSuite } from "@nestjs-adk/testing";

const suite = new SessionStorageContractSuite();
for (const contract of suite.cases(() => new PrismaSessionStorage(prisma))) {
	it(contract.name, () => contract.run());
}

The suite is data, not a test file, so vitest, jest and node:test all drive it. It reads your capabilities() and only demands what you claimed: a storage honest about being ephemeral is not held to optimistic concurrency, and one claiming durability is held to all four guarantees. It is written against this package's published API and nothing else, which is the same constraint your adapter is under.

inspect answers where a conversation stands without running anything:

const inspection = await support.inspect(sessionId);
inspection.isAwaitingApproval;
inspection.approval.awaiting; // the calls a human still has to answer

Capping the loop

A lost model can call tools forever, and a broken tool can fail forever while the model retries. Both burn tokens. RunLimits caps three things:

AdkModule.forRoot(
	AdkModuleOptions.from({
		defaultModel,
		runtime: RuntimeOptions.from({ limits: new RunLimits(16, 2) }),
	}),
);

maxIterations is how many model and tool round trips one run may take; past it the run throws AgentMaxIterationsError. It defaults to 50, because a model looping on a tool it cannot satisfy spends money until something stops it. RunLimits.unbounded() takes the ceiling off, and it has to be asked for:

runtime: RuntimeOptions.from({ limits: RunLimits.unbounded() });

maxConsecutiveToolFailures is a breaker per tool: the same tool failing that many times in a row throws ToolRepeatedFailureError without waiting for the bigger cap, and a success resets the count.

maxInvalidArgs is the third and the only one always on, defaulting to 2. It counts how many times the model may call a tool with arguments the schema rejects. The first mistakes go back to the model as a result it can act on, because the model wrote the argument and usually fixes it next call, while throwing would kill a run over a missing field. Past the limit the run throws ToolInvalidArgsError. It only counts for declared tools: a tool from an external catalog carries the server's own schema, and a bad call comes back from the server as an error the model reacts to.

Three levels declare them, and each replaces the one above it field by field: the module, then the agent in @Agent, then the call. A field a level left out keeps whatever the level above decided, so an agent that only needs more round trips says only that.

@Agent({
	name: "sales",
	description: "Catalog, prices and quotes.",
	limits: new RunLimits(16),
})
export class SalesAgent extends AdkAgent {}

Replacing is not narrowing: an agent that declares 16 runs under 16 even when the module said 8. A sector that genuinely needs more round trips is the reason the field exists, and making it a ceiling would leave the application raising the module limit for everyone instead.

Keeping the context small

Long conversations and big tool results both eat the window, and each has its own answer.

A tool result above 20 thousand characters is stored as an artifact, and the model gets a placeholder naming it and saying how to read it. runtime.context.offload decides the threshold: CharacterCountOffloadPolicy.byDefault(), above(n) or disabled(). It is a port, so an application that decides by media type or by tool extends OffloadPolicy instead. The section below is what the model does with the placeholder.

For long histories there is compaction, and it is on without you declaring anything. Once a conversation passes nine tenths of the model's window it is shortened to seven tenths, oldest closed exchanges first, keeping the four most recent. Declare a ContextSummarizer and what leaves is replaced by a summary:

runtime: RuntimeOptions.from({
	context: { summarizer: new StoreSummarizer(flash) },
});

Without one the same conversation simply forgets, which is why declaring a summarizer matters more than the thresholds: a customer who gave their order number ten turns ago should not have to give it again.

The thresholds are shares of the window and not token counts, because the same count is comfortable in a window of a million and impossible in one of a hundred and twenty eight thousand. Say your own:

runtime: RuntimeOptions.from({
	context: { compaction: new WindowShareCompactionPolicy({ maxShare: 0.8, targetShare: 0.5, keepRecentBlocks: 6 }) },
});

The ceiling is measured against what the provider reported, so a conversation nobody has had is never compacted, and neither is one running on a model that never declared its window: a share of an unstated limit is not a number this library will invent. If you need a conversation shortened there anyway, extend AdkCompactionPolicy with the size you have in mind.

The policy decides whether and how much; CompactionStrategy decides how. The shipped one, OldestFirstCompactionStrategy, drops the oldest answered exchanges and summarizes what fell. An application with another idea declares it once:

runtime: RuntimeOptions.from({ context: { compactionStrategy: new MyStrategy() } });

An agent may declare its own compaction, and like limits it replaces the module's rather than narrowing it. Here it is the whole policy that is replaced and not a field: two policies deciding how much to keep would be one of them shortening what the other just decided to hold on to.

compaction: false turns it off, at either level, for a conversation that may not lose a word. It is a different statement from saying nothing: an agent that declared false stays uncompacted under a runtime that declared a policy, and when it outgrows its window the call is refused with ContextBudgetExceededError rather than the beginning of the conversation being dropped quietly.

Reading how full the window is

const budget = await this.support.contextBudget(chatId);

budget.usedTokens?.tokens; // what the provider counted for the last call
budget.projectedUsedShare; // that count as a share of this model's window
budget.projectedFreeTokens; // what is left of it

It reads and never runs a turn. What it describes is the last call a provider actually counted, so a conversation nobody has asked anything in answers a window and no size, and so does one continued under a different model until that model answers once: a count taken by one provider divided by another one's window is a wrong number that looks right.

This is the meter, not the decision. What compacts is the policy above, during a run, on the prompt about to be sent.

Artifacts, and asking questions of one

An artifact is content the session owns and the model addresses without reading: a result the runtime moved out of the context, an image the user sent, or a file the application attached. The placeholder the model reads says what it is and how to get at it:

[artifact a-1 "orders.json", application/json, 40000 characters, read with read_artifact(artifactId, offset, limit), and its shape is one the artifact exploration tools understand]

It names read_artifact and no other tool on purpose. That sentence is durable: it is written into the journal and read back on every later turn, so it cannot know which agent will read it, and naming outline_artifact to an agent that was never given it is an instruction the model can only waste a call on. Every agent that has tools has read_artifact.

Seven tools answer it, all owned by the runtime, and none of them is exempt from anything. Your access policy is asked about read_artifact exactly as it is asked about your own tools, your approval policy is asked about edit_artifact the same way, and every one of them works inside the session that asked, so knowing an id is not enough to read one. Every one that opens an artifact refuses bytes with a reason: an image is an artifact too, and no tool reads a page of base64.

Those seven names belong to the runtime, and so do the three it adds to a catalog by itself: activate_skill, transfer_to_agent and delegate_to_agent. An agent that declares a tool of its own under one of the ten fails the boot with DuplicateRuntimeToolNameError, which names the tool, the agent and the provider that declared it. The runtime binds its own after yours, so before this the model was offered the runtime's tool under your name and your tool was dropped with nothing said anywhere. The way to get the runtime's tool is to list the class; the way to keep yours is to rename it.

The last three reach a catalog only when the agent has an on-demand skill, a transfer edge or a delegation edge, and they are reserved on every agent anyway. Reserving them only where the edge exists would let your own transfer_to_agent work until the day somebody adds a transfer target to that agent, and the boot would then break for a reason nowhere near that edit.

read_artifact is there for every agent that has any tools at all. The other six are opt in, listed on the agent that needs them:

import { ArtifactExplorationTools, EditArtifactTool, OutlineArtifactTool, SliceArtifactTool } from "@nestjs-adk/core";

@Agent({
	name: "analyst",
	description: "Reads what the customer sends.",
	tools: [LookupOrderTool, ...ArtifactExplorationTools],
})
export class AnalystAgent extends AdkAgent {}

@Agent({
	name: "importer",
	description: "Reads spreadsheets, and corrects the rows it was told to.",
	tools: [OutlineArtifactTool, SliceArtifactTool, EditArtifactTool],
})
export class ImporterAgent extends AdkAgent {}

The class is a request and the runtime binds it to the store it composed, so nothing is wired by hand and nothing is instantiated by you. ArtifactExplorationTools is the five that read, for an agent that should open whatever it is handed; an agent that only ever sees CSV lists the ones it uses. EditArtifactTool is never in that group and is always listed on its own, because a name that says exploration must not quietly carry a write. Outside a container, where you build an AgentDefinition yourself, SliceArtifactTool.request() is the same thing.

They are opt in because a tool declaration is prompt you pay for on every turn. The six cost 5 374 characters of name, description and schema in the prefix of every agent that carries them, and an agent that never sees an artifact was paying for all of it. Opting in is also what keeps them out of the way of an agent whose own tools they would crowd.

| Tool | Arguments | Answers | | --- | --- | --- | | list_artifacts | none | the session's artifacts, newest first: id, name, type, size, and whether each one is explorable. It stops at a hundred and says truncated | | read_artifact | artifactId, offset?/limit? in characters or fromLine?/lines? in lines | a page, the total, and whether more remains | | outline_artifact | artifactId, depth? | for JSON, the keys, the types and array lengths down to depth (2 by default); for a CSV, the columns with a type and a sample, and the row count; for Markdown, the headings with their line; for text, the lines, characters and how it starts | | search_artifact | artifactId, query, regex?, caseSensitive?, mode?, maxMatches?, context? | where a string appears: excerpts around each hit, lines with the whole line, or count alone, plus totalMatches, counted up to ten thousand, with countStopped when it hit that | | query_artifact | artifactId, pointer | the value at an RFC 6901 JSON Pointer such as /orders/0/total, or an outline of it when it is too large | | slice_artifact | artifactId, fromRow?, toRow?, columns? | a rectangle of a CSV, by row range and column name | | edit_artifact | artifactId, edits | the new size, and per block where it landed and how much it removed and added |

Reading is paged, and the page nobody asked for is the offload threshold itself: exactly the largest answer the runtime was willing to leave in a context. A page past the end is empty rather than an error, which is how a model finds out where the content stops. Reading by line exists because a search answers with a line; fromLine is how the model follows it up. The outline is decided by parsing, in the order JSON, CSV, Markdown, text, and never by the declared type.

Whether a placeholder calls the content explorable at all follows the policy, not the bytes. OffloadPolicy.decide answers inline, opaque or explorable, and the shipped one calls JSON and text explorable and everything else opaque, because telling a model a shape is worth exploring when no tool can parse it is a call spent being told no. list_artifacts answers on the same rule, one explorable boolean per entry.

Every answer is budgeted at the offload threshold, which is what stops a tool written to help a model read something too large from producing something too large. The budget is max(threshold, 1000) and offload triggers strictly above the threshold, so at any threshold of a thousand or more a fitted answer stays inline by arithmetic rather than by an exemption. Anything cut to fit says truncated: true rather than pretending it is complete. read_artifact repaginates in a loop until the answer fits, and a line read that is still over budget after that degrades to a page addressed by character at the start of the requested line, so no answer stays over budget on either path. One corner is worth knowing: below a threshold of a thousand the floor sits above it, so a runtime answer can be offloaded once (it stops growing there, and maxIterations ends the run in any case).

Two things these tools deliberately cannot do. query_artifact takes a JSON Pointer and only a pointer, and slice_artifact takes rows and column names and nothing else: JSONPath filters are an expression language, and an expression language whose source is a string the model wrote is code execution with extra steps. search_artifact is a literal string unless you pass regex: true, and a pattern then goes through a guard that refuses anything that could backtrack: a quantifier on a group that itself repeats or branches, a backreference, lookaround, a repetition over 100, or more than 200 characters. A refused pattern comes back as { refused: true, reason } the model can correct, not as a failed run.

One ceiling: a tool that opens an artifact reads all of it, and runtime.context.maxExplorableCharacters (twenty million by default) is the largest one it will. Above that it refuses with a reason, before reading a byte. The one way past it is read_artifact by character range, which asks the store for a range instead of the whole thing and so works at any size. Reading by line does not, because line starts are not known without the whole text.

Whatever comes back is still content somebody else wrote. See the note on tool results below: the library marks none of it.

Changing one in place

An agent handed a file usually has to hand one back. edit_artifact changes a text artifact where it lives, keeping its id, so the placeholder the conversation already wrote still points at it. It takes edits, one string holding one or more git conflict style blocks, the format Aider and Cline use:

<<<<<<< SEARCH
	const timeout = 30;
=======
	const timeout = 120;
>>>>>>> REPLACE

Blocks are applied in order, each against the result of the one before it. Matching is exact and never fuzzy, indentation and line endings included, and a SEARCH section has to appear exactly once. A block that matches nothing, or matches twice, is refused with a reason the model can act on, and nothing at all is written: a half applied edit leaves a file in a state nobody wrote, and a fuzzy match corrupts content in silence, which is worse than a call spent being told to read the part first. A malformed block is refused the same way, named by the line it broke on and shown the shape it should have had. An empty REPLACE section deletes the SEARCH text.

edit_artifact declares ToolEffect.WRITE, so an approval policy that holds writes holds it and the change waits for a person:

runtime: RuntimeOptions.from({ tools: { approvals: EffectApprovalPolicy.from(ToolEffect.WRITE) } });

The answer carries the new character count, because a placeholder written into the journal earlier still quotes the old one and nothing rewrites a past event.

Where the bytes live

ArtifactStorage is the port, InMemoryArtifactStorage is the default and SqliteArtifactStorage is the durable one. Point it at the same file as the sessions:

const connection = new SqliteConnection("store.db");

AdkModule.forRoot(
	AdkModuleOptions.from({
		defaultModel,
		storage: new SqliteSessionStorage(connection),
		artifacts: new SqliteArtifactStorage(connection),
	}),
);

The two belong together for a reason that is not tidiness. A journal is durable and an in memory artifact store is not, so a conversation restored after a restart names artifacts nothing can resolve, and the model is left reading a sentence about content it has no way to reach. The same is true the moment there are two processes: whichever one did not write the artifact cannot read it.

So a runtime composed to offload into InMemoryArtifactStorage reports ArtifactsNotDurable through ContextNoticeSink at boot. It is a notice and not a refusal, because one process is a perfectly correct way to run a script, a test or a container, and there is no logger behind it: declare the sink and you hear it, declare nothing and the library stays quiet.

class StoreNotices extends ContextNoticeSink {
	public report(context: SessionContext | undefined, notice: ContextNotice): void {
		this.logger.warn(notice.message);
	}
}

The fix is one line either way: a durable store, or offload: CharacterCountOffloadPolicy.disabled(), which keeps large results in the prompt and pays for them there.

An artifact is mutable. ArtifactStorage.update(context, reference, content) replaces what one holds while keeping its id and its place in the session's list, and it is what edit_artifact calls. The reference you pass is the one you read, and its digest is the lock: the store compares it with what it holds now and throws TamperedArtifactReferenceError when the two disagree, instead of overwriting a write somebody else made in between. Writing is scoped like reading, so a reference from another conversation answers ArtifactNotFoundError and nothing is written.

Mutating content a durable journal points at is safe here because the journal never persists a digest. It keeps the artifact id, and every read path looks the reference up again before reading it, so there is no stored digest anywhere that an edit could invalidate. The one thing it cannot fix is a sentence: a placeholder in a past event still quotes the character count the artifact had then, and nothing rewrites past events, which is why edit_artifact answers with the new size.

update is abstract and not a default that throws, so an ArtifactStorage you wrote yourself does not compile until you implement it. That is deliberate. A default would split stores into ones that can be edited and ones that cannot, and you would find out which kind you had when a model called edit_artifact in production.

Writing your own works like the session port, and is measured the same way:

import { ArtifactStorageContractSuite } from "@nestjs-adk/testing";

const suite = new ArtifactStorageContractSuite();
for (const contract of suite.cases(() => new S3ArtifactStorage(client))) {
	it(contract.name, () => contract.run());
}

It demands the guarantees the port is written about: what comes out of read is what went into put, name and encoding included, verified against the digest the reference carries; bytes come back as bytes; a session only ever reads its own, with anything else answered as absent rather than refused, because an id is guessable and a refusal confirms it exists; list answers the session's own, newest first, up to the bound; readRange answers the same characters a full read would; and update replaces content without moving the artifact, refuses a reference the content has moved past, and refuses one session writing another's. readRange has a default that reads and slices, so an adapter only overrides it to do better. Both shipped stores answer the same cases.

Transfer and delegation

Two agents can work on one conversation, and the difference is who owns it afterwards.

A transfer hands the conversation over. Whoever received it answers from then on, including on the next question:

@Agent({ name: "concierge", description: "Triage." })
@TransfersTo(SalesAgent, WarrantyAgent)
export class ConciergeAgent extends AdkAgent {}

A delegation asks somebody one question and keeps the conversation where it is. The answer comes back as the result of the call that asked for it:

@Agent({ name: "warranty", description: "Returns and warranties." })
@DelegatesTo(BillingAgent)
export class WarrantyAgent extends AdkAgent {}

Both give the model a tool (transfer_to_agent, delegate_to_agent) restricted to the targets you declared, and both are also available from code: agent.delegate(sessionId, to, task) runs one through the same edges and the same events. A target nobody declared is refused, at boot when it is not an agent at all and at run time when the edge does not exist. Both names are the runtime's, on every agent, so a tool of your own called transfer_to_agent or delegate_to_agent fails the boot: see Artifacts.

A delegated run is a run of its own: its own model, tools, context and limits, resolved from scratch for the child. It writes to the same journal, its cost joins the parent's total once with the child's model listed separately, and neither agent reads the other's conversation. A chain three deep is refused, and so is a session handed back and forth more than eight times.

Human approval

Some actions should not run without a person saying yes. The tool declares what it does to the world:

@Tool({ name: "issue_refund", description: "Refunds an order.", schema, effect: "destructive" })

The scale is ordered: read observes, write changes state the same API can undo, and destructive has no undo, which covers deleting but also sending an email or charging a card. A tool that declares no effect counts as write. A tool that arrived from a source carries the server's own annotation, and an unannotated one counts as destructive.

What pauses is policy, declared once for the runtime:

runtime: RuntimeOptions.from({ tools: { approvals: EffectApprovalPolicy.from(ToolEffect.DESTRUCTIVE) } });

It reads as "from this level up, pause". EffectApprovalPolicy.destructiveOnly() is the default, so a tool declared destructive waits for a person unless the application says otherwise: the cost of that being wrong is a run that waits, and the cost the other way is an effect nobody agreed to. EffectApprovalPolicy.never() pauses nothing, and is how an application takes the gate off. Implement AdkApprovalPolicy when the decision needs more than the effect: requires(tool, invocation, actor) also receives who is asking, when the run was given an actor, which is how one person's reads run on their own while another's wait for a click.

The policy is asked about every tool, the runtime's own included. There is no exemption: read_artifact, transfer_to_agent and delegate_to_agent all declare read, so the default holds none of them, and edit_artifact declares write, so a policy from write up holds it. A rule you wrote about who may change what should not have a hole in it where the library's own tools are.

When the model calls a tool at or above that level, the tool does not run. The run suspends and comes back with the call waiting:

const result = await support.ask("refund order A-1042", { sessionId });
result.isAwaitingApproval; // true
result.awaiting[0]?.callId; // what a human is answering about

Your application shows that to a person, and then:

await support.approve(sessionId, callId, { by: "gabriel" }); // runs the tool, resumes the run
await support.reject(sessionId, callId, "outside the window", { by: "gabriel" }); // tells the model why

Both return an ordinary AgentResult, so the conversation carries on. A turn holding two calls stays suspended until both are answered: running half of it would put an effect in the world nobody finished agreeing to.

The decision is a new run, minutes or days later and possibly in another process. Nothing is held in memory between the two: the pending call lives in the journal, and the runtime keeps no credentials. That is why a held call that came from a source needs sources declared again on the decision, and why short-lived credentials belong inside the tool rather than carried across the pause.

Streaming

stream runs exac