@happyvertical/smrt-prompts 0.60.14 → 0.60.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -28,6 +28,7 @@ Each layer can override any subset of fields (template, profile, model, params).
28
28
  - **Stored overrides use nullable fields** so inheritance stays field-by-field — null means "use the lower layer"
29
29
  - **Provider selection is indirect** in v1: prompts select named profiles, and profiles resolve to provider/model in `smrt-config`
30
30
  - **`editable` flags are enforced on `PromptOverride.save()`** — definitions can lock specific fields against tenant override
31
+ - **Tier names are reserved profile names** (#4750): `cheap`, `good`, `great`, `best` and `auto` need no `profiles` entry. `resolvePrompt()` only marks them (`ai.tier`, `ai.promptKey`, and the code default's `ai.latency`) and never copies a binding into `provider`/`model`/`params`: the tier binds once, at call time, through core's seam (`prepareAiOperation()` / `getAiClient(tier)`) with the prompt key, so prompt and call cannot disagree. `allowedProfileNames` applies to tier names chosen by config or an override, but not to the tier the code default itself declares when no config, stored or runtime layer sets a profile (#4755), so an allow-list never breaks framework prompts. An explicit prompt `model` stays validated by `allowedModels` and is sent per call on the tier client. **Footgun:** a same-named `profiles` entry wins and silently opts that name out of tiers. `definePrompt({ ai: { minimumTier } })` sets the ladder floor for a tier prompt (#4752); it is read from the code default only (stripped from params at every layer), so config and tenant overrides cannot lower it, and `promptMessageOptions()` forwards it with `tier`. `tier`, `latency` and `promptKey` never come from params. The canonical `promptMessageOptions()` forwards them; callers send the result through `prepareAiOperation()` (`SmrtClass`, so collections too), which strips them before the provider call. Sites holding their own client (content chat and thumbnails, facts' injected message-only client, the translation job, `Issue`'s explicit-provider path) pass `{ routeTier: false }` or drop the keys, so the prompt's tier does not route there and records no tier tags; the translation job and `Issue`'s path still apply a stored tenant or user binding through core's `resolveInferenceTarget({ appBindings: false })` (#4756), which adds tier and `source` tags only when a binding applied.
31
32
 
32
33
  ## Generated surfaces
33
34
 
@@ -51,13 +52,45 @@ write) or `PromptOverrideCollection.setTemplateOverride()` /
51
52
  - `vitest.config.ts` runs two projects (`server` node + `smrtVitestPlugin`, `svelte` jsdom + `@sveltejs/vite-plugin-svelte` with `conditions: ['browser']`) because the browser condition would send `smrt-core` to its browser build if applied globally.
52
53
  - `PromptSettingsService.create()` builds its `PromptOverrideCollection` with the caller's `defaultListLimit`/`maxListLimit` stripped before the bulk `getOverrideMapForKeys()` enumeration read that backs `listPromptSettings()` — the #3056 hazard class in `smrt-features`'s `FeatureOverrideCollection.getOverrideMap()`, applied here proactively rather than left for a follow-up issue. A host-configured list bound must never silently drop a key's override from a management screen.
53
54
 
55
+ ## Usage tags (#4751)
56
+
57
+ `resolvePrompt()` returns `ai.usageTags = { promptKey, promptLayer,
58
+ templateHash }`: `promptLayer` is the highest layer that supplied the template
59
+ (`default | config | app | tenant | runtime`; a params-only layer does not
60
+ count), `templateHash` the first 12 hex chars of the SHA-256 of the unrendered
61
+ effective template (Web Crypto, so the root stays free of `node:crypto`).
62
+ `promptMessageOptions(ai, { usageTags? })` is the one helper that turns a
63
+ resolution into `ai.message()` options; package copies re-export it. Tag
64
+ precedence, low to high: a `usageTags` object in params (tenant-editable, so
65
+ reserved tags — identity, `runId`, tier, `substitutions`, `fusionKey` — are
66
+ dropped from it), the resolution's tags, the caller's. Params never carry
67
+ `tier`, `latency` or `promptKey` either: tier routing comes only from the
68
+ validated profile. Every consumer
69
+ call site must forward them (`promptMessageOptions()` or a spread of
70
+ `resolved.ai`); core lifts `promptKey` into `_smrt_ai_usage.prompt_key`
71
+ (`../core/agents/ai-usage.md`).
72
+
73
+ ## Framework prompt tiers (#4755)
74
+
75
+ Every framework `definePrompt()` declares `ai.profile` as a tier: closed-
76
+ vocabulary classification and yes/no predicates → `cheap`; summaries,
77
+ descriptions, translations, headlines → `good`; synthesis over user content
78
+ that is persisted or applied (feedback incorporation, reviews, corrections,
79
+ fact extraction and reconciliation) → `great`; nothing defaults to `best`.
80
+ `ai.latency` is `interactive` on request paths (chat, editor) and `background`
81
+ for jobs, else unset; only the code default declares it. Prompts that make no model call (persona instructions,
82
+ chat system prompts) or call a non-text model (image generation) declare no
83
+ tier. An explicit model on the call path wins over the tier. Each package's
84
+ `AGENTS.md` records its choices; one test per package pins the tag set.
85
+
54
86
  ## Prompt keys are persisted identifiers
55
87
 
56
88
  Overrides are stored keyed by the exact `key` string and resolved by that
57
89
  string at runtime. **Renaming a key orphans every existing override and
58
- silently reverts every tenant to the registry default.** Treat a shipped key
59
- as immutable; a rename needs a data migration over
60
- `_smrt_prompt_overrides.key`, not an edit.
90
+ silently reverts every tenant to the registry default**, and it also orphans
91
+ the key's `_smrt_ai_usage` series: history stays under the old `prompt_key`
92
+ and outcome labels never join the new one. Treat a shipped key as immutable;
93
+ a rename needs a data migration over `_smrt_prompt_overrides.key`, not an edit.
61
94
 
62
95
  ## Caching
63
96
 
package/README.md CHANGED
@@ -18,7 +18,10 @@ definePrompt({
18
18
  key: 'projects.issue.incorporateFeedback',
19
19
  template: 'Rewrite the issue body incorporating this feedback: {feedback}',
20
20
  ai: {
21
- profile: 'default',
21
+ // An inference tier (`cheap | good | great | best | auto`) or a profile
22
+ // named in config. With no `inference` config every tier runs on the
23
+ // app's configured AI client.
24
+ profile: 'great',
22
25
  params: { temperature: 0.4 },
23
26
  },
24
27
  });
package/dist/index.d.ts CHANGED
@@ -14,8 +14,9 @@ export { InvalidPromptScopeError, PromptOverrideAuthorizationError, type PromptO
14
14
  export { definePrompt, PromptRegistry } from './prompt-registry.js';
15
15
  export { resolvePrompt } from './prompt-resolver.js';
16
16
  export { type ListPromptSettingsOptions, PromptFieldNotEditableError, type PromptSettingsLevel, type PromptSettingsRow, PromptSettingsService, type PromptSettingsServiceOptions, type SetPromptOverrideRequest, UnknownPromptKeyError, } from './prompt-settings.js';
17
- export type { NormalizedPromptAI, PromptAIInput, PromptConfigOverrideInput, PromptDefinition, PromptDefinitionInput, PromptEditableConfig, PromptLayer, PromptOverrideScopeType, PromptPackageConfig, PromptParams, PromptProfileConfig, ResolvedPrompt, ResolvedPromptAI, ResolvePromptOptions, } from './types.js';
17
+ export type { NormalizedPromptAI, PromptAIInput, PromptConfigOverrideInput, PromptDefinition, PromptDefinitionInput, PromptEditableConfig, PromptLayer, PromptOverrideScopeType, PromptPackageConfig, PromptParams, PromptProfileConfig, PromptSourceLayer, PromptUsageTags, ResolvedPrompt, ResolvedPromptAI, ResolvePromptOptions, } from './types.js';
18
18
  export { APP_PROMPT_SCOPE_ID } from './types.js';
19
+ export { type PromptMessageOptions, type PromptMessageOptionsExtra, promptMessageOptions, promptTemplateHash, } from './utils.js';
19
20
  /** @internal */
20
21
  export declare const PACKAGE_VERSION_INITIALIZED = true;
21
22
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,wBAAwB,CAAC;AAEhC,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AACrF,OAAO,EACL,cAAc,EACd,KAAK,qBAAqB,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,KAAK,wBAAwB,EAC7B,qBAAqB,EACrB,KAAK,0BAA0B,GAChC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EACL,KAAK,yBAAyB,EAC9B,2BAA2B,EAC3B,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,qBAAqB,EACrB,KAAK,4BAA4B,EACjC,KAAK,wBAAwB,EAC7B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kBAAkB,EAClB,aAAa,EACb,yBAAyB,EACzB,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,WAAW,EACX,uBAAuB,EACvB,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,gBAAgB;AAChB,eAAO,MAAM,2BAA2B,OAAO,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,wBAAwB,CAAC;AAEhC,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AACrF,OAAO,EACL,cAAc,EACd,KAAK,qBAAqB,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,KAAK,wBAAwB,EAC7B,qBAAqB,EACrB,KAAK,0BAA0B,GAChC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EACL,KAAK,yBAAyB,EAC9B,2BAA2B,EAC3B,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,qBAAqB,EACrB,KAAK,4BAA4B,EACjC,KAAK,wBAAwB,EAC7B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kBAAkB,EAClB,aAAa,EACb,yBAAyB,EACzB,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,WAAW,EACX,uBAAuB,EACvB,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,gBAAgB;AAChB,eAAO,MAAM,2BAA2B,OAAO,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { APP_PROMPT_SCOPE_ID } from "./types.js";
2
- import { ObjectRegistry, RuntimeError, SmrtCollection, SmrtObject, field, smrt } from "@happyvertical/smrt-core";
2
+ import { INFERENCE_TIERS, ObjectRegistry, RuntimeError, SmrtCollection, SmrtObject, field, isInferenceTier, isInferenceTierRequest, smrt } from "@happyvertical/smrt-core";
3
3
  import { getPackageConfig } from "@happyvertical/smrt-config";
4
4
  import { getTenantId } from "@happyvertical/smrt-tenancy";
5
5
  //#region \0rolldown/runtime.js
@@ -15,7 +15,7 @@ var __exportAll = (all, no_symbols) => {
15
15
  };
16
16
  //#endregion
17
17
  //#region src/__smrt-register__.ts
18
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-prompts","packageVersion":"0.60.14","objects":{"@happyvertical/smrt-prompts:PromptOverrideCollection":{"name":"promptoverridecollection","className":"PromptOverrideCollection","qualifiedName":"@happyvertical/smrt-prompts:PromptOverrideCollection","collection":"promptoverrides","filePath":"/home/runner/work/smrt/smrt/packages/prompts/src/collections/PromptOverrideCollection.ts","packageName":"@happyvertical/smrt-prompts","fields":{},"methods":{"getAppOverride":{"name":"getAppOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"getTenantOverride":{"name":"getTenantOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"getResolutionLayers":{"name":"getResolutionLayers","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<object>","isStatic":false,"isPublic":true},"getOverrideMapForKeys":{"name":"getOverrideMapForKeys","async":true,"parameters":[{"name":"keys","type":"string[]","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<Map<string, PromptOverride>>","isStatic":false,"isPublic":true},"findByScope":{"name":"findByScope","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"setTemplateOverride":{"name":"setTemplateOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false},{"name":"template","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<PromptOverride>","isStatic":false,"isPublic":true},"removeOverride":{"name":"removeOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_prompt_overrides","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PromptOverride","exportName":"PromptOverrideCollection","collectionExportName":"PromptOverrideCollectionCollection","collectionOf":"@happyvertical/smrt-prompts:PromptOverride","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_prompt_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_prompt_overrides\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"key\\" TEXT NOT NULL DEFAULT '',\\n \\"tenant_id\\" UUID,\\n \\"template\\" TEXT,\\n \\"profile\\" TEXT,\\n \\"model\\" TEXT,\\n \\"params\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"key":{"type":"TEXT","notNull":true,"unique":false,"default":""},"tenant_id":{"type":"UUID","notNull":false,"unique":false},"template":{"type":"TEXT","notNull":false,"unique":false},"profile":{"type":"TEXT","notNull":false,"unique":false},"model":{"type":"TEXT","notNull":false,"unique":false},"params":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_prompt_overrides_key_context_idx","columns":["key","context"],"unique":true},{"name":"_smrt_prompt_overrides_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_prompt_overrides_created_at_idx","columns":["created_at"]}],"version":"3fcceb69"},"importPath":"@happyvertical/smrt-prompts"},"@happyvertical/smrt-prompts:PromptOverride":{"name":"promptoverride","className":"PromptOverride","qualifiedName":"@happyvertical/smrt-prompts:PromptOverride","collection":"promptoverrides","filePath":"/home/runner/work/smrt/smrt/packages/prompts/src/models/PromptOverride.ts","packageName":"@happyvertical/smrt-prompts","fields":{"key":{"type":"text","required":true,"default":"","_meta":{"required":true}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true}},"template":{"type":"text","required":false,"_meta":{"nullable":true}},"profile":{"type":"text","required":false,"_meta":{"nullable":true}},"model":{"type":"text","required":false,"_meta":{"nullable":true}},"params":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{"getParams":{"name":"getParams","async":false,"parameters":[],"returnType":"PromptParams","isStatic":false,"isPublic":true},"setParams":{"name":"setParams","async":false,"parameters":[{"name":"params","type":"PromptParams | null","optional":false,"unionBranches":[{"type":"PromptParams"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"toPromptLayer":{"name":"toPromptLayer","async":false,"parameters":[],"returnType":"PromptLayer","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_prompt_overrides","conflictColumns":["key","context"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"PromptOverride","collectionExportName":"PromptOverrideCollection","validationRules":[{"field":"key","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_prompt_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_prompt_overrides\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"key\\" TEXT NOT NULL DEFAULT '',\\n \\"tenant_id\\" UUID,\\n \\"template\\" TEXT,\\n \\"profile\\" TEXT,\\n \\"model\\" TEXT,\\n \\"params\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"key":{"type":"TEXT","notNull":true,"unique":false,"default":""},"tenant_id":{"type":"UUID","notNull":false,"unique":false},"template":{"type":"TEXT","notNull":false,"unique":false},"profile":{"type":"TEXT","notNull":false,"unique":false},"model":{"type":"TEXT","notNull":false,"unique":false},"params":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_prompt_overrides_key_context_idx","columns":["key","context"],"unique":true},{"name":"_smrt_prompt_overrides_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_prompt_overrides_created_at_idx","columns":["created_at"]}],"version":"3fcceb69"},"importPath":"@happyvertical/smrt-prompts"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624"],"via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
18
+ ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-prompts","packageVersion":"0.60.16","objects":{"@happyvertical/smrt-prompts:PromptOverrideCollection":{"name":"promptoverridecollection","className":"PromptOverrideCollection","qualifiedName":"@happyvertical/smrt-prompts:PromptOverrideCollection","collection":"promptoverrides","filePath":"/home/runner/work/smrt/smrt/packages/prompts/src/collections/PromptOverrideCollection.ts","packageName":"@happyvertical/smrt-prompts","fields":{},"methods":{"getAppOverride":{"name":"getAppOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"getTenantOverride":{"name":"getTenantOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"getResolutionLayers":{"name":"getResolutionLayers","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<object>","isStatic":false,"isPublic":true},"getOverrideMapForKeys":{"name":"getOverrideMapForKeys","async":true,"parameters":[{"name":"keys","type":"string[]","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<Map<string, PromptOverride>>","isStatic":false,"isPublic":true},"findByScope":{"name":"findByScope","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<PromptOverride | null>","isStatic":false,"isPublic":true},"setTemplateOverride":{"name":"setTemplateOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false},{"name":"template","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<PromptOverride>","isStatic":false,"isPublic":true},"removeOverride":{"name":"removeOverride","async":true,"parameters":[{"name":"key","type":"string","optional":false},{"name":"scopeType","type":"PromptOverrideScopeType","optional":false},{"name":"scopeId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_prompt_overrides","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PromptOverride","exportName":"PromptOverrideCollection","collectionExportName":"PromptOverrideCollectionCollection","collectionOf":"@happyvertical/smrt-prompts:PromptOverride","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_prompt_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_prompt_overrides\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"key\\" TEXT NOT NULL DEFAULT '',\\n \\"tenant_id\\" UUID,\\n \\"template\\" TEXT,\\n \\"profile\\" TEXT,\\n \\"model\\" TEXT,\\n \\"params\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"key":{"type":"TEXT","notNull":true,"unique":false,"default":""},"tenant_id":{"type":"UUID","notNull":false,"unique":false},"template":{"type":"TEXT","notNull":false,"unique":false},"profile":{"type":"TEXT","notNull":false,"unique":false},"model":{"type":"TEXT","notNull":false,"unique":false},"params":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_prompt_overrides_key_context_idx","columns":["key","context"],"unique":true},{"name":"_smrt_prompt_overrides_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_prompt_overrides_created_at_idx","columns":["created_at"]}],"version":"3fcceb69"},"importPath":"@happyvertical/smrt-prompts"},"@happyvertical/smrt-prompts:PromptOverride":{"name":"promptoverride","className":"PromptOverride","qualifiedName":"@happyvertical/smrt-prompts:PromptOverride","collection":"promptoverrides","filePath":"/home/runner/work/smrt/smrt/packages/prompts/src/models/PromptOverride.ts","packageName":"@happyvertical/smrt-prompts","fields":{"key":{"type":"text","required":true,"default":"","_meta":{"required":true}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true}},"template":{"type":"text","required":false,"_meta":{"nullable":true}},"profile":{"type":"text","required":false,"_meta":{"nullable":true}},"model":{"type":"text","required":false,"_meta":{"nullable":true}},"params":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{"getParams":{"name":"getParams","async":false,"parameters":[],"returnType":"PromptParams","isStatic":false,"isPublic":true},"setParams":{"name":"setParams","async":false,"parameters":[{"name":"params","type":"PromptParams | null","optional":false,"unionBranches":[{"type":"PromptParams"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"toPromptLayer":{"name":"toPromptLayer","async":false,"parameters":[],"returnType":"PromptLayer","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_prompt_overrides","conflictColumns":["key","context"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"PromptOverride","collectionExportName":"PromptOverrideCollection","validationRules":[{"field":"key","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_prompt_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_prompt_overrides\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"key\\" TEXT NOT NULL DEFAULT '',\\n \\"tenant_id\\" UUID,\\n \\"template\\" TEXT,\\n \\"profile\\" TEXT,\\n \\"model\\" TEXT,\\n \\"params\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"key":{"type":"TEXT","notNull":true,"unique":false,"default":""},"tenant_id":{"type":"UUID","notNull":false,"unique":false},"template":{"type":"TEXT","notNull":false,"unique":false},"profile":{"type":"TEXT","notNull":false,"unique":false},"model":{"type":"TEXT","notNull":false,"unique":false},"params":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_prompt_overrides_key_context_idx","columns":["key","context"],"unique":true},{"name":"_smrt_prompt_overrides_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_prompt_overrides_created_at_idx","columns":["created_at"]}],"version":"3fcceb69"},"importPath":"@happyvertical/smrt-prompts"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624"],"via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
19
19
  //#endregion
20
20
  //#region src/cache.ts
21
21
  var PROMPT_CACHE_TTL_MS = 3e4;
@@ -125,7 +125,11 @@ var AI_ROUTING_PARAM_KEYS = /* @__PURE__ */ new Set([
125
125
  "provider",
126
126
  "type",
127
127
  "model",
128
- "defaultModel"
128
+ "defaultModel",
129
+ "tier",
130
+ "latency",
131
+ "promptKey",
132
+ "minimumTier"
129
133
  ]);
130
134
  function isPlainObject(value) {
131
135
  return !!value && typeof value === "object" && !Array.isArray(value);
@@ -171,9 +175,13 @@ function normalizeAIInput(ai) {
171
175
  if (!isPlainObject(ai)) return { params: {} };
172
176
  const profile = typeof ai.profile === "string" || ai.profile === null ? ai.profile : void 0;
173
177
  const model = typeof ai.model === "string" || ai.model === null ? ai.model : void 0;
178
+ if (ai.minimumTier !== void 0 && !isInferenceTier(ai.minimumTier)) throw new Error(`Prompt ai.minimumTier must be one of ${INFERENCE_TIERS.join(", ")}; got "${String(ai.minimumTier)}".`);
179
+ const latency = ai.latency === "interactive" || ai.latency === "background" ? ai.latency : void 0;
174
180
  return {
175
181
  profile: profile ?? void 0,
176
182
  model: model ?? void 0,
183
+ ...latency ? { latency } : {},
184
+ ...ai.minimumTier ? { minimumTier: ai.minimumTier } : {},
177
185
  params: extractPromptParams(ai, AI_RESERVED_KEYS)
178
186
  };
179
187
  }
@@ -230,25 +238,28 @@ function validateProfileName(profileName, config) {
230
238
  if (profileName.trim() === "") throw new Error("Prompt profile names cannot be empty");
231
239
  const allowedProfileNames = config.allowedProfileNames;
232
240
  if (Array.isArray(allowedProfileNames) && !allowedProfileNames.includes(profileName)) throw new Error(`Prompt profile "${profileName}" is not in the allowed profile list`);
233
- if (!config.profiles?.[profileName]) throw new Error(`Prompt profile "${profileName}" is not configured`);
241
+ if (!config.profiles?.[profileName] && !isInferenceTierRequest(profileName)) throw new Error(`Prompt profile "${profileName}" is not configured`);
234
242
  }
235
243
  function validateModelName(modelName, config) {
236
244
  if (modelName.trim() === "") throw new Error("Prompt model overrides cannot be empty");
237
245
  const allowedModels = config.allowedModels;
238
246
  if (Array.isArray(allowedModels) && !allowedModels.includes(modelName)) throw new Error(`Prompt model "${modelName}" is not in the allowed model list`);
239
247
  }
240
- function buildResolvedAI(ai, config) {
248
+ function buildResolvedAI(ai, config, options = {}) {
241
249
  let provider;
242
250
  let model = ai.model;
243
251
  let params = ai.params;
252
+ let tier;
244
253
  if (ai.profile) {
245
- validateProfileName(ai.profile, config);
254
+ if (!(ai.profile === options.defaultProfile && !config.profiles?.[ai.profile] && isInferenceTierRequest(ai.profile))) validateProfileName(ai.profile, config);
246
255
  const configuredProfile = config.profiles?.[ai.profile];
247
- if (!configuredProfile) throw new Error(`Prompt profile "${ai.profile}" is not configured`);
248
- const profileConfig = normalizeProfileConfig(configuredProfile);
249
- provider = profileConfig.provider;
250
- model = model ?? profileConfig.model;
251
- params = mergePromptParams(profileConfig.params, params);
256
+ if (configuredProfile) {
257
+ const profileConfig = normalizeProfileConfig(configuredProfile);
258
+ provider = profileConfig.provider;
259
+ model = model ?? profileConfig.model;
260
+ params = mergePromptParams(profileConfig.params, params);
261
+ } else if (isInferenceTierRequest(ai.profile)) tier = ai.profile;
262
+ else throw new Error(`Prompt profile "${ai.profile}" is not configured`);
252
263
  }
253
264
  if (ai.model) validateModelName(ai.model, config);
254
265
  if (ai.model && !ai.profile) throw new Error("Direct prompt model overrides require an effective prompt profile");
@@ -258,6 +269,7 @@ function buildResolvedAI(ai, config) {
258
269
  profile: ai.profile,
259
270
  provider,
260
271
  model,
272
+ ...tier ? { tier } : {},
261
273
  ...config.allowedModels ? { allowedModels: [...config.allowedModels] } : {},
262
274
  params
263
275
  };
@@ -265,6 +277,55 @@ function buildResolvedAI(ai, config) {
265
277
  if (typeof params.maxTokens === "number") resolved.maxTokens = params.maxTokens;
266
278
  return resolved;
267
279
  }
280
+ var TEMPLATE_HASH_LENGTH = 12;
281
+ async function promptTemplateHash(template) {
282
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(template));
283
+ let hex = "";
284
+ for (const byte of new Uint8Array(digest)) {
285
+ hex += byte.toString(16).padStart(2, "0");
286
+ if (hex.length >= TEMPLATE_HASH_LENGTH) break;
287
+ }
288
+ return hex.slice(0, TEMPLATE_HASH_LENGTH);
289
+ }
290
+ function promptMessageOptions(ai, extra = {}) {
291
+ const { tier: _tier, latency: _latency, promptKey: _promptKey, usageTags: paramTags, ...params } = ai.params || {};
292
+ const routeTier = extra.routeTier !== false;
293
+ const usageTags = {
294
+ ...paramUsageTags(paramTags),
295
+ ...ai.usageTags ?? {},
296
+ ...extra.usageTags ?? {}
297
+ };
298
+ return {
299
+ ...params,
300
+ ...ai.model ? { model: ai.model } : {},
301
+ ...routeTier && ai.tier ? { tier: ai.tier } : {},
302
+ ...routeTier && ai.tier && ai.promptKey ? { promptKey: ai.promptKey } : {},
303
+ ...routeTier && ai.tier && ai.latency ? { latency: ai.latency } : {},
304
+ ...routeTier && ai.tier && ai.minimumTier ? { minimumTier: ai.minimumTier } : {},
305
+ ...typeof ai.temperature === "number" ? { temperature: ai.temperature } : {},
306
+ ...typeof ai.maxTokens === "number" ? { maxTokens: ai.maxTokens } : {},
307
+ ...Object.keys(usageTags).length > 0 ? { usageTags } : {}
308
+ };
309
+ }
310
+ var RESERVED_USAGE_TAGS = /* @__PURE__ */ new Set([
311
+ "promptKey",
312
+ "promptLayer",
313
+ "templateHash",
314
+ "runId",
315
+ "tierRequested",
316
+ "tierResolved",
317
+ "substitutions",
318
+ "fusionKey"
319
+ ]);
320
+ function paramUsageTags(value) {
321
+ if (!isPlainObject(value)) return {};
322
+ const tags = {};
323
+ for (const [key, tag] of Object.entries(value)) {
324
+ if (RESERVED_USAGE_TAGS.has(key)) continue;
325
+ if (tag !== void 0 && tag !== null) tags[key] = String(tag);
326
+ }
327
+ return tags;
328
+ }
268
329
  function renderPromptTemplate(template, variables) {
269
330
  if (!variables || Object.keys(variables).length === 0) return template;
270
331
  return template.replace(/\{([^{}]+)\}/g, (_match, rawKey) => {
@@ -707,6 +768,12 @@ var PromptOverrideService = class {
707
768
  };
708
769
  //#endregion
709
770
  //#region src/prompt-resolver.ts
771
+ function suppliesTemplate(layer) {
772
+ return layer?.template !== void 0 && layer.template !== null;
773
+ }
774
+ function suppliesProfile(layer) {
775
+ return layer?.profile !== void 0 && layer.profile !== null;
776
+ }
710
777
  function getPromptConfig$1() {
711
778
  return getPackageConfig("prompts", {
712
779
  profiles: {},
@@ -729,20 +796,40 @@ async function loadPromptBase(key, options) {
729
796
  const loadedAtGeneration = getPromptCacheGeneration(key, cacheDb);
730
797
  const config = getPromptConfig$1();
731
798
  const layers = [{
732
- template: definition.template,
733
- profile: definition.ai.profile ?? null,
734
- model: definition.ai.model ?? null,
735
- params: definition.ai.params
736
- }, normalizePromptLayer(config.prompts?.[key])];
799
+ name: "default",
800
+ layer: {
801
+ template: definition.template,
802
+ profile: definition.ai.profile ?? null,
803
+ model: definition.ai.model ?? null,
804
+ params: definition.ai.params
805
+ }
806
+ }, {
807
+ name: "config",
808
+ layer: normalizePromptLayer(config.prompts?.[key])
809
+ }];
737
810
  if (collection) {
738
811
  const stored = await collection.getResolutionLayers(key, tenantId);
739
- if (stored.app) layers.push(stored.app.toPromptLayer());
740
- if (stored.tenant) layers.push(stored.tenant.toPromptLayer());
812
+ if (stored.app) layers.push({
813
+ name: "app",
814
+ layer: stored.app.toPromptLayer()
815
+ });
816
+ if (stored.tenant) layers.push({
817
+ name: "tenant",
818
+ layer: stored.tenant.toPromptLayer()
819
+ });
820
+ }
821
+ const merged = mergePromptLayers(...layers.map(({ layer }) => layer));
822
+ let templateLayer = "default";
823
+ let profileLayer = "default";
824
+ for (const { name, layer } of layers) {
825
+ if (suppliesTemplate(layer)) templateLayer = name;
826
+ if (suppliesProfile(layer)) profileLayer = name;
741
827
  }
742
- const merged = mergePromptLayers(...layers);
743
828
  const value = {
744
829
  key,
745
830
  template: merged.template,
831
+ templateLayer,
832
+ profileLayer,
746
833
  ai: merged.ai
747
834
  };
748
835
  setCachedPromptBase(key, tenantId, cacheDb, value, loadedAtGeneration);
@@ -758,11 +845,28 @@ async function resolvePrompt(key, options = {}) {
758
845
  model: base.ai.model ?? null,
759
846
  params: base.ai.params
760
847
  }, runtimeOverride);
848
+ const promptLayer = suppliesTemplate(runtimeOverride) ? "runtime" : base.templateLayer;
849
+ const profileFromDefault = base.profileLayer === "default" && !suppliesProfile(runtimeOverride);
850
+ const ai = buildResolvedAI(merged.ai, config, { defaultProfile: profileFromDefault ? PromptRegistry.get(key)?.ai.profile : void 0 });
851
+ if (ai.tier) {
852
+ ai.promptKey = key;
853
+ const latency = PromptRegistry.get(key)?.ai.latency;
854
+ if (latency) ai.latency = latency;
855
+ const minimumTier = PromptRegistry.get(key)?.ai.minimumTier;
856
+ if (minimumTier) ai.minimumTier = minimumTier;
857
+ }
761
858
  return {
762
859
  key,
763
860
  template: merged.template,
764
861
  text: renderPromptTemplate(merged.template, options.variables),
765
- ai: buildResolvedAI(merged.ai, config)
862
+ ai: {
863
+ ...ai,
864
+ usageTags: {
865
+ promptKey: key,
866
+ promptLayer,
867
+ templateHash: await promptTemplateHash(merged.template)
868
+ }
869
+ }
766
870
  };
767
871
  }
768
872
  //#endregion
@@ -933,6 +1037,6 @@ var PromptSettingsService = class PromptSettingsService {
933
1037
  //#region src/index.ts
934
1038
  var PACKAGE_VERSION_INITIALIZED = true;
935
1039
  //#endregion
936
- export { APP_PROMPT_SCOPE_ID, InvalidPromptScopeError, PACKAGE_VERSION_INITIALIZED, PromptFieldNotEditableError, PromptOverride, PromptOverrideAuthorizationError, PromptOverrideCollection, PromptOverrideService, PromptRegistry, PromptSettingsService, UnknownPromptKeyError, clearPromptCache, definePrompt, getPromptCacheTtlMs, resolvePrompt };
1040
+ export { APP_PROMPT_SCOPE_ID, InvalidPromptScopeError, PACKAGE_VERSION_INITIALIZED, PromptFieldNotEditableError, PromptOverride, PromptOverrideAuthorizationError, PromptOverrideCollection, PromptOverrideService, PromptRegistry, PromptSettingsService, UnknownPromptKeyError, clearPromptCache, definePrompt, getPromptCacheTtlMs, promptMessageOptions, promptTemplateHash, resolvePrompt };
937
1041
 
938
1042
  //# sourceMappingURL=index.js.map