@rubrion/mastra-cloudflare 0.0.0-stage → 0.2.0

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.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @rubrion/mastra-cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Mastra](https://mastra.ai) agents on Cloudflare Workers, without the boilerplate:
4
+
5
+ - **`createAgentServer`**: an OpenAI-compatible server (`/v1/models`, `/v1/chat/completions` with real SSE streaming) for your agents, as a Worker `fetch` handler, with no HTTP framework and a small startup cost. `model: "auto"` routes each message to the right agent, or splits it across up to three.
6
+ - **`defineAgents`**: agents as plain config, built lazily once per isolate (bindings and secrets are only readable inside a request).
7
+ - **`d1Memory`**: Mastra Memory on D1, no vector store to pay for.
8
+ - **`workersAI`**, **`openAICompatible`**, **`providerModel`**: models from Workers AI, any OpenAI-compatible endpoint, or the provider each request carries.
9
+ - Re-exports `Agent`, `createTool`, `z` and `RequestContext`, so a project needs only this package.
10
+
11
+ The [rubry template](https://github.com/rubrion/rubry) puts it to work: agents plus a middleware with API keys and a settings page.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @rubrion/mastra-cloudflare
17
+ ```
18
+
19
+ `wrangler.jsonc` needs `"compatibility_flags": ["nodejs_compat"]`.
20
+
21
+ ## A Worker in 20 lines
22
+
23
+ ```ts
24
+ import { env } from 'cloudflare:workers';
25
+ import { createAgentServer, createTool, d1Memory, defineAgents, z } from '@rubrion/mastra-cloudflare';
26
+
27
+ const time = createTool({
28
+ id: 'current_time',
29
+ description: 'The current date and time.',
30
+ inputSchema: z.object({}),
31
+ execute: async () => ({ now: new Date().toISOString() }),
32
+ });
33
+
34
+ const agents = defineAgents(
35
+ [
36
+ { id: 'writer', name: 'Writer', description: 'Writes and edits text.', instructions: 'Write what is asked, briefly.' },
37
+ { id: 'helper', name: 'Helper', description: 'General questions; knows the time.', instructions: 'Be useful.', tools: { current_time: time } },
38
+ ],
39
+ { memory: d1Memory(() => env.MEMORY) },
40
+ );
41
+
42
+ export default createAgentServer({
43
+ agents,
44
+ apiKey: (e: Env) => e.API_KEY,
45
+ provider: (e: Env) => ({ baseURL: 'https://api.openai.com/v1', apiKey: e.OPENAI_API_KEY, model: 'gpt-5-mini' }),
46
+ });
47
+ ```
48
+
49
+ ```bash
50
+ curl -N http://localhost:8787/v1/chat/completions -H "Authorization: Bearer $API_KEY" \
51
+ -H "Content-Type: application/json" \
52
+ -d '{"model":"auto","stream":true,"messages":[{"role":"user","content":"What time is it?"}]}'
53
+ ```
54
+
55
+ ## Server
56
+
57
+ `createAgentServer({ agents, name?, apiKey?, provider?, planner?, maxSteps?, maxAgents? })` returns `{ fetch(request, env) }`. `maxSteps` (tool rounds per reply, default 5) and `maxAgents` (how many agents `auto` may split a request across, default 3) take a number or `(env) => number`.
58
+
59
+ Replies carry OpenAI's `usage` (prompt, completion and total tokens over the planner, every agent and every tool round): in the JSON body, or on the final chunk when streaming.
60
+
61
+ | Route | |
62
+ |---|---|
63
+ | `GET /` | health: name and agent ids |
64
+ | `GET /v1/models` | `auto` (when it can route) and each agent, with its description |
65
+ | `POST /v1/chat/completions` | `model`: agent id or `auto`; `stream: true` for SSE; text and `image_url` content |
66
+
67
+ Per-request headers, for a middleware in front (see `HEADERS`):
68
+
69
+ | Header | |
70
+ |---|---|
71
+ | `X-Provider-Base-URL` / `X-Provider-Key` / `X-Provider-Model` | the model for this request (else `provider(env)`) |
72
+ | `X-Agents: a,b` | only these agents are on |
73
+ | `X-Session-Id` | memory per (session, agent): send only the new message. Needs `memory` on `defineAgents` |
74
+
75
+ ## Agents
76
+
77
+ ```ts
78
+ interface AgentSpec {
79
+ id: string;
80
+ name: string;
81
+ description: string; // the router picks agents by it
82
+ instructions: string | ((args: { requestContext }) => string);
83
+ model?: (requestContext) => Model; // default: providerModel (the request's provider)
84
+ tools?: Record<string, Tool>;
85
+ maxOutputTokens?: number;
86
+ enabled?: () => boolean; // off when its configuration is missing
87
+ }
88
+ ```
89
+
90
+ `defineAgents(specs, { memory })` returns `{ list(), find(id), get(id) → { agent, spec }, mastra() }`. Specs can carry extra fields of your own (`defineAgents<MySpec>(…)`). `buildAgent(spec)` builds one uncached Agent, e.g. per request.
91
+
92
+ ## Models
93
+
94
+ ```ts
95
+ openAICompatible({ baseURL, apiKey, model }); // OpenAI, OpenRouter, LiteLLM, vLLM, Ollama, another agent server…
96
+ workersAI(env.AI, '@cf/google/gemma-4-26b-a4b-it', { thinking: true }); // with providerOptions: workersAIOptions(true)
97
+ providerModel(requestContext, fallback?); // the provider the request carries
98
+ ```
99
+
100
+ `workersAI` with `thinking` drops `reasoning_effort` from the binding call: Mastra sends the AI SDK's unified `reasoning` option, and reasoning models such as Gemma 4 stop thinking whenever it is present.
101
+
102
+ ## License
103
+
104
+ GPL-3.0-only
@@ -0,0 +1,47 @@
1
+ import { Agent } from '@mastra/core/agent';
2
+ import { Mastra } from '@mastra/core/mastra';
3
+ import type { MastraMemory } from '@mastra/core/memory';
4
+ import type { RequestContext } from '@mastra/core/request-context';
5
+ import { type Model } from './models.js';
6
+ export interface AgentSpec {
7
+ id: string;
8
+ name: string;
9
+ /** What the agent is for, in one or two sentences. The router picks agents by it. */
10
+ description: string;
11
+ instructions: string | ((args: {
12
+ requestContext: RequestContext;
13
+ }) => string);
14
+ /** Its model; by default the request's provider (`providerModel`). */
15
+ model?: (requestContext: RequestContext) => Model;
16
+ tools?: Record<string, unknown>;
17
+ /** Cap on each reply, in tokens. */
18
+ maxOutputTokens?: number;
19
+ /** Off when its configuration is missing (e.g. a key that isn't set). */
20
+ enabled?: () => boolean;
21
+ }
22
+ export interface AgentsOptions {
23
+ /** Memory every agent shares (see `d1Memory`); without it agents are stateless. */
24
+ memory?: () => MastraMemory;
25
+ }
26
+ /** A Mastra Agent from a spec, not cached: for agents made per request. */
27
+ export declare function buildAgent(spec: AgentSpec, { memory }?: AgentsOptions): Agent<string, never, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
28
+ /**
29
+ * The registry of a Worker's agents. `T` can carry app-specific fields
30
+ * (a tagline, a price) next to the spec's own.
31
+ */
32
+ export declare function defineAgents<T extends AgentSpec>(specs: T[], options?: AgentsOptions): {
33
+ specs: T[];
34
+ memory: (() => MastraMemory) | undefined;
35
+ /** The agents that are on. */
36
+ list: () => T[];
37
+ find: (id: string) => T | undefined;
38
+ /** An agent and its spec, or undefined when unknown or off. */
39
+ get(id: string): {
40
+ agent: Agent<string, import("@mastra/core/agent").ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
41
+ spec: T;
42
+ } | undefined;
43
+ /** A Mastra instance with every enabled agent registered (logger, storage wiring). */
44
+ mastra(): Mastra<Record<string, Agent<any, import("@mastra/core/agent").ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>>, Record<string, import("@mastra/core/workflows").AnyWorkflow>, Record<string, import("@mastra/core/vector").MastraVector<any>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").IMastraLogger, Record<string, import("@mastra/core/mcp").MCPServerBase<any>>, Record<string, import("@mastra/core/evals").MastraScorer<any, any, any, any>>, Record<string, import("@mastra/core/tools").ToolAction<any, any, any, any, any, any, unknown>>, Record<string, import("@mastra/core/processors").Processor<any, unknown>>, Record<string, MastraMemory>, Record<string, import("@mastra/core/channels").ChannelProvider>, Record<string, import("@mastra/core/classifier").Classifier<any>>, Record<string, import("@mastra/core/knowledge").Knowledge>>;
45
+ };
46
+ export type AgentRegistry<T extends AgentSpec = AgentSpec> = ReturnType<typeof defineAgents<T>>;
47
+ //# sourceMappingURL=agents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,M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agents.js ADDED
@@ -0,0 +1,53 @@
1
+ // Agents as configuration: a list of specs becomes Mastra Agents, built once
2
+ // per isolate on first use (bindings and secrets are only readable then).
3
+ import { Agent } from '@mastra/core/agent';
4
+ import { Mastra } from '@mastra/core/mastra';
5
+ import { providerModel } from './models.js';
6
+ /** A Mastra Agent from a spec, not cached: for agents made per request. */
7
+ export function buildAgent(spec, { memory } = {}) {
8
+ return new Agent({
9
+ id: spec.id,
10
+ name: spec.name,
11
+ description: spec.description,
12
+ instructions: ({ requestContext }) => (typeof spec.instructions === 'function' ? spec.instructions({ requestContext }) : spec.instructions),
13
+ model: ({ requestContext }) => (spec.model ?? providerModel)(requestContext),
14
+ tools: (spec.tools ?? {}),
15
+ ...(memory ? { memory: () => memory() } : {}),
16
+ });
17
+ }
18
+ /**
19
+ * The registry of a Worker's agents. `T` can carry app-specific fields
20
+ * (a tagline, a price) next to the spec's own.
21
+ */
22
+ export function defineAgents(specs, options = {}) {
23
+ const built = new Map();
24
+ let mastra;
25
+ const list = () => specs.filter((s) => s.enabled?.() ?? true);
26
+ const find = (id) => list().find((s) => s.id === id);
27
+ const agentOf = (spec) => {
28
+ let agent = built.get(spec.id);
29
+ if (!agent) {
30
+ agent = buildAgent(spec, options);
31
+ built.set(spec.id, agent);
32
+ }
33
+ return agent;
34
+ };
35
+ return {
36
+ specs,
37
+ memory: options.memory,
38
+ /** The agents that are on. */
39
+ list,
40
+ find,
41
+ /** An agent and its spec, or undefined when unknown or off. */
42
+ get(id) {
43
+ const spec = find(id);
44
+ return spec ? { agent: agentOf(spec), spec } : undefined;
45
+ },
46
+ /** A Mastra instance with every enabled agent registered (logger, storage wiring). */
47
+ mastra() {
48
+ mastra ??= new Mastra({ agents: Object.fromEntries(list().map((s) => [s.id, agentOf(s)])) });
49
+ return mastra;
50
+ },
51
+ };
52
+ }
53
+ //# sourceMappingURL=agents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.js","sourceRoot":"","sources":["../src/agents.ts"],"names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js';
2
+ export { openAICompatible, providerModel, workersAI, workersAIOptions, PROVIDER, DEFAULT_MODEL, type AiBinding, type Model, type ProviderConfig } from './models.js';
3
+ export { buildAgent, defineAgents, type AgentRegistry, type AgentSpec, type AgentsOptions } from './agents.js';
4
+ export { createAgentServer, HEADERS, type AgentServerOptions } from './server.js';
5
+ export { plannerAgent, RoutingPlanSchema, type RoutingPlan } from './routing.js';
6
+ export { Agent } from '@mastra/core/agent';
7
+ export { Mastra } from '@mastra/core/mastra';
8
+ export { RequestContext } from '@mastra/core/request-context';
9
+ export { createTool } from '@mastra/core/tools';
10
+ export { z } from 'zod';
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,EAAE,KAAK,SAAS,EAAE,KAAK,KAAK,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AACrK,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,KAAK,aAAa,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAC/G,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAGjF,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // @rubrion/mastra-cloudflare: Mastra agents on Cloudflare Workers.
2
+ export { d1Memory } from './memory.js';
3
+ export { openAICompatible, providerModel, workersAI, workersAIOptions, PROVIDER, DEFAULT_MODEL } from './models.js';
4
+ export { buildAgent, defineAgents } from './agents.js';
5
+ export { createAgentServer, HEADERS } from './server.js';
6
+ export { plannerAgent, RoutingPlanSchema } from './routing.js';
7
+ // So a project needs only this package to define agents and tools.
8
+ export { Agent } from '@mastra/core/agent';
9
+ export { Mastra } from '@mastra/core/mastra';
10
+ export { RequestContext } from '@mastra/core/request-context';
11
+ export { createTool } from '@mastra/core/tools';
12
+ export { z } from 'zod';
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EAAE,QAAQ,EAAwB,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,EAAmD,MAAM,aAAa,CAAC;AACrK,OAAO,EAAE,UAAU,EAAE,YAAY,EAA0D,MAAM,aAAa,CAAC;AAC/G,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAA2B,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AAEjF,mEAAmE;AACnE,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { Memory } from '@mastra/memory';
2
+ export interface D1MemoryOptions {
3
+ /** Messages recalled into each prompt; the one memory setting charged per turn. */
4
+ lastMessages?: number;
5
+ /** Store id, for Mastra's logs. */
6
+ id?: string;
7
+ }
8
+ /**
9
+ * A getter for a D1-backed Memory, with no vector store or embedder to pay
10
+ * for. Pass the getter as an agent's `memory`.
11
+ *
12
+ * const memory = d1Memory(() => env.MEMORY, { lastMessages: 8 });
13
+ */
14
+ export declare function d1Memory(binding: () => D1Database, { lastMessages, id }?: D1MemoryOptions): () => Memory;
15
+ //# sourceMappingURL=memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,WAAW,eAAe;IAC/B,mFAAmF;IACnF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mCAAmC;IACnC,EAAE,CAAC,EAAE,MAAM,CAAC;CACZ;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,UAAU,EAAE,EAAE,YAAiB,EAAE,EAAoB,EAAE,GAAE,eAAoB,gBAQpH"}
package/dist/memory.js ADDED
@@ -0,0 +1,19 @@
1
+ // Mastra Memory on D1. Built lazily: D1 table setup is I/O, which Workers only
2
+ // allow inside a request, never at module load. Tables are created on first use.
3
+ import { D1Store } from '@mastra/cloudflare-d1';
4
+ import { Memory } from '@mastra/memory';
5
+ /**
6
+ * A getter for a D1-backed Memory, with no vector store or embedder to pay
7
+ * for. Pass the getter as an agent's `memory`.
8
+ *
9
+ * const memory = d1Memory(() => env.MEMORY, { lastMessages: 8 });
10
+ */
11
+ export function d1Memory(binding, { lastMessages = 10, id = 'mastra-memory' } = {}) {
12
+ let memory;
13
+ return () => (memory ??= new Memory({
14
+ storage: new D1Store({ id, binding: binding() }),
15
+ vector: false,
16
+ options: { lastMessages, semanticRecall: false, generateTitle: false },
17
+ }));
18
+ }
19
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.js","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,iFAAiF;AACjF,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AASxC;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAyB,EAAE,EAAE,YAAY,GAAG,EAAE,EAAE,EAAE,GAAG,eAAe,KAAsB,EAAE;IACpH,IAAI,MAA0B,CAAC;IAC/B,OAAO,GAAG,EAAE,CACX,CAAC,MAAM,KAAK,IAAI,MAAM,CAAC;QACtB,OAAO,EAAE,IAAI,OAAO,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC;QAChD,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE;KACtE,CAAC,CAAC,CAAC;AACN,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { LanguageModelV4 } from '@ai-sdk/provider';
2
+ import type { RequestContext } from '@mastra/core/request-context';
3
+ /** An OpenAI-compatible provider: OpenAI, OpenRouter, a LiteLLM/vLLM/Ollama proxy, another agent server. */
4
+ export interface ProviderConfig {
5
+ baseURL: string;
6
+ apiKey: string;
7
+ model: string;
8
+ /** Shown in Mastra's logs; defaults to "provider". */
9
+ name?: string;
10
+ }
11
+ /** The request-context key the server stores the request's provider under. */
12
+ export declare const PROVIDER = "provider";
13
+ /** The request-context key for the model used when a request carries no provider (see `defaultModel`). */
14
+ export declare const DEFAULT_MODEL = "default-model";
15
+ /** What every factory here returns: an AI SDK language model, as Mastra agents take. */
16
+ export type Model = LanguageModelV4;
17
+ export declare const openAICompatible: (config: ProviderConfig) => Model;
18
+ /**
19
+ * The model of the request's provider (see `PROVIDER`), else `fallback`, else
20
+ * the server's `defaultModel`. The default of every agent that doesn't name
21
+ * its own model.
22
+ */
23
+ export declare function providerModel(requestContext?: RequestContext, fallback?: ProviderConfig): Model;
24
+ /** The slice of the `AI` binding the Workers AI provider calls. */
25
+ export interface AiBinding {
26
+ run(model: string, inputs: Record<string, unknown>, options?: unknown): Promise<unknown>;
27
+ }
28
+ /**
29
+ * A Workers AI model. `thinking` (for reasoning models such as Gemma 4 or
30
+ * Qwen 3) turns their thinking on or off through the chat template; leave it
31
+ * undefined for other models. With thinking on, the binding also drops
32
+ * `reasoning_effort`: Mastra sends the AI SDK's unified `reasoning` option,
33
+ * which the provider turns into `reasoning_effort`, and these models stop
34
+ * thinking whenever it is present at all.
35
+ */
36
+ export declare function workersAI(binding: AiBinding, model: string, { thinking }?: {
37
+ thinking?: boolean;
38
+ }): Model;
39
+ /** Provider options that switch a Workers AI reasoning model's thinking on or off. */
40
+ export declare const workersAIOptions: (thinking: boolean) => {
41
+ 'workers-ai': {
42
+ chat_template_kwargs: {
43
+ enable_thinking: boolean;
44
+ };
45
+ };
46
+ };
47
+ //# sourceMappingURL=models.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,4GAA4G;AAC5G,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,8EAA8E;AAC9E,eAAO,MAAM,QAAQ,aAAa,CAAC;AACnC,0GAA0G;AAC1G,eAAO,MAAM,aAAa,kBAAkB,CAAC;AAE7C,wFAAwF;AACxF,MAAM,MAAM,KAAK,GAAG,eAAe,CAAC;AAEpC,eAAO,MAAM,gBAAgB,GAAI,QAAQ,cAAc,KAAG,KAC8F,CAAC;AAEzJ;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,cAAc,CAAC,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,KAAK,CAM/F;AAED,mEAAmE;AACnE,MAAM,WAAW,SAAS;IACzB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACzF;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,GAAE;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,KAAK,CAU7G;AAED,sFAAsF;AACtF,eAAO,MAAM,gBAAgB,GAAI,UAAU,OAAO;;;;;;CAAgF,CAAC"}
package/dist/models.js ADDED
@@ -0,0 +1,46 @@
1
+ // Model factories for Workers: any OpenAI-compatible endpoint, Workers AI,
2
+ // and the provider a request carries (set by a middleware, see server.ts).
3
+ import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
4
+ import { createWorkersAI } from 'workers-ai-provider';
5
+ /** The request-context key the server stores the request's provider under. */
6
+ export const PROVIDER = 'provider';
7
+ /** The request-context key for the model used when a request carries no provider (see `defaultModel`). */
8
+ export const DEFAULT_MODEL = 'default-model';
9
+ export const openAICompatible = (config) => createOpenAICompatible({ name: config.name ?? 'provider', baseURL: config.baseURL.replace(/\/+$/, ''), apiKey: config.apiKey }).chatModel(config.model);
10
+ /**
11
+ * The model of the request's provider (see `PROVIDER`), else `fallback`, else
12
+ * the server's `defaultModel`. The default of every agent that doesn't name
13
+ * its own model.
14
+ */
15
+ export function providerModel(requestContext, fallback) {
16
+ const config = requestContext?.get(PROVIDER) ?? fallback;
17
+ if (config?.baseURL && config.model)
18
+ return openAICompatible(config);
19
+ const model = requestContext?.get(DEFAULT_MODEL);
20
+ if (model)
21
+ return model;
22
+ throw new Error('No model provider configured for this request');
23
+ }
24
+ /**
25
+ * A Workers AI model. `thinking` (for reasoning models such as Gemma 4 or
26
+ * Qwen 3) turns their thinking on or off through the chat template; leave it
27
+ * undefined for other models. With thinking on, the binding also drops
28
+ * `reasoning_effort`: Mastra sends the AI SDK's unified `reasoning` option,
29
+ * which the provider turns into `reasoning_effort`, and these models stop
30
+ * thinking whenever it is present at all.
31
+ */
32
+ export function workersAI(binding, model, { thinking } = {}) {
33
+ const ai = {
34
+ run: (m, inputs, options) => {
35
+ if (thinking === undefined)
36
+ return binding.run(m, inputs, options);
37
+ const { reasoning_effort: _ignored, ...rest } = inputs;
38
+ const kwargs = { ...inputs.chat_template_kwargs, enable_thinking: thinking };
39
+ return binding.run(m, { ...(thinking ? rest : inputs), chat_template_kwargs: kwargs }, options);
40
+ },
41
+ };
42
+ return createWorkersAI({ binding: ai })(model);
43
+ }
44
+ /** Provider options that switch a Workers AI reasoning model's thinking on or off. */
45
+ export const workersAIOptions = (thinking) => ({ 'workers-ai': { chat_template_kwargs: { enable_thinking: thinking } } });
46
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,2EAA2E;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAGnE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAWtD,8EAA8E;AAC9E,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAAC;AACnC,0GAA0G;AAC1G,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC;AAK7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAsB,EAAS,EAAE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,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;QACjG,CAAC;KACD,CAAC;IACF,OAAO,eAAe,CAAC,EAAE,OAAO,EAAE,EAAmB,EAAE,CAAC,CAAC,KAA0D,CAAqB,CAAC;AAC1I,CAAC;AAED,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,QAAiB,EAAE,EAAE,CAAC,CAAC,EAAE,YAAY,EAAE,EAAE,oBAAoB,EAAE,EAAE,eAAe,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC"}
@@ -0,0 +1,32 @@
1
+ import { Agent } from '@mastra/core/agent';
2
+ import type { RequestContext } from '@mastra/core/request-context';
3
+ import { z } from 'zod';
4
+ import type { AgentSpec } from './agents.js';
5
+ import { type Model } from './models.js';
6
+ export declare const RoutingPlanSchema: z.ZodObject<{
7
+ slices: z.ZodArray<z.ZodObject<{
8
+ agent: z.ZodString;
9
+ instructions: z.ZodString;
10
+ }, z.core.$strip>>;
11
+ }, z.core.$strip>;
12
+ export type RoutingPlan = z.infer<typeof RoutingPlanSchema>;
13
+ export interface ChatMessage {
14
+ role: string;
15
+ content: unknown;
16
+ }
17
+ /** The planner agent; `candidates` is set per request in its request context. */
18
+ export declare function plannerAgent(model?: (requestContext: RequestContext) => Model, rules?: string): Agent<"planner", import("@mastra/core/agent").ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
19
+ export declare const candidatesJson: (specs: AgentSpec[]) => string;
20
+ /** Keep a model-made plan to known agents; null when nothing usable is left. */
21
+ export declare function sanitizePlan(plan: RoutingPlan | null | undefined, ids: Set<string>, max?: number): RoutingPlan | null;
22
+ export declare const fallbackPlan: (id: string, instructions: string) => RoutingPlan;
23
+ /** The last `n` user turns, each with the replies that followed it. */
24
+ export declare function recentTurns(messages: ChatMessage[], n?: number): ChatMessage[];
25
+ export declare function textOf(content: unknown): string;
26
+ export declare function lastUserText(messages: ChatMessage[]): string;
27
+ /** One reply from several agents: their outputs under their names. */
28
+ export declare const mergeReplies: (parts: {
29
+ name: string;
30
+ text: string;
31
+ }[]) => string;
32
+ //# sourceMappingURL=routing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing.d.ts","sourceRoot":"","sources":["../src/routing.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAiB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAExD,eAAO,MAAM,iBAAiB;;;;;iBAW5B,CAAC;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE5D,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;CACjB;AAWD,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,cAAc,EAAE,cAAc,KAAK,KAAK,EAAE,KAAK,SAAQ,yIAQ5F;AAED,eAAO,MAAM,cAAc,GAAI,OAAO,SAAS,EAAE,WAA+F,CAAC;AAEjJ,gFAAgF;AAChF,wBAAgB,YAAY,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,SAAI,GAAG,WAAW,GAAG,IAAI,CAGhH;AAED,eAAO,MAAM,YAAY,GAAI,IAAI,MAAM,EAAE,cAAc,MAAM,KAAG,WAA0D,CAAC;AAE3H,uEAAuE;AACvE,wBAAgB,WAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,CAAC,SAAI,GAAG,WAAW,EAAE,CAGzE;AAED,wBAAgB,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAI/C;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAG5D;AAED,sEAAsE;AACtE,eAAO,MAAM,YAAY,GAAI,OAAO;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,WAC2C,CAAC"}
@@ -0,0 +1,62 @@
1
+ // Multi-agent routing: a planner agent reads the agents' descriptions and the
2
+ // last few turns, and assigns the request to one or more of them (at most 3),
3
+ // each with its own slice of the work. Falls back to the first agent.
4
+ import { Agent } from '@mastra/core/agent';
5
+ import { z } from 'zod';
6
+ import { providerModel } from './models.js';
7
+ export const RoutingPlanSchema = z.object({
8
+ slices: z
9
+ .array(z.object({
10
+ agent: z.string(),
11
+ /** What this agent delivers, and only that. */
12
+ instructions: z.string(),
13
+ }))
14
+ .min(1)
15
+ .max(3),
16
+ });
17
+ const RULES = `You are the routing planner of a multi-agent system.
18
+ Pick which agent(s) handle the user's LAST message, using the earlier turns as context.
19
+ Rules:
20
+ - Only use agents from the list below.
21
+ - Prefer one agent. Use several only for clearly distinct deliverables, at most 3.
22
+ - Each slice owns exactly one deliverable; its instructions name only that deliverable, never the whole request.
23
+ - Repeat shared constraints (dates, names, audience) in every slice that needs them.
24
+ Reply with JSON only: {"slices":[{"agent":"<agent id>","instructions":"<what this agent delivers>"}]}`;
25
+ /** The planner agent; `candidates` is set per request in its request context. */
26
+ export function plannerAgent(model, rules = RULES) {
27
+ return new Agent({
28
+ id: 'planner',
29
+ name: 'Routing planner',
30
+ description: 'Assigns a request to the agents that should handle it.',
31
+ instructions: ({ requestContext }) => `${rules}\n\nAgents (JSON):\n${requestContext.get('candidates') ?? '[]'}`,
32
+ model: ({ requestContext }) => (model ?? providerModel)(requestContext),
33
+ });
34
+ }
35
+ export const candidatesJson = (specs) => JSON.stringify(specs.map((s) => ({ id: s.id, name: s.name, description: s.description })));
36
+ /** Keep a model-made plan to known agents; null when nothing usable is left. */
37
+ export function sanitizePlan(plan, ids, max = 3) {
38
+ const slices = (plan?.slices ?? []).filter((s) => s && ids.has(s.agent)).slice(0, Math.max(1, Math.min(max, 3)));
39
+ return slices.length ? { slices } : null;
40
+ }
41
+ export const fallbackPlan = (id, instructions) => ({ slices: [{ agent: id, instructions }] });
42
+ /** The last `n` user turns, each with the replies that followed it. */
43
+ export function recentTurns(messages, n = 3) {
44
+ const users = messages.flatMap((m, i) => (m.role === 'user' ? [i] : []));
45
+ return users.length <= n ? messages : messages.slice(users[users.length - n]);
46
+ }
47
+ export function textOf(content) {
48
+ if (typeof content === 'string')
49
+ return content;
50
+ if (Array.isArray(content))
51
+ return content.map((p) => (p && typeof p === 'object' && 'text' in p ? String(p.text) : '')).join('\n');
52
+ return '';
53
+ }
54
+ export function lastUserText(messages) {
55
+ for (let i = messages.length - 1; i >= 0; i--)
56
+ if (messages[i].role === 'user')
57
+ return textOf(messages[i].content);
58
+ return '';
59
+ }
60
+ /** One reply from several agents: their outputs under their names. */
61
+ export const mergeReplies = (parts) => parts.length === 1 ? parts[0].text.trim() : parts.map((p) => `**${p.name}**\n\n${p.text.trim()}`).join('\n\n');
62
+ //# sourceMappingURL=routing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing.js","sourceRoot":"","sources":["../src/routing.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,8EAA8E;AAC9E,sEAAsE;AACtE,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,aAAa,EAAc,MAAM,aAAa,CAAC;AAExD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,MAAM,EAAE,CAAC;SACP,KAAK,CACL,CAAC,CAAC,MAAM,CAAC;QACR,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AC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpI,OAAO,EAAE,CAAC;AACX,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,QAAuB;IACnD,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;QAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACnH,OAAO,EAAE,CAAC;AACX,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAAuC,EAAE,EAAE,CACvE,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { RequestContext } from '@mastra/core/request-context';
2
+ import type { AgentRegistry, AgentSpec } from './agents.js';
3
+ import { type Model, type ProviderConfig } from './models.js';
4
+ export declare const HEADERS: {
5
+ readonly baseURL: "x-provider-base-url";
6
+ readonly key: "x-provider-key";
7
+ readonly model: "x-provider-model";
8
+ readonly agents: "x-agents";
9
+ readonly session: "x-session-id";
10
+ };
11
+ export interface AgentServerOptions<T extends AgentSpec, E> {
12
+ agents: AgentRegistry<T>;
13
+ /** Shown as `owned_by` in /v1/models and in the health check. */
14
+ name?: string;
15
+ /** The bearer key callers must send; none (or empty) leaves the server open. */
16
+ apiKey?: (env: E) => string | undefined;
17
+ /** The provider when the request doesn't carry one (e.g. from env vars). */
18
+ provider?: (env: E) => ProviderConfig | undefined;
19
+ /** The model when there's no provider at all, e.g. `workersAI(env.AI, …)`: works with no keys. */
20
+ defaultModel?: (env: E) => Model;
21
+ /** "auto" routing; false turns it off. The planner uses the request's provider unless given a model. */
22
+ planner?: false | {
23
+ model?: (requestContext: RequestContext) => Model;
24
+ rules?: string;
25
+ };
26
+ /** Tool-call rounds per reply (default 5); a function to set it per environment. */
27
+ maxSteps?: number | ((env: E) => number);
28
+ /** Most agents "auto" may split a request across (default 3; 1 to never split). */
29
+ maxAgents?: number | ((env: E) => number);
30
+ }
31
+ export declare function createAgentServer<T extends AgentSpec, E = unknown>(options: AgentServerOptions<T, E>): {
32
+ fetch(request: Request, env: E): Promise<Response>;
33
+ };
34
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAA2B,KAAK,KAAK,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAGvF,eAAO,MAAM,OAAO;;;;;;CAMV,CAAC;AAEX,MAAM,WAAW,kBAAkB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC;IACzD,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC;IACzB,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gFAAgF;IAChF,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,MAAM,GAAG,SAAS,CAAC;IACxC,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,cAAc,GAAG,SAAS,CAAC;IAClD,kGAAkG;IAClG,YAAY,CAAC,EAAE,CAAC,GAAG,E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