Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add `konsistent` with initial config to enforce structural conventions (#558)

Felix Arntz2958abf7a6e3
diff --git a/.changeset/strong-trains-admire.md b/.changeset/strong-trains-admire.md
new file mode 100644
index 000000000..4e30758ae
--- /dev/null
+++ b/.changeset/strong-trains-admire.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+feat(eve): add `konsistent` with initial config to enforce structural conventions
diff --git a/konsistent.json b/konsistent.json
new file mode 100644
index 000000000..ac2e5ea6f
--- /dev/null
+++ b/konsistent.json
@@ -0,0 +1,321 @@
+{
+ "$schema": "node_modules/konsistent/konsistent.schema.json",
+ "version": "v1",
+ "kebabToPascalMap": {
+ "github": "GitHub",
+ "junit": "JUnit",
+ "instruction": "Instructions"
+ },
+ "kebabToCamelMap": {
+ "github": "github",
+ "junit": "junit",
+ "instruction": "instructions"
+ },
+ "conventions": [
+ {
+ "name": "package-directories",
+ "description": "Workspace package folders keep their package metadata, changelog, TypeScript configs, and source entrypoint.",
+ "paths": "packages/{packageName}",
+ "must": {
+ "haveType": "directory",
+ "haveFiles": ["package.json", "CHANGELOG.md", "tsconfig.json", "src/index.ts"]
+ }
+ },
+ {
+ "name": "public-definitions",
+ "description": "Public definition requirements.",
+ "paths": [
+ "packages/eve/src/public/{conceptName:matches(^[a-z]+$)}s/index.ts",
+ "!packages/eve/src/public/connections",
+ "!packages/eve/src/public/definitions"
+ ],
+ "must": [
+ {
+ "name": "public-barrels-must-reexport-their-concept-definition-function-and-type",
+ "description": "Public barrels re-export their concept's definition function and type.",
+ "must": {
+ "export": [
+ {
+ "name": "define${conceptName.toPascalCase()}",
+ "from": "#public/definitions/${conceptName.toCamelCase()}.js"
+ }
+ ],
+ "exportTypes": [
+ {
+ "name": "${conceptName.toPascalCase()}Definition",
+ "from": "#public/definitions/${conceptName.toCamelCase()}.js"
+ }
+ ],
+ "haveFiles": [
+ "../definitions/${conceptName.toCamelCase()}.ts",
+ "../../shared/${conceptName.toCamelCase()}-definition.ts"
+ ]
+ }
+ },
+ {
+ "name": "public-definitions-must-import-from-matching-shared-definitions",
+ "description": "Public definitions must import from their matching shared definitions.",
+ "for": {
+ "files": ["../definitions/${conceptName.toCamelCase()}.ts"]
+ },
+ "must": {
+ "importFrom": "#shared/${conceptName.toCamelCase()}-definition.js"
+ }
+ },
+ {
+ "name": "compiler-manifest-must-export-matching-compiled-definitions",
+ "description": "Compiler manifest must export matching compiled definitions.",
+ "for": {
+ "files": ["../../compiler/manifest.ts"]
+ },
+ "must": {
+ "exportTypes": ["Compiled${conceptName.toPascalCase()}Definition"]
+ }
+ },
+ {
+ "name": "discover-manifest-must-export-matching-source-ref-types",
+ "description": "Discover manifest must export matching source ref types.",
+ "for": {
+ "files": ["../../discover/manifest.ts"]
+ },
+ "must": {
+ "exportTypes": ["${conceptName.toPascalCase()}SourceRef"]
+ }
+ },
+ {
+ "name": "runtime-types-file-must-export-matching-resolved-definitions",
+ "description": "Runtime types file must export matching compiled definitions.",
+ "for": {
+ "files": ["../../runtime/types.ts"]
+ },
+ "must": {
+ "exportTypes": ["Resolved${conceptName.toPascalCase()}Definition"]
+ }
+ }
+ ]
+ },
+ {
+ "name": "public-channel-barrels",
+ "description": "Built-in public channel barrels re-export their channel factory and core channel types from the implementation module.",
+ "paths": "packages/eve/src/public/channels/{channelName}/index.ts",
+ "must": {
+ "export": [
+ {
+ "name": "${channelName.toCamelCase()}Channel",
+ "from": "#public/channels/${channelName}/${channelName.toCamelCase()}Channel.js"
+ }
+ ],
+ "exportTypes": [
+ {
+ "name": "${channelName.toPascalCase()}Channel",
+ "from": "#public/channels/${channelName}/${channelName.toCamelCase()}Channel.js"
+ },
+ {
+ "name": "${channelName.toPascalCase()}ChannelConfig",
+ "from": "#public/channels/${channelName}/${channelName.toCamelCase()}Channel.js"
+ },
+ {
+ "name": "${channelName.toPascalCase()}ReceiveTarget",
+ "from": "#public/channels/${channelName}/${channelName.toCamelCase()}Channel.js"
+ }
+ ]
+ }
+ },
+ {
+ "name": "public-sandbox-backends",
+ "description": "Public sandbox implementation barrels have matching backend implementation files.",
+ "paths": [
+ "packages/eve/src/public/sandbox/{sandboxName}.ts",
+ "!packages/eve/src/public/sandbox/index.ts",
+ "!packages/eve/src/public/sandbox/*-sandbox.ts"
+ ],
+ "must": [
+ {
+ "name": "public-sandbox-barrels-must-reexport-their-backend",
+ "description": "Public sandbox barrels re-export their backend factory and create options from matching implementation files.",
+ "must": {
+ "haveFiles": ["backends/${sandboxName}.ts", "${sandboxName}-sandbox.ts"],
+ "export": [
+ {
+ "name": "${sandboxName.toFlatCase()}",
+ "from": "#public/sandbox/backends/${sandboxName}.js"
+ }
+ ],
+ "exportTypes": [
+ {
+ "name": "${sandboxName.toPascalCase()}SandboxCreateOptions",
+ "from": "#public/sandbox/${sandboxName}-sandbox.js"
+ }
+ ]
+ }
+ },
+ {
+ "name": "public-sandbox-options-must-export-create-options",
+ "description": "Public sandbox option files export the matching create options type.",
+ "for": {
+ "files": ["${sandboxName}-sandbox.ts"]
+ },
+ "must": {
+ "exportTypes": ["${sandboxName.toPascalCase()}SandboxCreateOptions"]
+ }
+ },
+ {
+ "name": "public-sandbox-backends-must-export-their-factory",
+ "description": "Public sandbox backend implementation files export the matching backend factory using the public create options type.",
+ "for": {
+ "files": ["backends/${sandboxName}.ts"]
+ },
+ "must": {
+ "importTypes": [
+ {
+ "name": "${sandboxName.toPascalCase()}SandboxCreateOptions",
+ "from": "#public/sandbox/${sandboxName}-sandbox.js"
+ }
+ ],
+ "exportFunctions": [
+ {
+ "name": "${sandboxName.toFlatCase()}",
+ "receiveParamsOfTypes": ["${sandboxName.toPascalCase()}SandboxCreateOptions"]
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "name": "eval-loaders",
+ "description": "Eval loaders must export their required symbols.",
+ "paths": [
+ "packages/eve/src/evals/loaders/{loaderName}.ts",
+ "!packages/eve/src/evals/loaders/index.ts"
+ ],
+ "must": {
+ "exportFunctions": [
+ {
+ "name": "load${loaderName.toPascalCase()}",
+ "receiveParamsOfTypes": ["string"]
+ }
+ ]
+ }
+ },
+ {
+ "name": "eval-reporters",
+ "description": "Eval reporters must export their required symbols.",
+ "paths": [
+ "packages/eve/src/evals/runner/reporters/{reporterName}.ts",
+ "!packages/eve/src/evals/runner/reporters/types.ts"
+ ],
+ "must": [
+ {
+ "must": {
+ "importTypes": [
+ {
+ "name": "EvalReporter",
+ "from": "#evals/runner/reporters/types.js"
+ }
+ ],
+ "declareClasses": [
+ {
+ "name": "${reporterName.toPascalCase()}Reporter",
+ "implement": ["EvalReporter"]
+ }
+ ],
+ "exportTypes": ["${reporterName.toPascalCase()}ReporterConfig"],
+ "exportFunctions": [
+ {
+ "name": "${reporterName.toPascalCase()}",
+ "receiveParamsOfTypes": ["${reporterName.toPascalCase()}ReporterConfig"],
+ "returnValueOfType": "EvalReporter"
+ }
+ ]
+ }
+ },
+ {
+ "for": {
+ "files": ["../../reporters/index.ts"]
+ },
+ "must": {
+ "export": [
+ {
+ "name": "${reporterName.toPascalCase()}",
+ "from": "#evals/runner/reporters/${reporterName}.js"
+ }
+ ],
+ "exportTypes": [
+ {
+ "name": "${reporterName.toPascalCase()}ReporterConfig",
+ "from": "#evals/runner/reporters/${reporterName}.js"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "name": "agent-app-directories",
+ "description": "Workspace agent apps keep their authored agent entry and instructions in agent/.",
+ "paths": [
+ "apps/frameworks/{appName}",
+ "!apps/frameworks/README.md",
+ "apps/fixtures/{appName}",
+ "!apps/fixtures/README.md",
+ "apps/templates/{appName}",
+ "!apps/templates/README.md"
+ ],
+ "must": {
+ "haveType": "directory",
+ "haveFiles": ["package.json", "tsconfig.json", "agent/agent.ts", "agent/instructions.md"]
+ }
+ },
+ {
+ "name": "e2e-fixture-directories",
+ "description": "Fixture-owned e2e apps share the same package, agent, and eval entry points.",
+ "paths": "e2e/fixtures/{fixtureName}",
+ "must": [
+ {
+ "must": {
+ "haveType": "directory",
+ "haveFiles": [
+ "package.json",
+ "tsconfig.json",
+ ".vercelignore",
+ "agent/agent.ts",
+ "agent/instructions.md",
+ "evals/evals.config.ts"
+ ]
+ }
+ },
+ {
+ "name": "e2e-eval-config-imports",
+ "description": "E2E eval config files use the public eve/evals config helper.",
+ "for": {
+ "files": "evals/evals.config.ts"
+ },
+ "must": {
+ "import": [
+ {
+ "name": "defineEvalConfig",
+ "from": "eve/evals"
+ }
+ ]
+ }
+ },
+ {
+ "name": "e2e-eval-imports",
+ "description": "E2E eval files use the public eve/evals authoring helper.",
+ "for": {
+ "files": "evals/**/*.eval.ts"
+ },
+ "must": {
+ "import": [
+ {
+ "name": "defineEval",
+ "from": "eve/evals"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/package.json b/package.json
index f6efab928..3e73970ea 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"fmt": "oxfmt",
"guard:fixtures": "node ./scripts/guard-test-fixtures.mjs",
"guard:invariants": "node ./scripts/guard-invariants.mjs",
+ "konsistent": "konsistent",
"lint": "oxlint --fix",
"prepare": "simple-git-hooks",
"test": "pnpm test:unit && pnpm test:integration",
@@ -37,6 +38,7 @@
"@types/node": "catalog:",
"ai": "catalog:",
"gray-matter": "4.0.3",
+ "konsistent": "1.0.0-beta.1",
"oxfmt": "0.55.0",
"oxlint": "1.70.0",
"simple-git-hooks": "2.13.1",
diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.ts
index ed0335480..1e888ad83 100644
--- a/packages/eve/src/channel/adapter.ts
+++ b/packages/eve/src/channel/adapter.ts
@@ -4,6 +4,7 @@ import { createLogger } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { SessionHandle } from "#channel/session.js";
import type { DeliverPayload } from "#channel/types.js";
+import type { FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";
const log = createLogger("channel.adapter");
@@ -94,11 +95,7 @@ export type ChannelEventHandlers<TCtx extends ChannelAdapterContext<any> = Chann
* When fields are provided, staging prefers them over the values the
* channel populated at ingestion time.
*/
-export interface FetchFileResult {
- readonly bytes: Buffer;
- readonly mediaType?: string;
- readonly filename?: string;
-}
+export type { FetchFileResult };
export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown>>;
@@ -160,7 +157,7 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
* Credentials should be captured in the closure at channel
* construction time.
*/
- readonly fetchFile?: (url: string) => Promise<Buffer | FetchFileResult | null>;
+ readonly fetchFile?: FetchFileFunction;
/**
* Framework-owned observability projection for the active channel.
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 344c88ad7..d6cb12d15 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -10,6 +10,7 @@ import {
} from "#compiler/remote-agent-node.js";
import type { ChannelRouteMethod } from "#public/definitions/channel.js";
import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
+import type { InternalInstructionsDefinition } from "#shared/instructions-definition.js";
import { jsonObjectSchema } from "#shared/json-schemas.js";
import type { Node } from "#shared/node.js";
import type {
@@ -124,7 +125,8 @@ export type CompiledAgentDefinition = Omit<InternalAgentDefinition, "model" | "c
* Normalized authored instructions prompt preserved in the compiled
* manifest.
*/
-export type CompiledInstructions = z.infer<typeof compiledInstructionsSchema>;
+export type CompiledInstructionsDefinition = InternalInstructionsDefinition &
+ (Omit<MarkdownSourceRef<undefined>, "definition"> | Omit<ModuleSourceRef, "exportName">);
/**
* Normalized authored skill preserved in the compiled manifest.
@@ -390,7 +392,7 @@ const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = z
})
.strict();
-const compiledInstructionsSchema = z
+const compiledInstructionsSchema: z.ZodType<CompiledInstructionsDefinition> = z
.object({
name: z.string(),
logicalPath: z.string(),
@@ -687,7 +689,7 @@ export function createCompiledAgentNodeManifest(input: {
readonly sandboxWorkspaces?: readonly CompiledSandboxWorkspace[];
readonly schedules?: readonly CompiledScheduleDefinition[];
readonly skills?: readonly CompiledSkillDefinition[];
- readonly instructions?: CompiledInstructions;
+ readonly instructions?: CompiledInstructionsDefinition;
readonly tools?: readonly CompiledToolDefinition[];
readonly workspaceResourceRoot?: CompiledWorkspaceResourceRoot;
}): CompiledAgentNodeManifest {
@@ -834,7 +836,7 @@ export function createCompiledAgentManifest(input: {
readonly skills?: readonly CompiledSkillDefinition[];
readonly subagentEdges?: readonly CompiledSubagentEdge[];
readonly subagents?: readonly CompiledSubagentNode[];
- readonly instructions?: CompiledInstructions;
+ readonly instructions?: CompiledInstructionsDefinition;
readonly tools?: readonly CompiledToolDefinition[];
}): CompiledAgentManifest {
return {
diff --git a/packages/eve/src/compiler/normalize-hook.ts b/packages/eve/src/compiler/normalize-hook.ts
index 05f0ff82c..2bb31262c 100644
--- a/packages/eve/src/compiler/normalize-hook.ts
+++ b/packages/eve/src/compiler/normalize-hook.ts
@@ -1,5 +1,5 @@
import { stripLogicalPathExtension } from "../discover/filesystem.js";
-import type { ModuleSourceRef } from "../shared/source-ref.js";
+import type { HookSourceRef } from "#discover/manifest.js";
import type { CompiledHookDefinition } from "./manifest.js";
/**
@@ -11,7 +11,7 @@ import type { CompiledHookDefinition } from "./manifest.js";
* path-relative slug used for diagnostics and ordering. Per-handler
* validation lives in the runtime resolver.
*/
-export function compileHookEntry(source: ModuleSourceRef): CompiledHookDefinition {
+export function compileHookEntry(source: HookSourceRef): CompiledHookDefinition {
return {
exportName: source.exportName,
logicalPath: source.logicalPath,
diff --git a/packages/eve/src/compiler/normalize-instructions.ts b/packages/eve/src/compiler/normalize-instructions.ts
index 67442fd81..989d0f6ee 100644
--- a/packages/eve/src/compiler/normalize-instructions.ts
+++ b/packages/eve/src/compiler/normalize-instructions.ts
@@ -3,7 +3,7 @@ import type { InstructionsSourceRef } from "#discover/manifest.js";
import { normalizeInstructionsDefinition } from "#internal/authored-definition/core.js";
import type {
CompiledDynamicInstructionsDefinition,
- CompiledInstructions,
+ CompiledInstructionsDefinition,
} from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
@@ -19,7 +19,7 @@ import { isDynamicSentinel, type DynamicToolEventName } from "#shared/dynamic-to
* produces model messages at runtime.
*/
export type CompiledInstructionsEntry =
- | { readonly kind: "instructions"; readonly definition: CompiledInstructions }
+ | { readonly kind: "instructions"; readonly definition: CompiledInstructionsDefinition }
| {
readonly kind: "dynamic-instructions";
readonly definition: CompiledDynamicInstructionsDefinition;
@@ -107,7 +107,7 @@ export async function compileInstructions(
agentRoot: string,
source: InstructionsSourceRef,
options: ModuleBackedDefinitionLoadOptions = {},
-): Promise<CompiledInstructions> {
+): Promise<CompiledInstructionsDefinition> {
const entry = await compileInstructionsEntry(agentRoot, source, options);
if (entry.kind === "dynamic-instructions") {
throw new Error(
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 6656fddee..324cde819 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -5,7 +5,7 @@ import {
type CompiledDynamicInstructionsDefinition,
type CompiledDynamicSkillDefinition,
type CompiledDynamicToolDefinition,
- type CompiledInstructions,
+ type CompiledInstructionsDefinition,
type CompiledSkillDefinition,
type CompiledToolDefinition,
createCompiledAgentManifest,
@@ -134,7 +134,7 @@ async function compileAgentNodeManifest(
compileInstructionsEntry(manifest.agentRoot, source, { externalDependencies }),
),
);
- const staticInstructions: CompiledInstructions[] = [];
+ const staticInstructions: CompiledInstructionsDefinition[] = [];
const dynamicInstructions: CompiledDynamicInstructionsDefinition[] = [];
for (const entry of compiledInstructionsEntries) {
@@ -145,7 +145,7 @@ async function compileAgentNodeManifest(
}
}
- const composedInstructions: CompiledInstructions | undefined =
+ const composedInstructions: CompiledInstructionsDefinition | undefined =
staticInstructions.length === 0
? undefined
: staticInstructions.length === 1
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index 221e34961..bdc09dc6f 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -1,6 +1,6 @@
import { stripLogicalPathExtension } from "#discover/filesystem.js";
import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";
-import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type { ToolSourceRef } from "#discover/manifest.js";
import type { CompiledToolDefinition, CompiledDynamicToolDefinition } from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
@@ -34,7 +34,7 @@ export type CompiledToolEntry =
*/
export async function compileToolEntry(
agentRoot: string,
- source: ModuleSourceRef,
+ source: ToolSourceRef,
options: ModuleBackedDefinitionLoadOptions = {},
): Promise<CompiledToolEntry> {
const entry = normalizeToolDefinition(
diff --git a/packages/eve/src/discover/manifest.ts b/packages/eve/src/discover/manifest.ts
index a4ce2d97b..9dd553113 100644
--- a/packages/eve/src/discover/manifest.ts
+++ b/packages/eve/src/discover/manifest.ts
@@ -42,6 +42,11 @@ export interface ConnectionSourceRef extends ModuleSourceRef {
readonly connectionName: string;
}
+/**
+ * Hook source reference preserved by the discovery manifest.
+ */
+export type HookSourceRef = ModuleSourceRef;
+
/**
* Instructions source reference preserved by discovery for compiler
* normalization.
@@ -56,6 +61,11 @@ export type SkillSourceRef =
| ModuleSourceRef
| (NamedSkillDefinition & SkillPackageSourceRef);
+/**
+ * Tool source reference preserved by the discovery manifest.
+ */
+export type ToolSourceRef = ModuleSourceRef;
+
/**
* Recursive manifest entry for a local subagent package.
*/
diff --git a/packages/eve/src/evals/cli/eval.ts b/packages/eve/src/evals/cli/eval.ts
index d2e4a9941..f8ae00869 100644
--- a/packages/eve/src/evals/cli/eval.ts
+++ b/packages/eve/src/evals/cli/eval.ts
@@ -12,7 +12,7 @@ import {
findMisplacedEvalDirs,
} from "#evals/runner/discover.js";
import { runEvals } from "#evals/runner/run-evals.js";
-import { ConsoleReporter } from "#evals/runner/reporters/console.js";
+import { Console } from "#evals/runner/reporters/console.js";
import { JUnit } from "#evals/runner/reporters/junit.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
import { resolveEvalTargetHandle } from "#evals/target.js";
@@ -131,7 +131,7 @@ export async function runEvalCommand(
});
}
- const reporters: EvalReporter[] = options.json === true ? [] : [new ConsoleReporter()];
+ const reporters: EvalReporter[] = options.json === true ? [] : [Console()];
if (options.junit !== undefined) {
reporters.push(JUnit({ filePath: options.junit }));
}
diff --git a/packages/eve/src/evals/reporters/index.ts b/packages/eve/src/evals/reporters/index.ts
index 26cb3b33b..32e914711 100644
--- a/packages/eve/src/evals/reporters/index.ts
+++ b/packages/eve/src/evals/reporters/index.ts
@@ -1,3 +1,4 @@
export { Braintrust, type BraintrustReporterConfig } from "#evals/runner/reporters/braintrust.js";
+export { Console, type ConsoleReporterConfig } from "#evals/runner/reporters/console.js";
export { JUnit, type JUnitReporterConfig } from "#evals/runner/reporters/junit.js";
export type { EvalReporter } from "#evals/runner/reporters/types.js";
diff --git a/packages/eve/src/evals/runner/reporters/console.test.ts b/packages/eve/src/evals/runner/reporters/console.test.ts
index c4b5e2572..1528800d7 100644
--- a/packages/eve/src/evals/runner/reporters/console.test.ts
+++ b/packages/eve/src/evals/runner/reporters/console.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, it } from "vitest";
import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
-import { ConsoleReporter } from "#evals/runner/reporters/console.js";
+import { Console } from "#evals/runner/reporters/console.js";
import type { EveEvalResult, EveEvalRunSummary } from "#evals/types.js";
-describe("ConsoleReporter", () => {
+describe("Console", () => {
it("reports skipped evals and their reason", () => {
const lines: string[] = [];
- const reporter = new ConsoleReporter({ color: false, log: (line) => lines.push(line) });
+ const reporter = Console({ color: false, log: (line) => lines.push(line) });
const result = skippedResult();
reporter.onEvalComplete(result);
diff --git a/packages/eve/src/evals/runner/reporters/console.ts b/packages/eve/src/evals/runner/reporters/console.ts
index cccbf873f..dd740e43d 100644
--- a/packages/eve/src/evals/runner/reporters/console.ts
+++ b/packages/eve/src/evals/runner/reporters/console.ts
@@ -9,16 +9,33 @@ import type {
} from "#evals/types.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
+/**
+ * Configuration for the console reporter. Every field is optional.
+ */
+export interface ConsoleReporterConfig {
+ /** Function to print console log messages. */
+ log?: (message: string) => void;
+ /** Whether to log with colored output. */
+ color?: boolean;
+}
+
+/**
+ * Creates a {@link ConsoleReporter}.
+ */
+export function Console(config: ConsoleReporterConfig = {}): EvalReporter {
+ return new ConsoleReporter(config);
+}
+
/**
* Console reporter that prints eval progress and results to stdout.
*/
-export class ConsoleReporter implements EvalReporter {
+class ConsoleReporter implements EvalReporter {
readonly #log: (message: string) => void;
readonly #colors: ReturnType<typeof picocolors.createColors>;
- constructor(options?: { log?: (message: string) => void; color?: boolean }) {
- this.#log = options?.log ?? console.log;
- this.#colors = picocolors.createColors(options?.color ?? Boolean(process.stdout.isTTY));
+ constructor(config?: ConsoleReporterConfig) {
+ this.#log = config?.log ?? console.log;
+ this.#colors = picocolors.createColors(config?.color ?? Boolean(process.stdout.isTTY));
}
onRunStart(evaluations: readonly EveEval[], target: EveEvalTarget): void {
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
index 3419d3f2d..dc11046a2 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
@@ -1,4 +1,4 @@
-import type { MicrosandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
+import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
export const MICROSANDBOX_DEFAULT_IMAGE = "ghcr.io/vercel/eve:latest";
@@ -29,7 +29,7 @@ export interface ResolvedMicrosandboxOptions {
* Applies defaults to `microsandbox(opts)`.
*/
export function resolveMicrosandboxOptions(
- options: MicrosandboxCreateOptions | undefined,
+ options: MicrosandboxSandboxCreateOptions | undefined,
): ResolvedMicrosandboxOptions {
return {
cpus: options?.cpus ?? MICROSANDBOX_DEFAULT_CPUS,
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
index a0f1df9e8..6b6cf54d1 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
@@ -17,7 +17,7 @@ import type {
} from "#public/definitions/sandbox-backend.js";
import type {
MicrosandboxBootstrapUseOptions,
- MicrosandboxCreateOptions,
+ MicrosandboxSandboxCreateOptions,
MicrosandboxSessionUseOptions,
} from "#public/sandbox/microsandbox-sandbox.js";
@@ -35,7 +35,7 @@ export const MICROSANDBOX_BACKEND_NAME = "microsandbox";
* under `eve/sandbox`.
*/
export interface CreateMicrosandboxSandboxBackendInput {
- readonly createOptions?: MicrosandboxCreateOptions;
+ readonly createOptions?: MicrosandboxSandboxCreateOptions;
}
/**
diff --git a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
index f1a32b0c0..94bfdb348 100644
--- a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
+++ b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
@@ -6,7 +6,7 @@ import type {
CompiledChannelDefinition,
CompiledChannelEntry,
CompiledConnectionDefinition,
- CompiledInstructions,
+ CompiledInstructionsDefinition,
CompiledScheduleDefinition,
CompiledSkillDefinition,
CompiledSubagentNode,
@@ -113,7 +113,9 @@ function isActiveChannel(entry: CompiledChannelEntry): entry is CompiledChannelD
return entry.kind === "channel";
}
-function toInstructionsEntry(instructions: CompiledInstructions): VercelEveInstructionsEntry {
+function toInstructionsEntry(
+ instructions: CompiledInstructionsDefinition,
+): VercelEveInstructionsEntry {
return {
logicalPath: instructions.logicalPath,
sourceKind: instructions.sourceKind,
diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.ts
index 238694636..835ecb42f 100644
--- a/packages/eve/src/internal/nitro/host/types.ts
+++ b/packages/eve/src/internal/nitro/host/types.ts
@@ -1,6 +1,6 @@
import type { CompileAgentResult } from "#compiler/compile-agent.js";
import type { ScheduleRegistration } from "#runtime/schedules/register.js";
-import type { ResolvedSchedule } from "#runtime/types.js";
+import type { ResolvedScheduleDefinition } from "#runtime/types.js";
import type { GeneratedCompiledArtifactsFiles } from "#internal/application/compiled-artifacts.js";
import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
@@ -62,6 +62,6 @@ export interface PreparedApplicationHost {
compileResult: CompileAgentResult;
compiledArtifacts: GeneratedCompiledArtifactsFiles;
scheduleRegistrations: readonly ScheduleRegistration[];
- schedules: readonly ResolvedSchedule[];
+ schedules: readonly ResolvedScheduleDefinition[];
workflowBuildDir: string;
}
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index 6ffd5f2b9..f0fcf6d39 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -11,7 +11,7 @@ import type {
AgentInfoData,
CompiledSubagentNode,
ResolvedSandboxDefinition,
- ResolvedSchedule,
+ ResolvedScheduleDefinition,
ResolvedSkillDefinition,
} from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
import type {
@@ -456,7 +456,7 @@ function renderSkill(skill: ResolvedSkillDefinition): AgentInfoSkillEntry {
};
}
-export function renderSchedule(schedule: ResolvedSchedule): AgentInfoScheduleEntry {
+export function renderSchedule(schedule: ResolvedScheduleDefinition): AgentInfoScheduleEntry {
return {
...toSource(schedule),
cron: schedule.cron,
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts b/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
index 4f92aaa19..d3a46aa62 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
@@ -13,9 +13,9 @@ import { resolveSchedules } from "#runtime/schedules/resolve-schedule.js";
import type {
ResolvedAgent,
ResolvedSandboxDefinition,
- ResolvedSchedule,
+ ResolvedScheduleDefinition,
ResolvedSkillDefinition,
- ResolvedInstructions,
+ ResolvedInstructionsDefinition,
} from "#runtime/types.js";
/**
@@ -25,12 +25,12 @@ import type {
export interface AgentInfoData {
readonly agent: ResolvedAgent;
readonly manifest: CompiledAgentManifest;
- readonly schedules: readonly ResolvedSchedule[];
+ readonly schedules: readonly ResolvedScheduleDefinition[];
}
export interface AgentInfoManifestData {
readonly manifest: CompiledAgentManifest;
- readonly schedules: readonly ResolvedSchedule[];
+ readonly schedules: readonly ResolvedScheduleDefinition[];
}
/**
@@ -120,7 +120,7 @@ export type {
CompiledAgentManifest,
CompiledSubagentNode,
ResolvedSandboxDefinition,
- ResolvedSchedule,
+ ResolvedScheduleDefinition,
ResolvedSkillDefinition,
- ResolvedInstructions,
+ ResolvedInstructionsDefinition,
};
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 0fe3dd94d..175f5ebb9 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -13,7 +13,7 @@ import {
messageToUserContent,
type ChatSdkChannelState,
} from "#public/channels/chat-sdk/index.js";
-import type { RouteHandlerArgs, SendFn } from "#public/definitions/defineChannel.js";
+import type { RouteHandlerArgs, SendFn } from "#public/definitions/channel.js";
import type {
Adapter,
AdapterPostableMessage,
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index 274ea200c..2a2d4c07a 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -32,7 +32,7 @@ import {
type SendFn,
type SendOptions,
type Session,
-} from "#public/definitions/defineChannel.js";
+} from "#public/definitions/channel.js";
const log = createLogger("chat-sdk.channel");
const DEFAULT_ROUTE = "/eve/v1";
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index 3c4ccf632..e4c5925fc 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -2,7 +2,7 @@ import type { DiscordInstrumentationMetadata } from "#public/channels/discord/in
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -47,12 +47,7 @@ import {
import { type DiscordWebhookVerifier } from "#public/channels/discord/verify.js";
import { verifyDiscordInbound } from "#public/channels/discord/verifyInbound.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
-import {
- defineChannel,
- POST,
- type Channel,
- type SendFn,
-} from "#public/definitions/defineChannel.js";
+import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";
const log = createLogger("discord.channel");
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index df7c0cef2..30c74d247 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -31,7 +31,7 @@ import {
type ChannelCors,
type ChannelEvents,
type ChannelSessionOps,
-} from "#public/definitions/defineChannel.js";
+} from "#public/definitions/channel.js";
import type { ChannelMethod } from "#public/definitions/channel.js";
import type { RunMode } from "#shared/run-mode.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
diff --git a/packages/eve/src/public/channels/github/dispatch.ts b/packages/eve/src/public/channels/github/dispatch.ts
index f24eda091..a7f36a9b0 100644
--- a/packages/eve/src/public/channels/github/dispatch.ts
+++ b/packages/eve/src/public/channels/github/dispatch.ts
@@ -39,7 +39,7 @@ import type {
GitHubInboundResult,
GitHubInboundResultOrPromise,
} from "#public/channels/github/githubChannel.js";
-import type { SendFn } from "#public/definitions/defineChannel.js";
+import type { SendFn } from "#public/definitions/channel.js";
const log = createLogger("github.dispatch");
diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.ts
index 223bd8d7c..436554cb8 100644
--- a/packages/eve/src/public/channels/github/githubChannel.ts
+++ b/packages/eve/src/public/channels/github/githubChannel.ts
@@ -1,7 +1,7 @@
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { createLogger } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -46,7 +46,7 @@ import {
} from "#public/channels/github/state.js";
import type { GitHubPullRequestContextConfig } from "#public/channels/github/pr-context.js";
import { verifyGitHubRequest } from "#public/channels/github/verify.js";
-import { defineChannel, POST, type Channel } from "#public/definitions/defineChannel.js";
+import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
const log = createLogger("github.channel");
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index 06c036ea1..b83b3be0c 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -29,14 +29,14 @@ export {
type WebSocketRouteHooks,
type WebSocketUpgradeRequest,
type WebSocketUpgradeResult,
-} from "#public/definitions/defineChannel.js";
+} from "#public/definitions/channel.js";
export {
createWebSocketUpgradeServer,
type WebSocketUpgradeServerBridge,
} from "#channel/websocket-upgrade-server.js";
import { getChannelInstrumentationKind } from "#channel/compiled-channel.js";
-import type { Channel } from "#public/definitions/defineChannel.js";
+import type { Channel } from "#public/definitions/channel.js";
// ---------------------------------------------------------------------------
// Channel metadata maps and isChannel narrowing
diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.ts
index f4bd38be1..32b5bb278 100644
--- a/packages/eve/src/public/channels/linear/linearChannel.ts
+++ b/packages/eve/src/public/channels/linear/linearChannel.ts
@@ -33,7 +33,7 @@ import {
type Channel,
type ChannelSessionOps,
type SendFn,
-} from "#public/definitions/defineChannel.js";
+} from "#public/definitions/channel.js";
import { isObject } from "#shared/guards.js";
import type { JsonObject } from "#shared/json.js";
import type { InputResponse } from "#runtime/input/types.js";
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index c0012f06e..5d41f3ff8 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -49,7 +49,7 @@ import type {
SlackInteractionAction,
SlackInteractionUser,
} from "#public/channels/slack/slackChannel.js";
-import type { SendFn } from "#public/definitions/defineChannel.js";
+import type { SendFn } from "#public/definitions/channel.js";
const log = createLogger("slack.interactions");
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index ac1b56c18..a391f06b4 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -4,7 +4,7 @@ import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { CardElement } from "#compiled/chat/index.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -48,12 +48,7 @@ import {
type UploadPolicyInput,
} from "#public/channels/upload-policy.js";
import { verifySlackRequest, type SlackWebhookVerifier } from "#public/channels/slack/verify.js";
-import {
- defineChannel,
- POST,
- type Channel,
- type SendFn,
-} from "#public/definitions/defineChannel.js";
+import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";
import { markEventHandled } from "./utils.js";
const log = createLogger("slack.channel");
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.ts
index 16d61b5f4..1be203e76 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts
@@ -2,7 +2,7 @@ import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -52,12 +52,7 @@ import {
} from "#public/channels/teams/inbound.js";
import { verifyTeamsRequest, type TeamsWebhookVerifier } from "#public/channels/teams/verify.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
-import {
- defineChannel,
- POST,
- type Channel,
- type SendFn,
-} from "#public/definitions/defineChannel.js";
+import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";
const log = createLogger("teams.channel");
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.ts
index fcc3c1e07..046a21c2a 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts
@@ -3,7 +3,7 @@ import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapt
import type { SessionHandle } from "#channel/session.js";
import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { isCompiledChannel } from "#channel/compiled-channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -52,12 +52,7 @@ import {
type TelegramWebhookSecretToken,
type TelegramWebhookVerifier,
} from "#public/channels/telegram/verify.js";
-import {
- defineChannel,
- POST,
- type Channel,
- type SendFn,
-} from "#public/definitions/defineChannel.js";
+import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
const log = createLogger("telegram.channel");
diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.ts
index ff9ae8644..ee8412e88 100644
--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts
+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts
@@ -2,7 +2,7 @@ import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { RouteHandler } from "#channel/routes.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
+import type { ChannelSessionOps } from "#public/definitions/channel.js";
import { createLogger } from "#internal/logging.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -48,7 +48,7 @@ import {
POST,
type Channel,
type SendFn,
-} from "#public/definitions/defineChannel.js";
+} from "#public/definitions/channel.js";
const log = createLogger("twilio.channel");
diff --git a/packages/eve/src/public/definitions/defineChannel.test.ts b/packages/eve/src/public/definitions/channel.test.ts
similarity index 99%
rename from packages/eve/src/public/definitions/defineChannel.test.ts
rename to packages/eve/src/public/definitions/channel.test.ts
index 8cd3bcd0f..0c617b6b4 100644
--- a/packages/eve/src/public/definitions/defineChannel.test.ts
+++ b/packages/eve/src/public/definitions/channel.test.ts
@@ -12,12 +12,7 @@ import type {
twilioChannel,
TwilioInstrumentationMetadata,
} from "#public/channels/twilio/index.js";
-import {
- POST,
- WS,
- defineChannel,
- type InferChannelMetadata,
-} from "#public/definitions/defineChannel.js";
+import { POST, WS, defineChannel, type InferChannelMetadata } from "#public/definitions/channel.js";
type IsEqual<TLeft, TRight> =
(<T>() => T extends TLeft ? 1 : 2) extends <T>() => T extends TRight ? 1 : 2
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 6501dfa5e..298c5a944 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -1,7 +1,45 @@
-import type { DeliverInput, GetEventStreamOptions, RunHandle, RunInput } from "#channel/types.js";
+import type { ChannelAdapter, ChannelInstrumentationMetadata } from "#channel/adapter.js";
+import { defaultDeliverResult } from "#channel/adapter.js";
+import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";
+import { normalizeChannelCors, type ChannelCorsOptions } from "#channel/cors.js";
+import { HTTP_ADAPTER_KIND } from "#channel/http.js";
+import type { TypedReceiveTarget } from "#channel/receive-target.js";
+import type { RouteDefinition, SendFn } from "#channel/routes.js";
+import type { Session, SessionHandle } from "#channel/session.js";
+import type {
+ DeliverInput,
+ DeliverPayload,
+ GetEventStreamOptions,
+ RunHandle,
+ RunInput,
+} from "#channel/types.js";
+import { buildCallbackContext } from "#context/build-callback-context.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { GenericChannelDefinition, GenericReceiveInput } from "#shared/channel-definition.js";
+
+declare const CHANNEL_METADATA_TYPE: unique symbol;
export type { GetEventStreamOptions } from "#channel/types.js";
+export type { Session, SessionHandle } from "#channel/session.js";
+export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
+export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
+export type {
+ HttpRouteDefinition,
+ RouteDefinition,
+ RouteHandlerArgs,
+ SendFn,
+ SendOptions,
+ SendPayload,
+ GetSessionFn,
+ WebSocketMessage,
+ WebSocketPeer,
+ WebSocketRouteDefinition,
+ WebSocketRouteHandler,
+ WebSocketRouteHooks,
+ WebSocketUpgradeRequest,
+ WebSocketUpgradeResult,
+} from "#channel/routes.js";
/**
* HTTP method a route handles. Defaults to `"POST"` — almost every route
@@ -144,3 +182,235 @@ export function isDisabledRouteSentinel(value: unknown): value is DisabledRouteS
(value as { kind?: unknown }).kind === DISABLED_ROUTE_SENTINEL_KIND
);
}
+
+type EventData<T extends HandleMessageStreamEvent["type"]> =
+ Extract<HandleMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;
+
+/**
+ * Session operations on the `channel` argument of every channel event handler.
+ */
+export interface ChannelSessionOps {
+ readonly continuationToken: string;
+ setContinuationToken(token: string): void;
+}
+
+/**
+ * Channel context passed to event handlers: `TCtx` intersected with
+ * {@link ChannelSessionOps}.
+ */
+export type ChannelContext<TCtx> = TCtx & ChannelSessionOps;
+
+type ChannelEventHandler<T extends HandleMessageStreamEvent["type"], TCtx> = (
+ data: EventData<T>,
+ channel: ChannelContext<TCtx>,
+ ctx: SessionContext,
+) => void | Promise<void>;
+
+type ChannelSessionFailedHandler<TCtx> = (
+ data: EventData<"session.failed">,
+ channel: ChannelContext<TCtx>,
+) => void | Promise<void>;
+
+/**
+ * Optional handlers keyed by session lifecycle event name. Each handler receives
+ * the event `data`, the {@link ChannelContext}, and a {@link SessionContext}
+ * `ctx`. The `session.failed` handler is the exception: it receives only `data`
+ * and the channel context, with no `ctx`.
+ */
+export interface ChannelEvents<TCtx = void> {
+ readonly "turn.started"?: ChannelEventHandler<"turn.started", TCtx>;
+ readonly "actions.requested"?: ChannelEventHandler<"actions.requested", TCtx>;
+ readonly "action.result"?: ChannelEventHandler<"action.result", TCtx>;
+ readonly "message.completed"?: ChannelEventHandler<"message.completed", TCtx>;
+ readonly "message.appended"?: ChannelEventHandler<"message.appended", TCtx>;
+ readonly "reasoning.appended"?: ChannelEventHandler<"reasoning.appended", TCtx>;
+ readonly "reasoning.completed"?: ChannelEventHandler<"reasoning.completed", TCtx>;
+ readonly "input.requested"?: ChannelEventHandler<"input.requested", TCtx>;
+ readonly "turn.failed"?: ChannelEventHandler<"turn.failed", TCtx>;
+ readonly "turn.completed"?: ChannelEventHandler<"turn.completed", TCtx>;
+ readonly "session.failed"?: ChannelSessionFailedHandler<TCtx>;
+ readonly "session.completed"?: ChannelEventHandler<"session.completed", TCtx>;
+ readonly "session.waiting"?: ChannelEventHandler<"session.waiting", TCtx>;
+ readonly "authorization.required"?: ChannelEventHandler<"authorization.required", TCtx>;
+ readonly "authorization.completed"?: ChannelEventHandler<"authorization.completed", TCtx>;
+}
+
+/**
+ * Input passed to a channel's `receive` callback when another channel or
+ * schedule proactively routes a message to it.
+ */
+export type ReceiveInput<TReceiveTarget = Record<string, unknown>> =
+ GenericReceiveInput<TReceiveTarget>;
+
+/**
+ * The object passed to {@link defineChannel}. `routes` is required; `state`
+ * seeds durable adapter state, `context` builds the per-step `channel` argument
+ * for `events` and `deliver`, `events` handle session lifecycle, `receive`
+ * accepts cross-channel handoffs, `fetchFile` stages remote file URLs, and
+ * `metadata` projects observability data.
+ *
+ * Generics: `TState` (adapter state), `TCtx` (context factory return type),
+ * `TReceiveTarget` (cross-channel target shape), `TMetadata` (instrumentation
+ * projection).
+ */
+export type ChannelDefinition<
+ TState = undefined,
+ TCtx = void,
+ TReceiveTarget = Record<string, unknown>,
+ TMetadata extends Record<string, unknown> = Record<string, unknown>,
+> = GenericChannelDefinition<ChannelEvents<TCtx>, TState, TCtx, TReceiveTarget, TMetadata>;
+
+/**
+ * Opaque channel value produced by {@link defineChannel} and exported from
+ * `agent/channels/<name>.ts`. Exposes the channel's routes, an optional
+ * `receive` hook, and (via a phantom property) its metadata shape. Unlike
+ * {@link ChannelDefinition} it has no `TCtx` parameter: the context type is
+ * internal to the definition.
+ */
+export interface Channel<
+ TState = undefined,
+ TReceiveTarget = Record<string, unknown>,
+ TMetadata extends Record<string, unknown> = Record<string, unknown>,
+> extends TypedReceiveTarget<TReceiveTarget> {
+ readonly __kind: typeof CHANNEL_SENTINEL;
+ readonly [CHANNEL_METADATA_TYPE]?: TMetadata;
+ readonly routes: readonly RouteDefinition<TState>[];
+ readonly cors?: ChannelCorsOptions;
+ readonly receive?: (
+ input: ReceiveInput<TReceiveTarget>,
+ args: { send: SendFn<TState> },
+ ) => Promise<Session>;
+}
+
+/**
+ * Extracts the metadata projection type (`TMetadata`) from a {@link Channel}.
+ * Resolves to `Record<string, unknown>` when the value is not a Channel.
+ */
+export type InferChannelMetadata<TChannel> =
+ TChannel extends Channel<any, any, infer TMetadata> ? TMetadata : Record<string, unknown>;
+
+/**
+ * Builds a {@link Channel} from a {@link ChannelDefinition}. Returns a value
+ * placed at `agent/channels/<name>.ts`; the file path supplies the channel name
+ * (do not add a `name` field). `TCtx` (the context factory's return type) is
+ * internal to the definition and is not part of the returned Channel signature.
+ */
+export function defineChannel<
+ TState = undefined,
+ TCtx = void,
+ TReceiveTarget = Record<string, unknown>,
+ TMetadata extends Record<string, unknown> = Record<string, unknown>,
+>(
+ definition: ChannelDefinition<TState, TCtx, TReceiveTarget, TMetadata>,
+): Channel<TState, TReceiveTarget, TMetadata> {
+ const adapter = buildAdapter(definition);
+ const cors = normalizeChannelCors(definition.cors);
+
+ const compiled: CompiledChannel<TState, TReceiveTarget, TMetadata> = {
+ __kind: CHANNEL_SENTINEL,
+ routes: definition.routes,
+ adapter,
+ cors,
+ receive: definition.receive,
+ };
+
+ return compiled;
+}
+
+function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<string, unknown>>(
+ definition: ChannelDefinition<TState, TCtx, TReceiveTarget, TMetadata>,
+): ChannelAdapter<any> {
+ const hasState = definition.state != null;
+ const hasContext = definition.context != null;
+ const hasFetchFile = definition.fetchFile !== undefined;
+ const metadata = definition.metadata;
+ const hasMetadata = metadata !== undefined;
+ const hasBehavior = hasState || hasContext || hasMetadata;
+
+ const eventHandlers: Record<string, unknown> = {};
+ let hasEventHandlers = false;
+
+ const eventTypes = [
+ "turn.started",
+ "actions.requested",
+ "action.result",
+ "message.completed",
+ "message.appended",
+ "reasoning.appended",
+ "reasoning.completed",
+ "input.requested",
+ "turn.failed",
+ "turn.completed",
+ "session.failed",
+ "session.completed",
+ "session.waiting",
+ "authorization.required",
+ "authorization.completed",
+ ] as const;
+
+ const events = definition.events;
+ for (const eventType of eventTypes) {
+ const userHandler = events?.[eventType];
+ if (userHandler) {
+ hasEventHandlers = true;
+ eventHandlers[eventType] = (data: unknown, adapterCtx: any) => {
+ const channel = {
+ ...adapterCtx,
+ continuationToken: adapterCtx.session?.continuationToken ?? "",
+ setContinuationToken: (token: string) => adapterCtx.session?.setContinuationToken(token),
+ };
+ if (eventType === "session.failed") {
+ return (userHandler as (data: unknown, channel: any) => void | Promise<void>)(
+ data,
+ channel,
+ );
+ }
+ const ctx = buildCallbackContext();
+ return (
+ userHandler as (data: unknown, channel: any, ctx: SessionContext) => void | Promise<void>
+ )(data, channel, ctx);
+ };
+ }
+ }
+
+ if (!hasBehavior && !hasEventHandlers && !hasFetchFile) {
+ return { kind: definition.kindHint ?? HTTP_ADAPTER_KIND } as ChannelAdapter<any>;
+ }
+
+ const adapter: ChannelAdapter<any> = {
+ kind: definition.kindHint ?? "defineChannel",
+ state: hasState ? { ...(definition.state as Record<string, unknown>) } : {},
+ fetchFile: definition.fetchFile,
+ instrumentation:
+ metadata === undefined
+ ? undefined
+ : {
+ metadata(state): ChannelInstrumentationMetadata {
+ return metadata(state as NonNullable<TState>);
+ },
+ },
+
+ createAdapterContext(base): any {
+ const state = base.state;
+ const session = base.session;
+ const channelCtx = hasContext
+ ? (definition.context as (s: any, session: SessionHandle) => any)(state, session)
+ : {};
+
+ return {
+ ...channelCtx,
+ state,
+ ctx: base.ctx,
+ session,
+ };
+ },
+
+ deliver(payload: DeliverPayload) {
+ return defaultDeliverResult(payload);
+ },
+
+ ...eventHandlers,
+ } as ChannelAdapter<any>;
+
+ return adapter;
+}
diff --git a/packages/eve/src/public/definitions/defineChannel.ts b/packages/eve/src/public/definitions/defineChannel.ts
deleted file mode 100644
index 60011e3fc..000000000
--- a/packages/eve/src/public/definitions/defineChannel.ts
+++ /dev/null
@@ -1,328 +0,0 @@
-import type {
- ChannelAdapter,
- ChannelInstrumentationMetadata,
- FetchFileResult,
-} from "#channel/adapter.js";
-import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";
-import { normalizeChannelCors, type ChannelCors, type ChannelCorsOptions } from "#channel/cors.js";
-import { defaultDeliverResult } from "#channel/adapter.js";
-import { HTTP_ADAPTER_KIND } from "#channel/http.js";
-import type { TypedReceiveTarget } from "#channel/receive-target.js";
-import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";
-import { buildCallbackContext } from "#context/build-callback-context.js";
-import type { HandleMessageStreamEvent } from "#protocol/message.js";
-import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { RouteDefinition, SendFn } from "#channel/routes.js";
-import type { Session, SessionHandle } from "#channel/session.js";
-
-declare const CHANNEL_METADATA_TYPE: unique symbol;
-
-export type { Session, SessionHandle } from "#channel/session.js";
-export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
-export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
-export type {
- HttpRouteDefinition,
- RouteDefinition,
- RouteHandlerArgs,
- SendFn,
- SendOptions,
- SendPayload,
- GetSessionFn,
- WebSocketMessage,
- WebSocketPeer,
- WebSocketRouteDefinition,
- WebSocketRouteHandler,
- WebSocketRouteHooks,
- WebSocketUpgradeRequest,
- WebSocketUpgradeResult,
-} from "#channel/routes.js";
-
-type EventData<T extends HandleMessageStreamEvent["type"]> =
- Extract<HandleMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;
-
-/**
- * Session operations on the `channel` argument of every channel event handler.
- */
-export interface ChannelSessionOps {
- readonly continuationToken: string;
- setContinuationToken(token: string): void;
-}
-
-/**
- * Channel context passed to event handlers: `TCtx` intersected with
- * {@link ChannelSessionOps}.
- */
-export type ChannelContext<TCtx> = TCtx & ChannelSessionOps;
-
-type ChannelEventHandler<T extends HandleMessageStreamEvent["type"], TCtx> = (
- data: EventData<T>,
- channel: ChannelContext<TCtx>,
- ctx: SessionContext,
-) => void | Promise<void>;
-
-type ChannelSessionFailedHandler<TCtx> = (
- data: EventData<"session.failed">,
- channel: ChannelContext<TCtx>,
-) => void | Promise<void>;
-
-/**
- * Optional handlers keyed by session lifecycle event name. Each handler receives
- * the event `data`, the {@link ChannelContext}, and a {@link SessionContext}
- * `ctx`. The `session.failed` handler is the exception: it receives only `data`
- * and the channel context, with no `ctx`.
- */
-export interface ChannelEvents<TCtx = void> {
- readonly "turn.started"?: ChannelEventHandler<"turn.started", TCtx>;
- readonly "actions.requested"?: ChannelEventHandler<"actions.requested", TCtx>;
- readonly "action.result"?: ChannelEventHandler<"action.result", TCtx>;
- readonly "message.completed"?: ChannelEventHandler<"message.completed", TCtx>;
- readonly "message.appended"?: ChannelEventHandler<"message.appended", TCtx>;
- readonly "reasoning.appended"?: ChannelEventHandler<"reasoning.appended", TCtx>;
- readonly "reasoning.completed"?: ChannelEventHandler<"reasoning.completed", TCtx>;
- readonly "input.requested"?: ChannelEventHandler<"input.requested", TCtx>;
- readonly "turn.failed"?: ChannelEventHandler<"turn.failed", TCtx>;
- readonly "turn.completed"?: ChannelEventHandler<"turn.completed", TCtx>;
- readonly "session.failed"?: ChannelSessionFailedHandler<TCtx>;
- readonly "session.completed"?: ChannelEventHandler<"session.completed", TCtx>;
- readonly "session.waiting"?: ChannelEventHandler<"session.waiting", TCtx>;
- readonly "authorization.required"?: ChannelEventHandler<"authorization.required", TCtx>;
- readonly "authorization.completed"?: ChannelEventHandler<"authorization.completed", TCtx>;
-}
-
-/**
- * Input passed to a channel's `receive` callback when another channel or
- * schedule proactively routes a message to it.
- */
-export interface ReceiveInput<TReceiveTarget = Record<string, unknown>> {
- readonly message: string;
- readonly target: Readonly<TReceiveTarget>;
- readonly auth: SessionAuthContext | null;
-}
-
-/**
- * The object passed to {@link defineChannel}. `routes` is required; `state`
- * seeds durable adapter state, `context` builds the per-step `channel` argument
- * for `events` and `deliver`, `events` handle session lifecycle, `receive`
- * accepts cross-channel handoffs, `fetchFile` stages remote file URLs, and
- * `metadata` projects observability data.
- *
- * Generics: `TState` (adapter state), `TCtx` (context factory return type),
- * `TReceiveTarget` (cross-channel target shape), `TMetadata` (instrumentation
- * projection).
- */
-export interface ChannelDefinition<
- TState = undefined,
- TCtx = void,
- TReceiveTarget = Record<string, unknown>,
- TMetadata extends Record<string, unknown> = Record<string, unknown>,
-> {
- readonly state?: TState;
- /**
- * CORS policy for this channel's HTTP routes. `true` enables H3/Nitro's
- * permissive defaults (`origin`, methods, request headers, and exposed
- * headers all `"*"`); `false` or omission leaves CORS untouched. Pass an
- * object for a serializable subset of H3/Nitro CORS options.
- */
- readonly cors?: ChannelCors;
- /**
- * Builds the per-step channel context handed to `events` and `deliver`.
- * Receives the live {@link SessionHandle}, so a factory can close over it to
- * register late-bound callbacks. eve writes state mutations made inside the
- * returned context back through `adapter.state`.
- *
- * Return the channel-owned context (thread handles, API clients, etc.). The
- * framework passes it as the `channel` argument to event handlers (with
- * {@link ChannelSessionOps} injected) and passes {@link SessionContext} as a
- * separate `ctx` argument.
- */
- context?(state: NonNullable<TState>, session: SessionHandle): TCtx;
-
- readonly routes: readonly RouteDefinition<TState>[];
- receive?(input: ReceiveInput<TReceiveTarget>, args: { send: SendFn<TState> }): Promise<Session>;
-
- readonly events?: ChannelEvents<TCtx>;
-
- /**
- * Fetches bytes for a `URL` object encountered on a `FilePart.data` by the
- * staging pipeline. Return `null` to pass the URL through to the model
- * provider unchanged, or bytes / {@link FetchFileResult} to stage the file to
- * the sandbox.
- */
- readonly fetchFile?: (url: string) => Promise<Buffer | FetchFileResult | null>;
-
- /**
- * Channel-owned metadata exposed to instrumentation callbacks. This is the
- * channel's public observability surface, not a dump of durable adapter state,
- * so keep it small. Return an object of JSON primitives, arrays, and plain
- * objects: eve omits `undefined` properties and drops projections containing
- * values such as `Date` or `Map`.
- */
- readonly metadata?: (state: NonNullable<TState>) => TMetadata;
-
- /**
- * Identifier of the adapter family this channel belongs to. Set by
- * higher-level wrappers (e.g. `slackChannel` passes `"slack"`) so downstream
- * consumers can render typed channel chips instead of bucketing everything
- * under "unknown".
- *
- * Authors calling `defineChannel` directly do not need to set this; the
- * framework defaults to `"http"` for stateless channels and `"defineChannel"`
- * for stateful ones.
- */
- readonly kindHint?: string;
-}
-
-/**
- * Opaque channel value produced by {@link defineChannel} and exported from
- * `agent/channels/<name>.ts`. Exposes the channel's routes, an optional
- * `receive` hook, and (via a phantom property) its metadata shape. Unlike
- * {@link ChannelDefinition} it has no `TCtx` parameter: the context type is
- * internal to the definition.
- */
-export interface Channel<
- TState = undefined,
- TReceiveTarget = Record<string, unknown>,
- TMetadata extends Record<string, unknown> = Record<string, unknown>,
-> extends TypedReceiveTarget<TReceiveTarget> {
- readonly __kind: typeof CHANNEL_SENTINEL;
- readonly [CHANNEL_METADATA_TYPE]?: TMetadata;
- readonly routes: readonly RouteDefinition<TState>[];
- readonly cors?: ChannelCorsOptions;
- readonly receive?: (
- input: ReceiveInput<TReceiveTarget>,
- args: { send: SendFn<TState> },
- ) => Promise<Session>;
-}
-
-/**
- * Extracts the metadata projection type (`TMetadata`) from a {@link Channel}.
- * Resolves to `Record<string, unknown>` when the value is not a Channel.
- */
-export type InferChannelMetadata<TChannel> =
- TChannel extends Channel<any, any, infer TMetadata> ? TMetadata : Record<string, unknown>;
-
-/**
- * Builds a {@link Channel} from a {@link ChannelDefinition}. Returns a value
- * placed at `agent/channels/<name>.ts`; the file path supplies the channel name
- * (do not add a `name` field). `TCtx` (the context factory's return type) is
- * internal to the definition and is not part of the returned Channel signature.
- */
-export function defineChannel<
- TState = undefined,
- TCtx = void,
- TReceiveTarget = Record<string, unknown>,
- TMetadata extends Record<string, unknown> = Record<string, unknown>,
->(
- definition: ChannelDefinition<TState, TCtx, TReceiveTarget, TMetadata>,
-): Channel<TState, TReceiveTarget, TMetadata> {
- const adapter = buildAdapter(definition);
- const cors = normalizeChannelCors(definition.cors);
-
- const compiled: CompiledChannel<TState, TReceiveTarget, TMetadata> = {
- __kind: CHANNEL_SENTINEL,
- routes: definition.routes,
- adapter,
- cors,
- receive: definition.receive,
- };
-
- return compiled;
-}
-
-function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<string, unknown>>(
- definition: ChannelDefinition<TState, TCtx, TReceiveTarget, TMetadata>,
-): ChannelAdapter<any> {
- const hasState = definition.state != null;
- const hasContext = definition.context != null;
- const hasFetchFile = definition.fetchFile !== undefined;
- const metadata = definition.metadata;
- const hasMetadata = metadata !== undefined;
- const hasBehavior = hasState || hasContext || hasMetadata;
-
- const eventHandlers: Record<string, unknown> = {};
- let hasEventHandlers = false;
-
- const eventTypes = [
- "turn.started",
- "actions.requested",
- "action.result",
- "message.completed",
- "message.appended",
- "reasoning.appended",
- "reasoning.completed",
- "input.requested",
- "turn.failed",
- "turn.completed",
- "session.failed",
- "session.completed",
- "session.waiting",
- "authorization.required",
- "authorization.completed",
- ] as const;
-
- const events = definition.events;
- for (const eventType of eventTypes) {
- const userHandler = events?.[eventType];
- if (userHandler) {
- hasEventHandlers = true;
- eventHandlers[eventType] = (data: unknown, adapterCtx: any) => {
- const channel = {
- ...adapterCtx,
- continuationToken: adapterCtx.session?.continuationToken ?? "",
- setContinuationToken: (token: string) => adapterCtx.session?.setContinuationToken(token),
- };
- if (eventType === "session.failed") {
- return (userHandler as (data: unknown, channel: any) => void | Promise<void>)(
- data,
- channel,
- );
- }
- const ctx = buildCallbackContext();
- return (
- userHandler as (data: unknown, channel: any, ctx: SessionContext) => void | Promise<void>
- )(data, channel, ctx);
- };
- }
- }
-
- if (!hasBehavior && !hasEventHandlers && !hasFetchFile) {
- return { kind: definition.kindHint ?? HTTP_ADAPTER_KIND } as ChannelAdapter<any>;
- }
-
- const adapter: ChannelAdapter<any> = {
- kind: definition.kindHint ?? "defineChannel",
- state: hasState ? { ...(definition.state as Record<string, unknown>) } : {},
- fetchFile: definition.fetchFile,
- instrumentation:
- metadata === undefined
- ? undefined
- : {
- metadata(state): ChannelInstrumentationMetadata {
- return metadata(state as NonNullable<TState>);
- },
- },
-
- createAdapterContext(base): any {
- const state = base.state;
- const session = base.session;
- const channelCtx = hasContext
- ? (definition.context as (s: any, session: SessionHandle) => any)(state, session)
- : {};
-
- return {
- ...channelCtx,
- state,
- ctx: base.ctx,
- session,
- };
- },
-
- deliver(payload: DeliverPayload) {
- return defaultDeliverResult(payload);
- },
-
- ...eventHandlers,
- } as ChannelAdapter<any>;
-
- return adapter;
-}
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index eaf9b0cad..267cc775a 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -3,8 +3,8 @@ import { describe, expect, it } from "vitest";
import { defineAgent } from "#public/definitions/agent.js";
import { none } from "#public/channels/auth.js";
import { eveChannel, defaultEveAuth } from "#public/channels/eve.js";
-import { defineChannel, POST } from "#public/definitions/defineChannel.js";
-import { defineHook } from "#public/definitions/hook.js";
+import { defineChannel, POST } from "#public/definitions/channel.js";
+import { defineHook, type StreamEventHook } from "#public/definitions/hook.js";
import { defineInstructions } from "#public/definitions/instructions.js";
import { defineInstrumentation } from "#public/definitions/instrumentation.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
@@ -152,6 +152,18 @@ function typeOnlyFixtures(): void {
},
});
+ const unknownStreamEventHook: StreamEventHook<unknown> = (event, ctx) => {
+ const sessionId: string = ctx.session.id;
+ const value: unknown = event;
+ void sessionId;
+ void value;
+ };
+ defineHook({
+ events: {
+ "*": unknownStreamEventHook,
+ },
+ });
+
eveChannel({
auth: none(),
onMessage(ctx, message) {
diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.ts
index ebac88150..2711f833f 100644
--- a/packages/eve/src/public/definitions/hook.ts
+++ b/packages/eve/src/public/definitions/hook.ts
@@ -1,6 +1,7 @@
import type { HandleMessageStreamEvent } from "../../protocol/message.js";
import type { SessionContext } from "./callback-context.js";
import type { ExactDefinition } from "./exact.js";
+import type { GenericHookDefinition, GenericStreamEventHooks } from "#shared/hook-definition.js";
/**
* Every hook handler receives this context.
@@ -34,13 +35,7 @@ export type StreamEventHook<TEvent> = (event: TEvent, ctx: HookContext) => void
* `*` matches every accepted runtime stream event and runs after the
* typed handler for that event (if any).
*/
-export type StreamEventHooks = {
- readonly "*"?: StreamEventHook<HandleMessageStreamEvent>;
-} & {
- readonly [K in HandleMessageStreamEvent["type"]]?: StreamEventHook<
- Extract<HandleMessageStreamEvent, { type: K }>
- >;
-};
+export type StreamEventHooks = GenericStreamEventHooks<HandleMessageStreamEvent, HookContext>;
/**
* Public hook definition authored in `agent/hooks/*.ts`.
@@ -51,9 +46,7 @@ export type StreamEventHooks = {
* contribute runtime model messages, use `defineDynamic` +
* `defineInstructions` in `agent/instructions/`.
*/
-export interface HookDefinition {
- readonly events?: StreamEventHooks;
-}
+export type HookDefinition = GenericHookDefinition<HandleMessageStreamEvent, HookContext>;
/**
* Identity-with-types helper. Returns the passed definition unchanged
diff --git a/packages/eve/src/public/definitions/instructions.ts b/packages/eve/src/public/definitions/instructions.ts
index d8545725a..cf7246a64 100644
--- a/packages/eve/src/public/definitions/instructions.ts
+++ b/packages/eve/src/public/definitions/instructions.ts
@@ -1,24 +1,8 @@
import { INSTRUCTIONS_BRAND } from "#shared/dynamic-tool-definition.js";
import type { ExactDefinition } from "#public/definitions/exact.js";
+import type { PublicInstructionsDefinition } from "#shared/instructions-definition.js";
-/**
- * Public definition for an instructions prompt authored in markdown or
- * TypeScript.
- *
- * Authored at the agent root as either `instructions.md` or
- * `instructions.{ts,cts,mts,js,cjs,mjs}`, or inside the
- * `agent/instructions/` directory for multi-file setups. Module-backed
- * static instructions execute once at build time. The compiler captures
- * the resulting markdown into the compiled manifest.
- *
- * When used inside a `defineDynamic` handler, the runtime lowers the
- * returned markdown to `{ role: "system", content: markdown }`.
- * Instructions produce system messages only. Use channel `context` for
- * user-role messages.
- */
-export interface InstructionsDefinition {
- readonly markdown: string;
-}
+export type InstructionsDefinition = Readonly<PublicInstructionsDefinition>;
/**
* Defines an instructions prompt in TypeScript from a `{ markdown }`
diff --git a/packages/eve/src/public/definitions/schedule.ts b/packages/eve/src/public/definitions/schedule.ts
index 5bc50e7bb..b2cfbbc7c 100644
--- a/packages/eve/src/public/definitions/schedule.ts
+++ b/packages/eve/src/public/definitions/schedule.ts
@@ -1,6 +1,11 @@
import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { ExactDefinition } from "#public/definitions/exact.js";
+import type {
+ GenericScheduleDefinition,
+ GenericScheduleRunHandler,
+ GenericScheduleDefinitionFields,
+} from "#shared/schedule-definition.js";
export type { InferReceiveTarget, TypedReceiveTarget } from "#channel/receive-target.js";
@@ -34,14 +39,7 @@ export interface ScheduleHandlerArgs {
* schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`receive`,
* `waitUntil`, `appAuth`) and may return synchronously or as a promise.
*/
-export type ScheduleRunHandler = (args: ScheduleHandlerArgs) => Promise<void> | void;
-
-/** Constraint shape that bounds the authored keys accepted by {@link defineSchedule}. */
-interface ScheduleDefinitionFields {
- readonly cron: string;
- readonly markdown?: string;
- readonly run?: ScheduleRunHandler;
-}
+export type ScheduleRunHandler = GenericScheduleRunHandler<ScheduleHandlerArgs>;
/**
* Public definition for a schedule authored in TypeScript. Provide a required
@@ -56,17 +54,7 @@ interface ScheduleDefinitionFields {
* Identity is derived from the file path under `agent/schedules/`; authored
* definitions do not carry a `name` field.
*/
-export type ScheduleDefinition =
- | {
- readonly cron: string;
- readonly markdown: string;
- readonly run?: never;
- }
- | {
- readonly cron: string;
- readonly markdown?: never;
- readonly run: ScheduleRunHandler;
- };
+export type ScheduleDefinition = GenericScheduleDefinition<ScheduleHandlerArgs>;
/**
* Defines a schedule in TypeScript. Export as the default from
@@ -102,7 +90,7 @@ export type ScheduleDefinition =
* ```
*/
export function defineSchedule<TSchedule extends ScheduleDefinition>(
- definition: ExactDefinition<TSchedule, ScheduleDefinitionFields>,
+ definition: ExactDefinition<TSchedule, GenericScheduleDefinitionFields<ScheduleHandlerArgs>>,
): TSchedule {
return definition;
}
diff --git a/packages/eve/src/public/hooks/index.ts b/packages/eve/src/public/hooks/index.ts
index bf611226c..314b5c928 100644
--- a/packages/eve/src/public/hooks/index.ts
+++ b/packages/eve/src/public/hooks/index.ts
@@ -12,4 +12,4 @@ export {
type StreamEventHook,
type StreamEventHooks,
defineHook,
-} from "../definitions/hook.js";
+} from "#public/definitions/hook.js";
diff --git a/packages/eve/src/public/sandbox/backends/default.ts b/packages/eve/src/public/sandbox/backends/default.ts
index d96d6e648..adfb0c78a 100644
--- a/packages/eve/src/public/sandbox/backends/default.ts
+++ b/packages/eve/src/public/sandbox/backends/default.ts
@@ -9,7 +9,7 @@ import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.
import { justbash } from "#public/sandbox/backends/just-bash.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
import { microsandbox } from "#public/sandbox/backends/microsandbox.js";
-import type { MicrosandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
+import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
import { vercel } from "#public/sandbox/backends/vercel.js";
import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
@@ -21,7 +21,7 @@ import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.
export interface DefaultSandboxOptions {
readonly docker?: DockerSandboxCreateOptions;
readonly justBash?: JustBashSandboxCreateOptions;
- readonly microsandbox?: MicrosandboxCreateOptions;
+ readonly microsandbox?: MicrosandboxSandboxCreateOptions;
readonly vercel?: VercelSandboxCreateOptions;
}
diff --git a/packages/eve/src/public/sandbox/backends/microsandbox.ts b/packages/eve/src/public/sandbox/backends/microsandbox.ts
index 2167060b5..31fd8cc5b 100644
--- a/packages/eve/src/public/sandbox/backends/microsandbox.ts
+++ b/packages/eve/src/public/sandbox/backends/microsandbox.ts
@@ -2,7 +2,7 @@ import { createMicrosandboxSandboxBackend } from "#execution/sandbox/bindings/lo
import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
import type {
MicrosandboxBootstrapUseOptions,
- MicrosandboxCreateOptions,
+ MicrosandboxSandboxCreateOptions,
MicrosandboxSessionUseOptions,
} from "#public/sandbox/microsandbox-sandbox.js";
@@ -21,7 +21,7 @@ import type {
* fallback behavior, use `defaultBackend()` instead.
*/
export function microsandbox(
- opts?: MicrosandboxCreateOptions,
+ opts?: MicrosandboxSandboxCreateOptions,
): SandboxBackend<MicrosandboxBootstrapUseOptions, MicrosandboxSessionUseOptions> {
return createMicrosandboxSandboxBackend({ createOptions: opts });
}
diff --git a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
index aaa913a53..58639cc68 100644
--- a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
+++ b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
@@ -9,7 +9,7 @@ import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
* stay stable while the underlying runtime evolves. Supported hosts:
* macOS on Apple Silicon, or Linux (glibc) with KVM enabled.
*/
-export interface MicrosandboxCreateOptions {
+export interface MicrosandboxSandboxCreateOptions {
/**
* OCI image used as the base runtime. eve prepares this image with
* Bash, the framework workspace, and the sandbox user before authored
diff --git a/packages/eve/src/public/sandbox/microsandbox.ts b/packages/eve/src/public/sandbox/microsandbox.ts
index e318571e9..a92efa86c 100644
--- a/packages/eve/src/public/sandbox/microsandbox.ts
+++ b/packages/eve/src/public/sandbox/microsandbox.ts
@@ -1,6 +1,6 @@
export { microsandbox } from "#public/sandbox/backends/microsandbox.js";
export type {
MicrosandboxBootstrapUseOptions,
- MicrosandboxCreateOptions,
+ MicrosandboxSandboxCreateOptions,
MicrosandboxSessionUseOptions,
} from "#public/sandbox/microsandbox-sandbox.js";
diff --git a/packages/eve/src/runtime/hooks/registry.ts b/packages/eve/src/runtime/hooks/registry.ts
index b77ee64e7..b223a7c68 100644
--- a/packages/eve/src/runtime/hooks/registry.ts
+++ b/packages/eve/src/runtime/hooks/registry.ts
@@ -1,3 +1,4 @@
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { StreamEventHook } from "../../public/definitions/hook.js";
import type { ResolvedHookDefinition } from "../types.js";
@@ -9,7 +10,7 @@ import type { ResolvedHookDefinition } from "../types.js";
*/
interface RuntimeStreamEventHookEntry {
readonly slug: string;
- readonly handler: StreamEventHook<unknown>;
+ readonly handler: StreamEventHook<HandleMessageStreamEvent>;
readonly eventType: string;
}
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 82bb4cd06..16bad0192 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -1,7 +1,7 @@
import { formatAvailableSkillsSection } from "#execution/skills/instructions.js";
import type {
ResolvedConnectionDefinition,
- ResolvedInstructions,
+ ResolvedInstructionsDefinition,
ResolvedSkillDefinition,
} from "#runtime/types.js";
import { createWorkspacePromptSection } from "#runtime/workspace/spec.js";
@@ -17,7 +17,7 @@ const PARALLEL_ACTION_INSTRUCTION =
*/
interface ComposeRuntimeBasePromptInput {
connections?: readonly ResolvedConnectionDefinition[];
- instructions?: ResolvedInstructions;
+ instructions?: ResolvedInstructionsDefinition;
skills?: readonly ResolvedSkillDefinition[];
toolsAvailable?: boolean;
workspaceSpec?: WorkspaceRuntimeSpec;
@@ -38,7 +38,7 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):
}
function createInstructionsPromptBlocks(
- instructions: ResolvedInstructions | undefined,
+ instructions: ResolvedInstructionsDefinition | undefined,
): readonly string[] {
if (instructions === undefined) {
return [];
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index e5e63f3b7..7f07f9c52 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -1,4 +1,7 @@
-import type { CompiledAgentNodeManifest, CompiledInstructions } from "#compiler/manifest.js";
+import type {
+ CompiledAgentNodeManifest,
+ CompiledInstructionsDefinition,
+} from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
import { resolveChannelDefinition } from "#runtime/resolve-channel.js";
@@ -19,7 +22,7 @@ import type {
ResolvedAgent,
ResolvedChannelDefinition,
ResolvedSkillDefinition,
- ResolvedInstructions,
+ ResolvedInstructionsDefinition,
} from "#runtime/types.js";
/**
@@ -96,7 +99,7 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg
input.manifest.sandbox === null
? null
: await resolveSandboxDefinition(input.manifest.sandbox, input.moduleMap, input.nodeId);
- const instructions = createResolvedInstructions(input.manifest.instructions);
+ const instructions = createResolvedInstructionsDefinition(input.manifest.instructions);
const workspaceResourceRoot = input.manifest.workspaceResourceRoot;
const resolvedAgent: ResolvedAgent = {
channels: resolvedChannels,
@@ -128,9 +131,9 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg
return resolvedAgent;
}
-function createResolvedInstructions(
- instructions: CompiledInstructions | undefined,
-): ResolvedInstructions | undefined {
+function createResolvedInstructionsDefinition(
+ instructions: CompiledInstructionsDefinition | undefined,
+): ResolvedInstructionsDefinition | undefined {
if (instructions === undefined) {
return undefined;
}
diff --git a/packages/eve/src/runtime/resolve-hook.ts b/packages/eve/src/runtime/resolve-hook.ts
index 18f97ac43..2e22fa685 100644
--- a/packages/eve/src/runtime/resolve-hook.ts
+++ b/packages/eve/src/runtime/resolve-hook.ts
@@ -1,6 +1,7 @@
import type { CompiledHookDefinition } from "../compiler/manifest.js";
import type { CompiledModuleMap } from "../compiler/module-map.js";
import { expectFunction, expectObjectRecord } from "../internal/authored-module.js";
+import type { HandleMessageStreamEvent } from "../protocol/message.js";
import type { StreamEventHook } from "../public/definitions/hook.js";
import { toErrorMessage } from "../shared/errors.js";
import { loadResolvedModuleExport, ResolveAgentError } from "./resolve-helpers.js";
@@ -32,7 +33,7 @@ export async function resolveHookDefinition(
describe(definition, "to return an object"),
);
- const events: Record<string, StreamEventHook<unknown>> = {};
+ const events: Record<string, StreamEventHook<HandleMessageStreamEvent>> = {};
const eventsRaw = resolvedRecord.events;
if (eventsRaw !== undefined) {
@@ -46,7 +47,7 @@ export async function resolveHookDefinition(
value,
describe(definition, `to provide a function for "events.${key}"`),
);
- events[key] = handler as StreamEventHook<unknown>;
+ events[key] = handler as StreamEventHook<HandleMessageStreamEvent>;
}
}
diff --git a/packages/eve/src/runtime/schedules/register.ts b/packages/eve/src/runtime/schedules/register.ts
index 13edc720e..6785a4a38 100644
--- a/packages/eve/src/runtime/schedules/register.ts
+++ b/packages/eve/src/runtime/schedules/register.ts
@@ -1,4 +1,4 @@
-import type { ResolvedSchedule } from "#runtime/types.js";
+import type { ResolvedScheduleDefinition } from "#runtime/types.js";
/**
* Stable Nitro task-name prefix for framework-owned authored schedules.
@@ -56,7 +56,7 @@ export class ScheduleRegistrationError extends Error {
* resolved authored schedules.
*/
export function createScheduleRegistrations(
- schedules: readonly ResolvedSchedule[],
+ schedules: readonly ResolvedScheduleDefinition[],
): ScheduleRegistration[] {
const registrations = schedules
.map((schedule) => ({
diff --git a/packages/eve/src/runtime/schedules/resolve-schedule.ts b/packages/eve/src/runtime/schedules/resolve-schedule.ts
index 2beb4ac70..6ac489505 100644
--- a/packages/eve/src/runtime/schedules/resolve-schedule.ts
+++ b/packages/eve/src/runtime/schedules/resolve-schedule.ts
@@ -1,7 +1,7 @@
import type { CompiledAgentManifest } from "#compiler/manifest.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
-import type { ResolvedSchedule } from "#runtime/types.js";
+import type { ResolvedScheduleDefinition } from "#runtime/types.js";
import { createScheduleRegistrations } from "#runtime/schedules/register.js";
/**
@@ -44,7 +44,9 @@ class ResolveScheduleError extends Error {
/**
* Resolves runtime-owned schedules from the compiled manifest.
*/
-export async function resolveSchedules(input: ResolveSchedulesInput): Promise<ResolvedSchedule[]> {
+export async function resolveSchedules(
+ input: ResolveSchedulesInput,
+): Promise<ResolvedScheduleDefinition[]> {
return [...input.manifest.schedules].map((schedule) => {
const base = {
cron: schedule.cron,
@@ -56,10 +58,10 @@ export async function resolveSchedules(input: ResolveSchedulesInput): Promise<Re
};
if (schedule.markdown !== undefined) {
- return { ...base, markdown: schedule.markdown } as ResolvedSchedule;
+ return { ...base, markdown: schedule.markdown } as ResolvedScheduleDefinition;
}
- return base as ResolvedSchedule;
+ return base as ResolvedScheduleDefinition;
});
}
@@ -69,7 +71,7 @@ export async function resolveSchedules(input: ResolveSchedulesInput): Promise<Re
*/
export async function loadResolvedCompiledSchedules(
input: LoadResolvedCompiledSchedulesInput,
-): Promise<ResolvedSchedule[]> {
+): Promise<ResolvedScheduleDefinition[]> {
const manifest = await loadCompiledManifest({
compiledArtifactsSource: input.compiledArtifactsSource,
});
@@ -86,7 +88,7 @@ export async function loadResolvedCompiledSchedules(
export async function loadResolvedCompiledScheduleByTaskName(
taskName: string,
input: LoadResolvedCompiledSchedulesInput,
-): Promise<ResolvedSchedule> {
+): Promise<ResolvedScheduleDefinition> {
const schedules = await loadResolvedCompiledSchedules(input);
const scheduleBySourceId = new Map(schedules.map((schedule) => [schedule.sourceId, schedule]));
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index fee391404..473158973 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -5,6 +5,7 @@ import type { CompiledChannel } from "#channel/compiled-channel.js";
import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
import type { HeadersValue } from "#client/types.js";
import type { DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { ChannelRouteMethod, RouteContext } from "#public/definitions/channel.js";
import type { RouteHandler, WebSocketRouteHandler } from "#channel/routes.js";
import type { OutboundAuthFn } from "#public/agents/auth.js";
@@ -49,7 +50,7 @@ export type ResolvedModuleSourceRef = Readonly<ModuleSourceRef>;
* the resulting markdown is captured here. Runtime never re-evaluates
* the module.
*/
-export type ResolvedInstructions = Readonly<
+export type ResolvedInstructionsDefinition = Readonly<
SourceRef & {
name: string;
markdown: string;
@@ -76,7 +77,7 @@ export type ResolvedSkillDefinition = Readonly<
* a {@link ScheduleHandlerArgs}-shaped argument; for the markdown form
* the dispatcher synthesizes a channel-less SCHEDULE_ADAPTER run.
*/
-export type ResolvedSchedule = Readonly<
+export type ResolvedScheduleDefinition = Readonly<
SourceRef & {
readonly cron: string;
readonly name: string;
@@ -207,7 +208,7 @@ export interface ResolvedHookDefinition extends ResolvedModuleSourceRef {
* wildcard if declared. Unknown keys are accepted at resolve time
* and ignored at dispatch time.
*/
- readonly events: Readonly<Record<string, StreamEventHook<unknown>>>;
+ readonly events: Readonly<Record<string, StreamEventHook<HandleMessageStreamEvent>>>;
}
/**
@@ -390,7 +391,7 @@ export interface ResolvedAgent {
* `instructions.{ts,...}`, or `undefined` when the agent does not
* declare one.
*/
- readonly instructions?: ResolvedInstructions;
+ readonly instructions?: ResolvedInstructionsDefinition;
/**
* Authored sandbox override for this agent, when one exists. `null`
* means the agent uses the framework default sandbox unchanged.
diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.ts
new file mode 100644
index 000000000..043c9970c
--- /dev/null
+++ b/packages/eve/src/shared/channel-definition.ts
@@ -0,0 +1,108 @@
+import { type ChannelCors } from "#channel/cors.js";
+import type { RouteDefinition, SendFn } from "#channel/routes.js";
+import type { Session, SessionHandle } from "#channel/session.js";
+import type { SessionAuthContext } from "#channel/types.js";
+
+/**
+ * Enriched return shape from a channel's {@link ChannelAdapter.fetchFile}
+ * function. Return a bare {@link Buffer} when only bytes are known, or
+ * this record when the fetch discovers a more accurate `mediaType` or
+ * `filename` (e.g. from an HTTP `Content-Type` header).
+ *
+ * When fields are provided, staging prefers them over the values the
+ * channel populated at ingestion time.
+ */
+export interface FetchFileResult {
+ readonly bytes: Buffer;
+ readonly mediaType?: string;
+ readonly filename?: string;
+}
+
+export type FetchFileFunction = (url: string) => Promise<Buffer | FetchFileResult | null>;
+
+/**
+ * Input passed to a channel's `receive` callback when another channel or
+ * schedule proactively routes a message to it.
+ */
+export interface GenericReceiveInput<TReceiveTarget = Record<string, unknown>> {
+ readonly message: string;
+ readonly target: Readonly<TReceiveTarget>;
+ readonly auth: SessionAuthContext | null;
+}
+
+/**
+ * The object passed to {@link defineChannel}. `routes` is required; `state`
+ * seeds durable adapter state, `context` builds the per-step `channel` argument
+ * for `events` and `deliver`, `events` handle session lifecycle, `receive`
+ * accepts cross-channel handoffs, `fetchFile` stages remote file URLs, and
+ * `metadata` projects observability data.
+ *
+ * Generics: `TState` (adapter state), `TCtx` (context factory return type),
+ * `TReceiveTarget` (cross-channel target shape), `TMetadata` (instrumentation
+ * projection).
+ */
+export interface GenericChannelDefinition<
+ TEvents,
+ TState = undefined,
+ TCtx = void,
+ TReceiveTarget = Record<string, unknown>,
+ TMetadata extends Record<string, unknown> = Record<string, unknown>,
+> {
+ readonly state?: TState;
+ /**
+ * CORS policy for this channel's HTTP routes. `true` enables H3/Nitro's
+ * permissive defaults (`origin`, methods, request headers, and exposed
+ * headers all `"*"`); `false` or omission leaves CORS untouched. Pass an
+ * object for a serializable subset of H3/Nitro CORS options.
+ */
+ readonly cors?: ChannelCors;
+ /**
+ * Builds the per-step channel context handed to `events` and `deliver`.
+ * Receives the live {@link SessionHandle}, so a factory can close over it to
+ * register late-bound callbacks. eve writes state mutations made inside the
+ * returned context back through `adapter.state`.
+ *
+ * Return the channel-owned context (thread handles, API clients, etc.). The
+ * framework passes it as the `channel` argument to event handlers (with
+ * {@link ChannelSessionOps} injected) and passes {@link SessionContext} as a
+ * separate `ctx` argument.
+ */
+ context?(state: NonNullable<TState>, session: SessionHandle): TCtx;
+
+ readonly routes: readonly RouteDefinition<TState>[];
+ receive?(
+ input: GenericReceiveInput<TReceiveTarget>,
+ args: { send: SendFn<TState> },
+ ): Promise<Session>;
+
+ readonly events?: TEvents;
+
+ /**
+ * Fetches bytes for a `URL` object encountered on a `FilePart.data` by the
+ * staging pipeline. Return `null` to pass the URL through to the model
+ * provider unchanged, or bytes / {@link FetchFileResult} to stage the file to
+ * the sandbox.
+ */
+ readonly fetchFile?: FetchFileFunction;
+
+ /**
+ * Channel-owned metadata exposed to instrumentation callbacks. This is the
+ * channel's public observability surface, not a dump of durable adapter state,
+ * so keep it small. Return an object of JSON primitives, arrays, and plain
+ * objects: eve omits `undefined` properties and drops projections containing
+ * values such as `Date` or `Map`.
+ */
+ readonly metadata?: (state: NonNullable<TState>) => TMetadata;
+
+ /**
+ * Identifier of the adapter family this channel belongs to. Set by
+ * higher-level wrappers (e.g. `slackChannel` passes `"slack"`) so downstream
+ * consumers can render typed channel chips instead of bucketing everything
+ * under "unknown".
+ *
+ * Authors calling `defineChannel` directly do not need to set this; the
+ * framework defaults to `"http"` for stateless channels and `"defineChannel"`
+ * for stateful ones.
+ */
+ readonly kindHint?: string;
+}
diff --git a/packages/eve/src/shared/hook-definition.ts b/packages/eve/src/shared/hook-definition.ts
new file mode 100644
index 000000000..733660d45
--- /dev/null
+++ b/packages/eve/src/shared/hook-definition.ts
@@ -0,0 +1,37 @@
+type BaseEvent = { type: string };
+
+/**
+ * Side-effect-only handler for one accepted runtime stream event.
+ *
+ * `TEvent` is one variant of the runtime stream-event union.
+ * {@link GenericStreamEventHooks} infers `TEvent` from the event key.
+ */
+export type GenericStreamEventHook<TEvent extends BaseEvent, TContext> = (
+ event: TEvent,
+ ctx: TContext,
+) => void | Promise<void>;
+
+/**
+ * Map of stream-event subscribers an authored hook file may declare.
+ *
+ * `*` matches every accepted runtime stream event and runs after the
+ * typed handler for that event (if any).
+ */
+export type GenericStreamEventHooks<TEvent extends BaseEvent, TContext> = {
+ readonly "*"?: GenericStreamEventHook<TEvent, TContext>;
+} & {
+ readonly [K in TEvent["type"]]?: GenericStreamEventHook<Extract<TEvent, { type: K }>, TContext>;
+};
+
+/**
+ * Public hook definition authored in `agent/hooks/*.ts`.
+ *
+ * Hook files declare stream-event subscribers (under `events:`) that
+ * fire after eve has accepted and durably recorded each event.
+ * Handlers are observe-only: they cannot inject model context. To
+ * contribute runtime model messages, use `defineDynamic` +
+ * `defineInstructions` in `agent/instructions/`.
+ */
+export interface GenericHookDefinition<TEvent extends BaseEvent, TContext> {
+ readonly events?: GenericStreamEventHooks<TEvent, TContext>;
+}
diff --git a/packages/eve/src/shared/instructions-definition.ts b/packages/eve/src/shared/instructions-definition.ts
new file mode 100644
index 000000000..d4e4deabf
--- /dev/null
+++ b/packages/eve/src/shared/instructions-definition.ts
@@ -0,0 +1,27 @@
+/**
+ * Public definition for an instructions prompt authored in markdown or
+ * TypeScript.
+ *
+ * Authored at the agent root as either `instructions.md` or
+ * `instructions.{ts,cts,mts,js,cjs,mjs}`, or inside the
+ * `agent/instructions/` directory for multi-file setups. Module-backed
+ * static instructions execute once at build time. The compiler captures
+ * the resulting markdown into the compiled manifest.
+ *
+ * When used inside a `defineDynamic` handler, the runtime lowers the
+ * returned markdown to `{ role: "system", content: markdown }`.
+ * Instructions produce system messages only. Use channel `context` for
+ * user-role messages.
+ */
+export interface PublicInstructionsDefinition {
+ markdown: string;
+}
+
+/**
+ * Internal definition for an instructions prompt authored in markdown or
+ * TypeScript.
+ */
+export interface InternalInstructionsDefinition {
+ name: string;
+ markdown: string;
+}
diff --git a/packages/eve/src/shared/schedule-definition.ts b/packages/eve/src/shared/schedule-definition.ts
new file mode 100644
index 000000000..92572f40b
--- /dev/null
+++ b/packages/eve/src/shared/schedule-definition.ts
@@ -0,0 +1,38 @@
+/**
+ * The `run` form of {@link ScheduleDefinition} invokes this handler when a
+ * schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`receive`,
+ * `waitUntil`, `appAuth`) and may return synchronously or as a promise.
+ */
+export type GenericScheduleRunHandler<TArgs> = (args: TArgs) => Promise<void> | void;
+
+/** Constraint shape that bounds the authored keys accepted by {@link defineSchedule}. */
+export interface GenericScheduleDefinitionFields<TArgs> {
+ readonly cron: string;
+ readonly markdown?: string;
+ readonly run?: GenericScheduleRunHandler<TArgs>;
+}
+
+/**
+ * Public definition for a schedule authored in TypeScript. Provide a required
+ * `cron` expression plus exactly one of `markdown` or `run`:
+ *
+ * - `markdown`: fire-and-forget agent invocation. The framework runs the agent
+ * on the prompt and discards the output (equivalent to the `<name>.md`
+ * markdown form).
+ * - `run`: full handler ({@link GenericScheduleRunHandler}). Receives
+ * `{ receive, waitUntil, appAuth }` and decides what to do.
+ *
+ * Identity is derived from the file path under `agent/schedules/`; authored
+ * definitions do not carry a `name` field.
+ */
+export type GenericScheduleDefinition<TArgs> =
+ | {
+ readonly cron: string;
+ readonly markdown: string;
+ readonly run?: never;
+ }
+ | {
+ readonly cron: string;
+ readonly markdown?: never;
+ readonly run: GenericScheduleRunHandler<TArgs>;
+ };
diff --git a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
index 652f02bc2..57f402998 100644
--- a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
+++ b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
@@ -94,7 +94,7 @@ export default defineSandbox({
},
{
descriptor: SLACK_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/slack/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/slack/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported slackChannel without extra annotations",
packageExports: {
"./channels/slack": {
@@ -104,7 +104,7 @@ export default defineSandbox({
},
{
descriptor: DISCORD_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/discord/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/discord/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported discordChannel without extra annotations",
packageExports: {
"./channels/discord": {
@@ -114,7 +114,7 @@ export default defineSandbox({
},
{
descriptor: GITHUB_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/github/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/github/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported githubChannel without extra annotations",
packageExports: {
"./channels/github": {
@@ -124,7 +124,7 @@ export default defineSandbox({
},
{
descriptor: TWILIO_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/twilio/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/twilio/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported twilioChannel without extra annotations",
packageExports: {
"./channels/twilio": {
@@ -134,7 +134,7 @@ export default defineSandbox({
},
{
descriptor: TEAMS_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/teams/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/teams/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported teamsChannel without extra annotations",
packageExports: {
"./channels/teams": {
@@ -144,7 +144,7 @@ export default defineSandbox({
},
{
descriptor: TELEGRAM_ROUTE_PORTABILITY_DESCRIPTOR,
- include: ["src/public/channels/telegram/index.ts", "src/public/definitions/defineChannel.ts"],
+ include: ["src/public/channels/telegram/index.ts", "src/public/definitions/channel.ts"],
name: "lets tsc typecheck a default-exported telegramChannel without extra annotations",
packageExports: {
"./channels/telegram": {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7f6ca8799..59e9c6363 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -86,6 +86,9 @@ importers:
gray-matter:
specifier: 4.0.3
version: 4.0.3
+ konsistent:
+ specifier: 1.0.0-beta.1
+ version: 1.0.0-beta.1
oxfmt:
specifier: 0.55.0
version: 0.55.0([email protected](@typescript-eslint/[email protected]))
@@ -2403,6 +2406,13 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+ '@konsistent/[email protected]':
+ resolution: {integrity: sha512-MidQWenua30khP6/8CDWsy6vVBQQBFj9SgC4IKE8r3+6fRWrnBklWsT9r7ndGC/VQtlb+8WMZUIRIBhZK26k6w==}
+ engines: {node: '>=22.11.0'}
+ hasBin: true
+ peerDependencies:
+ zod: ^4
+
'@kwsites/[email protected]':
resolution: {integrity: sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==}
@@ -9790,6 +9800,11 @@ packages:
resolution: {integrity: sha512-4LqMNoONzR43B1W0ek0fhXMsDNW/zxa1NdFAVMY+k28pgZLovR4G3PB5MrpTxCy1QaZCqNoiaKPr5w5qZHfSNw==}
+ resolution: {integrity: sha512-1izi+r5Jqoz9gEzS/7l6tkBoHhRaDerAovjBTxlwyUzAVDAxmj6QL84H8mN5aoi9rh1eloO0s12C5M2L+o3SFg==}
+ engines: {node: '>=22.11.0'}
+ hasBin: true
+
resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}
@@ -14388,6 +14403,12 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ citty: 0.2.2
+ jiti: 2.7.0
+ zod: 4.4.3
+
'@kwsites/[email protected]':
dependencies:
debug: 4.4.3
@@ -22456,6 +22477,16 @@ snapshots:
+ dependencies:
+ '@konsistent/convention': 1.0.0-beta.1([email protected])
+ citty: 0.2.2
+ picocolors: 1.1.1
+ resolve.exports: 2.0.3
+ tinyglobby: 0.2.17
+ typescript: 5.9.3
+ zod: 4.4.3
+