@north-light/plugin

中文文档
0.3.573发布于 2026/11/02UNLICENSEDTypeScriptES Module

crouter

原始使用文档
文档目录8 节
  1. Install
  2. Define a plugin
  3. Install into crtr
  4. Serving as an app registered in the directory
  5. Metered provider tools
  6. Reference
  7. Related
  8. License

@north-light/plugin — define crtr commands once in TypeScript and serve them over HTTP

crouter

npm

@north-light/plugin lets an application add commands to the crtr CLI, and so to every agent that runs it. You write one typed command tree. The package turns it into a Fetch handler, a commands.json manifest, and the archive that crtr pkg plugin install --endpoint reads. You do not write a manifest, a route table, or a plugin.json.

It is a server-side authoring kit, not a runtime: the handler is a standard Fetch { fetch } default export that you deploy on whatever host serves one. It does not run agents; an agent calls your command the way it calls any other crtr command, and crtr makes an HTTP request to your endpoint. Plugins that need no server, such as local executables, are installed from a marketplace instead; see the plugin docs.

Docs · Commands · Deploying · Official marketplace · crouter repository

Install

npm install @north-light/plugin

The package is ESM-only. Import it from an ES module or use dynamic import() from CommonJS. To try a plugin you also need the crtr CLI: npm install -g @north-light/cli, then run crtr once to sign in to a model provider.

Define a plugin

Create src/crtr-plugin.ts:

import {
  createFetchHandler,
  defineBranch,
  defineLeaf,
  definePlugin,
  field,
  LeafError,
  param,
} from '@north-light/plugin';

export const plugin = definePlugin({
  name: 'acme',
  description: 'Manage Acme applications.',
  whenToUse: 'you need to create or inspect an Acme application.',
  summary: 'Acme application management',
  rootEntry: {
    concept: 'an Acme application',
    description: 'Create and inspect applications.',
    whenToUse: 'the task is about an Acme application.',
  },
  commands: {
    app: defineBranch({
      description: 'Create and inspect applications.',
      whenToUse: 'you are working with an application.',
      summary: 'application operations',
      children: {
        create: defineLeaf({
          description: 'Create an Acme application.',
          whenToUse: 'an application does not exist yet.',
          summary: 'create an application',
          params: {
            name: param.positional('The application name.', { required: true }),
            region: param.enum(['us-east', 'eu-west'], 'The region for the application.', { default: 'us-east' }),
          },
          output: {
            appId: field.string('The created application id.'),
            url: field.string('The application URL.'),
          },
          effects: ['Creates an Acme application.'],
          handler(input) {
            if (input.name === 'taken') {
              throw new LeafError({
                code: 'name_taken',
                message: 'That application name is already in use.',
                status: 409,
                field: 'name',
              });
            }
            return {
              appId: `app_${input.name}`,
              url: `https://${input.name}.${input.region ?? 'us-east'}.acme.example.com`,
            };
          },
        }),
      },
    }),
  },
});

export default {
  fetch: createFetchHandler(plugin, { token: process.env.ACME_CRTR_TOKEN }),
};

The handler input is inferred from params: name is required and region is optional. Deploy the default export at the URL crtr reaches. The same URL handles GET archive requests and POST command requests.

Install into crtr

Set the same bearer token on the machine that runs crtr, then install the handler's actual mount path:

export ACME_CRTR_TOKEN='replace-with-a-secret'
crtr pkg plugin install --endpoint https://acme.example.com/crtr --name acme --auth-env ACME_CRTR_TOKEN
crtr acme app create my-app --region eu-west

export covers commands you type yourself. An agent's crtr acme … runs inside its broker, whose env comes from the profile env store, not from your shell — so for agents, store the token there too: echo -n "$ACME_CRTR_TOKEN" | crtr profile env set <profile> --name ACME_CRTR_TOKEN. Nodes launched under that profile from then on carry it.

Use the actual mount path in --endpoint. The generated archive declares command paths below that path, while crtr stores the origin for later command calls. Installing only https://acme.example.com would send calls to the origin root instead of /crtr.

Serving as an app registered in the directory

An app that serves commands to people who connected it passes directory authentication instead of a static token:

import { createFetchHandler, createNodeHandler } from '@north-light/plugin';

const handler = createFetchHandler(plugin, {
  auth: { issuer: 'https://directory.example', audience: 'https://acme.example.com/crtr', providerId: CLIENT_ID },
  requests,
});

providerId is the app's client id (its OAuth client id), bare or as app:<id>. The directory mints scopes as <provider id>:<group>, so the kit requires <providerId>:<group> on each leaf. Without providerId it requires <plugin name>:<group>, which only a first-party provider whose name equals its id carries — every call from any other app answers 403 scope_missing, and the error's next names the id to set.

Declare the app's tool groups next to its leaves with definePlugin({ provider: true, version, groups }). groups is keyed by group id; each value has consentLine and optionally who (own, user, allowlist, any, team:<id>; omitted means user) and allowlist (app:<id> principals, only with who: 'allowlist'). Every leaf's group must name a declared group and every declared group must be used by a leaf, or definePlugin throws. The served bundle.json carries it as "groups": {"<id>": {"consent_line": "...", "who"?: "...", "allowlist"?: [...]}} and the directory applies it when it refreshes the provider's manifest. See Commands in the docs.

On Node, Express or Nest, mount the Fetch handler with createNodeHandler(handler, { bodyLimit?, origin? }). It turns the request into a Fetch Request (using req.rawBody when the framework buffered it, else the stream), refuses a body over bodyLimit (default 65536 bytes) with 413 before the handler runs, streams the response with its repeated headers and set-cookie, and answers 500 if the handler throws. In Nest, a controller method is @All(['', '*path']) serve(@Req() req, @Res() res) { return node(req, res); }; with node:http, createServer((req, res) => void node(req, res)). Pass origin when the public origin differs from the Host header.

Metered provider tools

With directory authentication, configure createFetchHandler(plugin, { auth, receipts: { provider: 'app:acme', outbox } }). provider must be the provider's authenticated app:<id> principal, not the plugin name. Emitted receipt tool values, and the tool that ctx.checkSpend() sends, are command paths after the plugin name: send for crtr acme send, or messages send for crtr acme messages send. A handler calls ctx.meter({ units, unit }) to emit a Crtr-Receipt; the provider persists and posts that same receipt to the directory ledger. ctx.meter may be called once for each distinct unit in a call (a repeated unit throws); pass receiptId to name a receipt (the default is the request id, and each receipt in a call needs its own id). One receipt rides in Crtr-Receipt as an object, several as a JSON array, and receipts metered before a LeafError ride on the error response.

The kit holds no prices: the directory owns every price, maximum and allowance (set in the console or with crtr cloud apps provider pricing), and charges from the receipt's units or its reported cost. ctx.meter sets the receipt's usd_equivalent to the first of: the usdEquivalent you pass (a tool that reports its cost passes it); units × the price row of this request's ctx.checkSpend() answer whose unit matches, for a unit-priced tool; otherwise 0. It never throws for a missing price. The figure is what the runtime shows as the call's cost; the directory recomputes the charge itself and never trusts it. ReceiptOptions.rates no longer exists: delete it when you upgrade (TypeScript flags it; a JavaScript config that still passes it is ignored).

ctx.causedBy is request:<this request's Crtr-Request-Id> (absent when the request carries none). A handler that calls a runtime itself passes it on, so the spend of those calls is traced to this call: new Crouter({ causedBy: ctx.causedBy }), or causedBy on runs.start.

ctx.caller.payer is the principal charged for the call, user:<id> or app:<id>: the token's payer claim, or sub when the token has none. ctx.meter stamps it on the receipt. Before a priced call, await ctx.checkSpend() asks the directory (POST <auth.issuer>/v1/billing/check, sending the request's outbound token) whether that payer may spend on this command (it posts { token, tool }, tool being the command path above) and keeps the price rows it answers for ctx.meter; it reserves nothing and resolves with { prices } (every row of the group's price, [price] when the directory answers only price, empty when unpriced). It needs receipts.ledger: { clientId, privateKey, keyId? }, the same credentials you pass to postReceipt, and throws a plain Error without them or without a verified caller. It resolves when the call may go ahead, throws SpendRefusedError { code, message, next } on a refusal (payment_required or limit_reached, with next the page that fixes it), and throws ReceiptPostError when the check cannot be completed. To refuse the call, rethrow it as new LeafError({ code: e.code, message: e.message, status: 402, next: e.next }).

To answer a rate limit, throw a LeafError with retryAfter (seconds, or a Date): throw new LeafError({ code: 'rate_limited', status: 429, message: 'Slow down.', retryAfter: 30 }) answers 429 with Retry-After: 30. headers: { 'X-RateLimit-Reset': '…' } sets any other response header; Content-Type, Content-Length, Content-Encoding, Transfer-Encoding and Crtr-Receipt belong to the kit. For a side-effect leaf the kit passes the headers to requests.store as answer.headers (lowercase names); a store that keeps and returns them makes a repeated request answer with the same headers.

For side-effect leaves, provide requests: { record, read, store, delete }. record(requestId, identity) atomically inserts both the id and {sub, grantee} from the verified caller (or null for a legacy static-token plugin); read(requestId) returns {identity, recordedAt, answer}. The kit refuses a repeated id from a different caller rather than replaying another person's result. store saves the result and receipt transactionally with the outbox. answer.receipt is the call's first receipt, as always; when a call metered more than one, answer.receipts also lists all of them (first included) and a store must save and return it from read (replay rebuilds Crtr-Receipt from receipts when present, else receipt). An unrecorded request saves each receipt with its own outbox.save call. onError gets (error, path, receipt, receipts?) and onAnswer gets receiptIds under the same rule. For provider logging, onAnswer(event) receives one metadata-only event per answered leaf POST (principal-chain fields, request/run ids, relative tool, status, duration, receipt id, replay flag); it never receives bearer tokens, arguments, or result bodies, and a logging failure does not alter the answer. createCallerVerifier(auth) is exported for providers that verify requests outside the Fetch handler.

Reference

The plugin guide covers commands, parameters, output, errors and streaming, deployment, and bundles and documents.

License

Proprietary. Copyright (c) 2026 Northlight Systems. All rights reserved. See LICENSE.

版本与发布记录

@north-light/plugin 共发布 155 个版本,首次发布于 2026/10/10;过去 12 个月发布了 155 个版本。

版本发布日期距今
0.3.573latest2026/11/021 天前
0.3.5722026/11/021 天前
0.3.5712026/11/021 天前
0.3.5702026/11/021 天前
0.3.5692026/11/012 天前
0.3.5682026/11/012 天前

关于 @north-light/plugin 的常见问题

如何安装 @north-light/plugin?

在项目目录运行 npm install @north-light/plugin,或使用 pnpm add / yarn add / bun add。

@north-light/plugin 支持 TypeScript 吗?

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

@north-light/plugin 支持 ESM 还是 CommonJS?

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

@north-light/plugin 可以商用吗?

@north-light/plugin 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

@north-light/plugin 还在维护吗?

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