@beignet/agent-auth-better-auth

中文文档
0.0.65发布于 2026/11/08MITTypeScriptES Module零依赖近 30 天下载 1769

Better Auth Agent Auth adapter for Beignet agent capabilities

原始使用文档
文档目录6 节
  1. Install
  2. Define capabilities
  3. Create the registry and executor
  4. Add the Agent Auth bridge
  5. Testing
  6. Agent skills

@beignet/agent-auth-better-auth

Runtime: Beignet requires Node.js 22.12 or newer. Bun is optional.

[!CAUTION] Beignet is experimental alpha software. The 0.0.x package line is for early evaluation, and APIs may change between releases while the framework settles.

Expose a typed Beignet agent capability registry through Better Auth's Agent Auth plugin. Beignet owns capability validation, application context, use-case execution, tracing, and instrumentation. Agent Auth owns registration, JWT verification, grants, constraints, approval, and protocol persistence.

Install

bun add @beignet/core @beignet/agent-auth-better-auth \
  @better-auth/[email protected] [email protected] zod@^4.6.6

The bridge supports Agent Auth >=0.6.2 <0.7.0 and Better Auth >=1.7.7 <1.8.0, with Zod ^4.6.6. The command pins the auth versions Beignet validates together.

Define capabilities

// lib/agent-capabilities.ts
import { createAgentCapabilities } from "@beignet/core/agent-capabilities";
import type { AppContext } from "@/app-context";

export type AgentPrincipal = {
  agentId: string;
  userId: string;
};

export const { defineAgentCapability, defineAgentCapabilityRegistry } =
  createAgentCapabilities<AppContext, AgentPrincipal>();
// features/issues/agent-capabilities.ts
import { z } from "zod";
import { createIssueUseCase } from "./use-cases";
import { defineAgentCapability } from "@/lib/agent-capabilities";

export const createIssueCapability = defineAgentCapability("issues.create", {
  description: "Create an issue in one workspace.",
  input: z.object({
    workspaceId: z.string().min(1),
    title: z.string().min(1),
  }),
  output: z.object({ id: z.string(), title: z.string() }),
  async handle({ ctx, input }) {
    const { workspaceId: _workspaceId, ...useCaseInput } = input;
    return createIssueUseCase.run({ ctx, input: useCaseInput });
  },
});

Create the registry and executor

import { createAgentCapabilityExecutor } from "@beignet/core/agent-capabilities";
import { appError } from "@/features/shared/errors";
import { createIssueCapability } from "@/features/issues/agent-capabilities";
import { defineAgentCapabilityRegistry } from "@/lib/agent-capabilities";
import { getServer } from "@/server";

export const agentCapabilityRegistry =
  defineAgentCapabilityRegistry([createIssueCapability]);

export const agentCapabilityExecutor = createAgentCapabilityExecutor({
  registry: agentCapabilityRegistry,
  async createContext({ principal, input }) {
    const server = await getServer();
    const membership = await server.ports.members.findMembership({
      workspaceId: input.workspaceId,
      userId: principal.userId,
    });
    if (!membership) throw appError("NotAWorkspaceMember");

    return server.createServiceContext({
      asUser: { id: principal.userId, role: membership.role },
      tenantId: input.workspaceId,
    });
  },
});

The executor validates arguments before context construction and validates the handler result before returning it to Agent Auth. The context resolver must derive tenant membership from authoritative app state rather than agent claims.

Add the Agent Auth bridge

import { agentAuth } from "@better-auth/agent-auth";
import { betterAuth } from "better-auth";
import { APIError } from "better-auth/api";
import { createBetterAuthAgentCapabilityAdapter } from
  "@beignet/agent-auth-better-auth";
import {
  agentCapabilityExecutor,
  agentCapabilityRegistry,
} from "@/server/agent-capabilities";

const agentCapabilities = createBetterAuthAgentCapabilityAdapter({
  registry: agentCapabilityRegistry,
  executor: agentCapabilityExecutor,
  principal({ agentSession }) {
    if (!agentSession.userId) {
      throw new APIError("FORBIDDEN", {
        message: "A delegated user is required.",
      });
    }
    return {
      agentId: agentSession.agentId,
      userId: agentSession.userId,
    };
  },
  metadata: {
    "issues.create": {
      approvalStrength: "session",
      requiredConstraints: ["workspaceId"],
    },
  },
});

export const auth = betterAuth({
  // database, sessions, and other app-owned configuration
  plugins: [
    agentAuth({
      ...agentCapabilities,
      providerName: "example",
      modes: ["delegated"],
    }),
  ],
});

After registering agentAuth(...), regenerate the Better Auth schema for your database adapter and apply the resulting migration. Repeat this step after upgrading Agent Auth or changing Better Auth plugins that add or modify database fields, so registration, grant, and protocol state match the runtime. Apps upgrading from Better Auth 1.7.0–1.7.2 must relax the legacy account.issuer constraint even though Agent Auth remains on 0.6.2. Follow the Better Auth 1.7 migration guidance before deploying the updated runtime.

If auth initialization and server composition depend on each other, provide a lazy executor instead of building an app-owned proxy:

import { agentCapabilityRegistry } from "@/lib/agent-capability-registry";

const agentCapabilities = createBetterAuthAgentCapabilityAdapter({
  registry: agentCapabilityRegistry,
  executor: () =>
    import("@/server/agent-capabilities").then(
      ({ agentCapabilityExecutor }) => agentCapabilityExecutor,
    ),
  principal({ agentSession }) {
    if (!agentSession.userId) {
      throw new APIError("FORBIDDEN", {
        message: "A delegated user is required.",
      });
    }
    return { agentId: agentSession.agentId, userId: agentSession.userId };
  },
});

Keep the transport-safe registry in a module that does not import server composition; only the executor needs the dynamic server import. The adapter loads the executor on the first execution and memoizes the first successful resolution for the lifetime of the warm module instance. Concurrent executions share initialization; a failed resolution is not cached.

Zod schemas are converted to protocol JSON Schema by default. Pass a Beignet SchemaConverter through schemaConverter when using another Standard Schema library. Conversion runs at adapter creation so unsupported schemas fail during boot instead of on the first agent request.

Agent Auth authorizes grant constraints against raw arguments before invoking the adapter. The adapter also verifies at execution time that the active grant still contains every field currently declared in requiredConstraints. This prevents older broad grants from remaining usable after capability metadata is tightened. Revoke or migrate stale grants so agents can request replacement grants with the newly required scope.

Beignet also rejects an invocation when schema validation changes a field constrained by the active grant. Keep constrained identifiers and amounts non-transforming; normalization remains available for unconstrained fields. The adapter snapshots active constrained values before validation, parses once, and checks the exact parsed input subsequently used for context construction and execution.

This bridge intentionally uses Agent Auth's default capability execution endpoint. It does not expose custom capability location metadata because custom locations send requests to an app-owned route and bypass this bridge's validation, context, constraint-stability, tracing, and output guarantees.

The adapter preserves intentional Better Auth APIError failures. Declared Beignet AppError failures use their stable application code as the Agent Auth error code. Individual execution also preserves the AppError HTTP status; batch execution reports each item as failed and preserves the code without a per-item HTTP status. Invalid arguments become Agent Auth invalid_request errors; unknown capabilities use capability_not_found; invalid outputs and unexpected failures become redacted internal_error responses. Throw APIError or a declared AppError only when a failure is intentionally safe for an agent to receive.

Only synchronous request/response capability results are supported in this release. Agent Auth asynchronous polling and streaming results remain transport-owned and are not produced by the Beignet executor.

Testing

Use the adapter testing subpath to exercise onExecute without manufacturing Better Auth's internal endpoint context:

import { createBetterAuthAgentCapabilityTestContext } from
  "@beignet/agent-auth-better-auth/testing";

await agentCapabilities.onExecute?.(
  createBetterAuthAgentCapabilityTestContext({
    capability: "issues.create",
    arguments: { workspaceId: "workspace_1", title: "Fix login" },
    constraints: { workspaceId: "workspace_1" },
  }),
);

Agent skills

This package ships a TanStack Intent skill: @beignet/agent-auth-better-auth#agent-capabilities. Load it when defining a capability registry, constructing delegated service contexts, or wiring Better Auth Agent Auth.

版本与发布记录

@beignet/agent-auth-better-auth 共发布 31 个版本,首次发布于 2026/07/12;过去 12 个月发布了 31 个版本。

版本发布日期距今
0.0.65latest2026/11/081 天前
0.0.642026/11/036 天前
0.0.632026/11/028 天前
0.0.622026/11/018 天前
0.0.612026/11/018 天前
0.0.602026/11/018 天前

关于 @beignet/agent-auth-better-auth 的常见问题

@beignet/agent-auth-better-auth 是什么?

Better Auth Agent Auth adapter for Beignet agent capabilities

如何安装 @beignet/agent-auth-better-auth?

在项目目录运行 npm install @beignet/agent-auth-better-auth,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(^4.6.6)、better-auth(>=1.7.7 <1.8.0)、@beignet/core(>=0.0.3 <1.0.0)、@better-auth/agent-auth(>=0.6.2 <0.7.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@beignet/agent-auth-better-auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@beignet/agent-auth-better-auth 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@beignet/agent-auth-better-auth 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@beignet/agent-auth-better-auth 可以商用吗?

@beignet/agent-auth-better-auth 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@beignet/agent-auth-better-auth 的下载量有多少?

根据 npm 官方下载统计,@beignet/agent-auth-better-auth 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,769 次,日均约 59 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@beignet/agent-auth-better-auth 还在维护吗?

最新版本 0.0.65 发布于 2026/11/08(1 天前);至今共发布 31 个版本,其中过去 12 个月发布了 31 个;首次发布于 2026/07/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。