@happyvertical/smrt-prompts

中文文档
0.62.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 3.4万

Typed prompt registry, override resolution, and tenant-aware prompt settings for SMRT

原始使用文档
文档目录9 节
  1. Installation
  2. Quick start
  3. What this package provides
  4. Generated surfaces
  5. Management UI
  6. Consumer recipe
  7. What the consumer still owns
  8. Prompt keys are persisted identifiers
  9. Documentation

@happyvertical/smrt-prompts

Typed prompt definitions, tenant-aware prompt overrides, and runtime prompt resolution for s-m-r-t applications.

Installation

pnpm add @happyvertical/smrt-prompts

Quick start

import { definePrompt, resolvePrompt } from '@happyvertical/smrt-prompts';

// 1. Register a prompt's defaults at startup
definePrompt({
  key: 'projects.issue.incorporateFeedback',
  template: 'Rewrite the issue body incorporating this feedback: {feedback}',
  ai: {
    // An inference tier (`cheap | good | great | best | auto`) or a profile
    // named in config. With no `inference` config every tier runs on the
    // app's configured AI client.
    profile: 'great',
    params: { temperature: 0.4 },
  },
});

// 2. Resolve at runtime (auto-uses tenant context from AsyncLocalStorage)
const resolved = await resolvePrompt('projects.issue.incorporateFeedback', {
  vars: { feedback: '...' },
});

// resolved.template — the merged template with overrides applied
// resolved.ai     — the merged AI configuration (profile, model, params)

What this package provides

  • definePrompt() — code-first prompt registration in a global process registry
  • resolvePrompt() — layered resolution: code default → config override → stored app override → stored tenant override → runtime override
  • PromptOverride — model for app-level and tenant-level prompt settings, stored in _smrt_prompt_overrides
  • PromptOverrideService / PromptSettingsService — the authorized write path and the read/write helper for a management screen (see "Management UI" below)
  • Named AI profiles loaded from packages.prompts config — prompts select profile names, profiles resolve to provider/model in config
  • Tracked calls and effort — every model call carries a prompt key: trackedPromptCall(resolved) turns a resolution into the argument of core's tracked client, and ai: { effort } sets the prompt's reasoning effort (low to max). Concepts: AI runs
  • TTL cache keyed by (key, tenantId), invalidated on override save/delete

Stored overrides support partial fields, so applications can override only the template, profile, model, or AI params without forking the rest of a prompt.

Generated surfaces

PromptOverride ships with generated REST routes, MCP tools, and CLI commands closed (api: false, cli: false, mcp: false). Override rows are authorization state for every scope, so write them only from server code through PromptOverrideService, which asks an authorizer you bind to the current caller before every write and fails closed:

const service = new PromptOverrideService(overrides, (request) =>
  request.scopeType === 'tenant' && request.scopeId === session.tenantId &&
  session.permissions.has('prompts.manage'),
);
await service.setTemplateOverride(key, 'tenant', session.tenantId, 'New text.');

Management UI

The package ships the settings screen so consuming apps do not each rebuild it: PromptSettingsService (root export) produces the rows, and PromptSettingsPanel (the ./svelte subpath) renders them. The root export stays Svelte-free, so a server-only consumer is unaffected; svelte is an optional peer dependency.

Consumer recipe

1. Register the prompt in code (see Quick start above), including editable if you want tenants or the app-wide default to be overridable:

definePrompt({
  key: 'projects.issue.incorporateFeedback',
  template: 'Rewrite the issue body incorporating this feedback: {feedback}',
  description: 'Rewrites an issue body from reviewer feedback.',
  editable: { template: true },
});

2. Load the rows in your server load. The load is where your permission check lives — the package makes no authorization decision:

// src/routes/settings/prompts/+page.server.ts
export async function load(event) {
  const auth = requirePermission(event, APP_PERMISSIONS.tenantAdmin);
  const settings = await PromptSettingsService.create({ db });
  return {
    tenantId: auth.tenantId,
    prompts: await settings.listPromptSettings({ tenantId: auth.tenantId }),
  };
}

listPromptSettings() returns one PromptSettingsRow per registered key — the effective template for the requested tenant, the raw override text at each scope (appTemplate/tenantTemplate), what reverting each scope produces (appDefaultTemplate/inheritedTemplate), and supplyingLevel. The row is structurally assignable to the panel's PromptSettingsView, so no mapping step is needed.

3. Render the panel:

<script lang="ts">
  import { PromptSettingsPanel } from '@happyvertical/smrt-prompts/svelte';
  let { data, form } = $props();
</script>

<PromptSettingsPanel
  prompts={data.prompts}
  contextKey={data.tenantId}
  formAction="?/savePrompt"
  message={form?.message}
  error={form?.error}
/>

The panel is presentational: it takes rows and callbacks, fetches nothing and authorizes nothing. Each row renders the key, description, effective text, and which level supplied it, plus a checkbox + text editor for the tenant scope (and, when showApp/appEditable are set, the app scope). Unchecking the box reverts that scope — the preview text next to it shows exactly what reverting produces. Supply onSave instead of formAction to drive it from a client handler.

4. Wire the write with your own permission check. setPromptOverride() refuses any key without a definition and any field the definition's editable config disallows, then delegates to PromptOverrideService, which asks your authorizer and fails closed:

export const actions = {
  savePrompt: async (event) => {
    const auth = requirePermission(event, APP_PERMISSIONS.tenantAdmin);
    const form = await event.request.formData();
    const settings = await PromptSettingsService.create(
      { db },
      {
        // Your decision, bound to this caller. Returning anything but `true` denies.
        authorize: (request) =>
          request.scopeType === 'tenant' && request.scopeId === auth.tenantId,
      },
    );

    try {
      await settings.setTenantPromptOverride(
        String(form.get('key') ?? ''),
        auth.tenantId,
        form.has('tenantOverride') ? String(form.get('tenantTemplate') ?? '') : null,
      );
    } catch (error) {
      if (error instanceof UnknownPromptKeyError) return fail(400, { error: 'Unknown prompt.' });
      if (error instanceof PromptFieldNotEditableError) return fail(400, { error: 'Not editable.' });
      if (error instanceof InvalidPromptScopeError) return fail(400, { error: 'Invalid scope.' });
      if (error instanceof PromptOverrideAuthorizationError) return fail(403, { error: 'Not permitted.' });
      throw error;
    }
    return { message: 'Prompt overrides saved.' };
  },
};

Constructing the service without an authorize option makes it read-only: every write then fails closed with PromptOverrideAuthorizationError. That is the right shape for a load function.

What the consumer still owns

  • the route, its navigation entry, and the page shell;
  • the permission check on both the load and the action;
  • the authorize callback (this package never decides who may write);
  • resolving the session's tenantId — a tenant id from the URL or a form field is a selector, not authorization;
  • registering prompts with definePrompt() at startup.

Prompt keys are persisted identifiers

Overrides are stored keyed by the exact key string and resolved by that string at runtime. Renaming a key orphans every existing override, silently reverting all tenants to the registry default — the change looks harmless in a diff and shows up as prompt text mysteriously resetting. Treat a key as immutable once shipped. A rename needs a data migration that rewrites _smrt_prompt_overrides.key, not an edit.

Documentation

版本与发布记录

@happyvertical/smrt-prompts 共发布 365 个版本,首次发布于 2026/06/23;过去 12 个月发布了 365 个版本。

版本发布日期距今
0.62.1latest2026/11/17今天
0.62.02026/11/17今天
0.61.62026/11/161 天前
0.61.52026/11/161 天前
0.61.42026/11/161 天前
0.61.32026/11/152 天前

关于 @happyvertical/smrt-prompts 的常见问题

@happyvertical/smrt-prompts 是什么?

Typed prompt registry, override resolution, and tenant-aware prompt settings for SMRT

如何安装 @happyvertical/smrt-prompts?

在项目目录运行 npm install @happyvertical/smrt-prompts,或使用 pnpm add / yarn add / bun add。

@happyvertical/smrt-prompts 支持 TypeScript 吗?

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

@happyvertical/smrt-prompts 支持 ESM 还是 CommonJS?

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

@happyvertical/smrt-prompts 可以商用吗?

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

@happyvertical/smrt-prompts 的下载量有多少?

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

@happyvertical/smrt-prompts 还在维护吗?

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