@happyvertical/smrt-prompts 0.74.1 → 0.74.3

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
@@ -18,10 +18,36 @@ SMRT prompt registry and tenant-aware prompt override package. Code defines defa
18
18
  2. File/config override — `getPackageConfig<PromptPackageConfig>('prompts', defaults)`
19
19
  3. App-level stored override — `PromptOverride` row with `tenantId = null`
20
20
  4. Tenant-level stored override — `PromptOverride` row with current tenant
21
- 5. Runtime override — passed to `resolvePrompt({ overrides })`
21
+ 5. Ambient scoped override (#5065) — `withPromptOverrides({ [key]: layer }, fn)`
22
+ 6. Runtime override — passed to `resolvePrompt(key, { override })`
22
23
 
23
24
  Each layer can override any subset of fields (template, profile, model, params). Inheritance is field-by-field.
24
25
 
26
+ ## Scoped ambient override (#5065)
27
+
28
+ `withPromptOverrides(overrides, fn)` (`prompt-resolver.ts`, store in
29
+ `scoped-overrides.ts`) runs `fn` so every `resolvePrompt()` inside it, with no
30
+ `override` argument, applies `overrides[key]` as a layer between stored tenant
31
+ overrides and the explicit `options.override` (which wins field by field). It is
32
+ what lets a prompt arena run a draft through the app's real method. Facts:
33
+
34
+ - Applied in `resolvePrompt()` after `loadPromptBase()`, so a draft never
35
+ reaches the prompt cache; a template from it is tagged `promptLayer:
36
+ 'runtime'` with the draft's `templateHash`.
37
+ - Backed by core's `createAsyncContext()` (public from core), stored on
38
+ `Symbol.for('smrt.prompts.scopedOverrides')` on `globalThis` so duplicated
39
+ module instances share it. Nested scopes: inner wins per key (whole layer),
40
+ outer keys stay visible.
41
+ - Host opt-in, default off: `allowScopedOverrides: true` in the `prompts`
42
+ package config; otherwise opening a scope throws. It also throws when the
43
+ runtime's async context does not propagate across `await` (browsers), since
44
+ a no-op would run and record the live template as the draft. Authorization
45
+ stays with the host.
46
+ - `allowedProfileNames`, `allowedModels` and effort validation apply exactly as
47
+ to `options.override` (effort is validated when the scope opens).
48
+ - It follows `await` in the same async tree only. Work enqueued as a job runs
49
+ outside the scope and resolves the live template.
50
+
25
51
  ## Conventions
26
52
 
27
53
  - **Namespace prompt keys** by package or domain: `projects.issue.incorporateFeedback`, `content.summarize.headline`
package/README.md CHANGED
@@ -38,7 +38,7 @@ const resolved = await resolvePrompt('projects.issue.incorporateFeedback', {
38
38
  ## What this package provides
39
39
 
40
40
  - **`definePrompt()`** — code-first prompt registration in a global process registry
41
- - **`resolvePrompt()`** — layered resolution: code default → config override → stored app override → stored tenant override → runtime override
41
+ - **`resolvePrompt()`** — layered resolution: code default → config override → stored app override → stored tenant override → scoped ambient override (`withPromptOverrides()`, host opt-in via `allowScopedOverrides`, does not follow jobs) → explicit `override`
42
42
  - **`PromptOverride`** — model for app-level and tenant-level prompt settings, stored in `_smrt_prompt_overrides`
43
43
  - **`PromptOverrideService`** / **`PromptSettingsService`** — the authorized write path and the read/write helper for a management screen (see "Management UI" below)
44
44
  - **Named AI profiles** loaded from `packages.prompts` config — prompts select profile names, profiles resolve to provider/model in config
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ export { PromptOverrideCollection } from './collections/PromptOverrideCollection
12
12
  export { PromptOverride, type PromptOverrideOptions, } from './models/PromptOverride.js';
13
13
  export { InvalidPromptScopeError, PromptOverrideAuthorizationError, type PromptOverrideAuthorizer, PromptOverrideService, type PromptOverrideWriteRequest, } from './prompt-override-service.js';
14
14
  export { definePrompt, PromptRegistry } from './prompt-registry.js';
15
- export { resolvePrompt } from './prompt-resolver.js';
15
+ export { resolvePrompt, withPromptOverrides } 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
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';
@@ -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,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,oBA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B,EAClB,iBAAiB,GAClB,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 { INFERENCE_TIERS, ObjectRegistry, REASONING_EFFORTS, RuntimeError, SmrtCollection, SmrtObject, field, isInferenceTier, isInferenceTierRequest, isReasoningEffort, smrt } from "@happyvertical/smrt-core";
2
+ import { INFERENCE_TIERS, ObjectRegistry, REASONING_EFFORTS, RuntimeError, SmrtCollection, SmrtObject, createAsyncContext, field, isInferenceTier, isInferenceTierRequest, isReasoningEffort, 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.74.1","objects":{"@happyvertical/smrt-prompts:PromptOverrideCollection":{"name":"promptoverridecollection","className":"PromptOverrideCollection","qualifiedName":"@happyvertical/smrt-prompts:PromptOverrideCollection","collection":"promptoverrides","filePath":"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":"src/models/PromptOverride.ts","packageName":"@happyvertical/smrt-prompts","fields":{"key":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"tenantId":{"type":"text","_meta":{"__statedOptions":["sqlType","nullable","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"template":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"profile":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"model":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"params":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"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.74.3","objects":{"@happyvertical/smrt-prompts:PromptOverrideCollection":{"name":"promptoverridecollection","className":"PromptOverrideCollection","qualifiedName":"@happyvertical/smrt-prompts:PromptOverrideCollection","collection":"promptoverrides","filePath":"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":"src/models/PromptOverride.ts","packageName":"@happyvertical/smrt-prompts","fields":{"key":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"tenantId":{"type":"text","_meta":{"__statedOptions":["sqlType","nullable","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"template":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"profile":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"model":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"params":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"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;
@@ -802,6 +802,25 @@ var PromptOverrideService = class {
802
802
  }
803
803
  };
804
804
  //#endregion
805
+ //#region src/scoped-overrides.ts
806
+ var STORAGE = /* @__PURE__ */ Symbol.for("smrt.prompts.scopedOverrides");
807
+ var shared = globalThis;
808
+ function context() {
809
+ shared[STORAGE] ??= createAsyncContext();
810
+ return shared[STORAGE];
811
+ }
812
+ function scopedOverridesPropagate() {
813
+ return context().propagatesAcrossAwait;
814
+ }
815
+ function runWithScopedOverrides(overrides, fn) {
816
+ const merged = new Map(context().getStore());
817
+ for (const [key, override] of Object.entries(overrides)) merged.set(key, { ...override });
818
+ return context().run(merged, fn);
819
+ }
820
+ function getScopedPromptOverride(key) {
821
+ return context().getStore()?.get(key);
822
+ }
823
+ //#endregion
805
824
  //#region src/prompt-resolver.ts
806
825
  function suppliesTemplate(layer) {
807
826
  return layer?.template !== void 0 && layer.template !== null;
@@ -874,16 +893,17 @@ async function loadPromptBase(key, options) {
874
893
  async function resolvePrompt(key, options = {}) {
875
894
  const config = getPromptConfig$1();
876
895
  const base = await loadPromptBase(key, options);
877
- const runtimeOverride = normalizePromptLayer(options.override);
896
+ const ambientOverride = normalizePromptLayer(getScopedPromptOverride(key));
897
+ const explicitOverride = normalizePromptLayer(options.override);
878
898
  const merged = mergePromptLayers({
879
899
  template: base.template,
880
900
  profile: base.ai.profile ?? null,
881
901
  model: base.ai.model ?? null,
882
902
  effort: base.ai.effort ?? null,
883
903
  params: base.ai.params
884
- }, runtimeOverride);
885
- const promptLayer = suppliesTemplate(runtimeOverride) ? "runtime" : base.templateLayer;
886
- const profileFromDefault = base.profileLayer === "default" && !suppliesProfile(runtimeOverride);
904
+ }, ambientOverride, explicitOverride);
905
+ const promptLayer = suppliesTemplate(ambientOverride) || suppliesTemplate(explicitOverride) ? "runtime" : base.templateLayer;
906
+ const profileFromDefault = base.profileLayer === "default" && !suppliesProfile(ambientOverride) && !suppliesProfile(explicitOverride);
887
907
  const ai = buildResolvedAI(merged.ai, config, { defaultProfile: profileFromDefault ? PromptRegistry.get(key)?.ai.profile : void 0 });
888
908
  if (ai.tier) {
889
909
  ai.promptKey = key;
@@ -906,6 +926,12 @@ async function resolvePrompt(key, options = {}) {
906
926
  }
907
927
  };
908
928
  }
929
+ function withPromptOverrides(overrides, fn) {
930
+ if (getPromptConfig$1().allowScopedOverrides !== true) throw new Error("withPromptOverrides() is disabled: set `allowScopedOverrides: true` in the \"prompts\" package config to opt in");
931
+ if (!scopedOverridesPropagate()) throw new Error("withPromptOverrides() needs async context that survives await, which this runtime does not provide");
932
+ for (const override of Object.values(overrides)) normalizePromptLayer(override);
933
+ return runWithScopedOverrides(overrides, fn);
934
+ }
909
935
  //#endregion
910
936
  //#region src/prompt-settings.ts
911
937
  function getPromptConfig() {
@@ -1075,6 +1101,6 @@ var PromptSettingsService = class PromptSettingsService {
1075
1101
  //#region src/index.ts
1076
1102
  var PACKAGE_VERSION_INITIALIZED = true;
1077
1103
  //#endregion
1078
- export { APP_PROMPT_SCOPE_ID, InvalidPromptScopeError, PACKAGE_VERSION_INITIALIZED, PromptFieldNotEditableError, PromptOverride, PromptOverrideAuthorizationError, PromptOverrideCollection, PromptOverrideService, PromptRegistry, PromptSettingsService, UnknownPromptKeyError, clearPromptCache, definePrompt, getPromptCacheTtlMs, promptMessageOptions, promptTemplateHash, resolvePrompt, trackedPromptCall };
1104
+ export { APP_PROMPT_SCOPE_ID, InvalidPromptScopeError, PACKAGE_VERSION_INITIALIZED, PromptFieldNotEditableError, PromptOverride, PromptOverrideAuthorizationError, PromptOverrideCollection, PromptOverrideService, PromptRegistry, PromptSettingsService, UnknownPromptKeyError, clearPromptCache, definePrompt, getPromptCacheTtlMs, promptMessageOptions, promptTemplateHash, resolvePrompt, trackedPromptCall, withPromptOverrides };
1079
1105
 
1080
1106
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/cache.ts","../src/utils.ts","../src/prompt-registry.ts","../src/models/PromptOverride.ts","../src/collections/PromptOverrideCollection.ts","../src/prompt-override-service.ts","../src/prompt-resolver.ts","../src/prompt-settings.ts","../src/index.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-prompts\\\",\\\"packageVersion\\\":\\\"0.74.1\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-prompts:PromptOverrideCollection\\\":{\\\"name\\\":\\\"promptoverridecollection\\\",\\\"className\\\":\\\"PromptOverrideCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-prompts:PromptOverrideCollection\\\",\\\"collection\\\":\\\"promptoverrides\\\",\\\"filePath\\\":\\\"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\\\":\\\"src/models/PromptOverride.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-prompts\\\",\\\"fields\\\":{\\\"key\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"default\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true,\\\"default\\\":\\\"\\\"},\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"template\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"profile\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"model\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"params\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"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}\"));\n","import type { DatabaseInterface } from '@happyvertical/sql';\nimport type { PromptCacheValue } from './types.js';\n\nconst PROMPT_CACHE_TTL_MS = 30_000;\n\ntype CacheEntry = {\n expiresAt: number;\n value: PromptCacheValue;\n};\n\nconst promptCache = new Map<string, CacheEntry>();\n/** Monotonic per-`(db, key)` invalidation counter; see getPromptCacheGeneration. */\nconst cacheGenerations = new Map<string, number>();\n/**\n * Source of every generation value. Drawing from one counter instead of\n * incrementing each key independently makes a generation unique across every\n * key and every clear, which is what lets `clearedThrough` work as a floor.\n */\nlet nextGeneration = 1;\n/**\n * Floor that `clearPromptCache()` raises for *every* key, including keys with\n * no map entry. A key that has never been invalidated in this process reads as\n * generation 0, so a resolution that captured 0 before a clear would still see\n * 0 after it and write its pre-clear value back — the flush would be silently\n * undone for the rest of the TTL.\n */\nlet clearedThrough = 0;\nconst dbInstanceIds = new WeakMap<object, string>();\nlet nextDbId = 1;\n\nfunction getDbNamespace(db: unknown): string {\n if (!db) {\n return 'no-db';\n }\n\n if (typeof db === 'string') {\n return `db:${db}`;\n }\n\n if (typeof db === 'object') {\n const dbObject = db as Record<string, unknown>;\n if (typeof dbObject.query === 'function') {\n if (!dbInstanceIds.has(dbObject)) {\n dbInstanceIds.set(dbObject, `db-instance:${nextDbId++}`);\n }\n const namespace = dbInstanceIds.get(dbObject);\n if (namespace) {\n return namespace;\n }\n\n return 'db-instance:unknown';\n }\n\n try {\n return `db-config:${JSON.stringify(dbObject)}`;\n } catch {\n return 'db-config:opaque';\n }\n }\n\n return 'db:unknown';\n}\n\nfunction buildCacheKey(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): string {\n return `${getDbNamespace(db)}::${key}::${tenantId ?? 'app'}`;\n}\n\nfunction buildGenerationKey(\n key: string,\n db: DatabaseInterface | unknown,\n): string {\n return `${getDbNamespace(db)}::${key}`;\n}\n\nfunction bumpGeneration(key: string, db: DatabaseInterface | unknown): void {\n cacheGenerations.set(buildGenerationKey(key, db), nextGeneration++);\n}\n\nexport function getPromptCacheTtlMs(): number {\n return PROMPT_CACHE_TTL_MS;\n}\n\nexport function getCachedPromptBase(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): PromptCacheValue | null {\n const cacheKey = buildCacheKey(key, tenantId, db);\n const cached = promptCache.get(cacheKey);\n\n if (!cached) {\n return null;\n }\n\n if (cached.expiresAt <= Date.now()) {\n promptCache.delete(cacheKey);\n return null;\n }\n\n return cached.value;\n}\n\n/**\n * Reads the current invalidation generation for a key.\n *\n * A resolution captures this *before* its asynchronous layer loads and hands\n * it back to {@link setCachedPromptBase}. Any write that lands while those\n * loads are in flight bumps the generation, so the in-flight resolution —\n * which read the pre-write layers — is refused the cache write instead of\n * repopulating the key it just invalidated. Without this, a read that raced a\n * write served the pre-write value for the full TTL, and a raced `delete()`\n * resurrected the deleted override.\n *\n * Tracked per `(db, key)` rather than per `(db, key, tenantId)`: an app-level\n * row is inherited by every tenant, so a write to any scope of a key must\n * invalidate every scope of it. This matches the coarsest fan-out of\n * {@link invalidatePromptCache}.\n *\n * A key with no entry of its own reports the {@link clearPromptCache} floor\n * rather than a bare 0, so a clear refuses in-flight writes for keys that have\n * never been invalidated too.\n */\nexport function getPromptCacheGeneration(\n key: string,\n db: DatabaseInterface | unknown,\n): number {\n const generation = cacheGenerations.get(buildGenerationKey(key, db)) ?? 0;\n return generation > clearedThrough ? generation : clearedThrough;\n}\n\nexport function setCachedPromptBase(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n value: PromptCacheValue,\n loadedAtGeneration: number,\n): void {\n if (getPromptCacheGeneration(key, db) !== loadedAtGeneration) {\n // A write landed while this resolution was loading. Its value is already\n // stale, so drop it rather than poison the key for the whole TTL.\n return;\n }\n\n promptCache.set(buildCacheKey(key, tenantId, db), {\n expiresAt: Date.now() + PROMPT_CACHE_TTL_MS,\n value,\n });\n}\n\n/**\n * Invalidates a cached resolution. An app-level write (tenantId null) clears\n * every tenant's entry for that key, because each tenant inherits from it.\n */\nexport function invalidatePromptCache(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): void {\n const dbNamespace = getDbNamespace(db);\n bumpGeneration(key, db);\n\n if (tenantId !== null && tenantId !== undefined) {\n promptCache.delete(buildCacheKey(key, tenantId, db));\n return;\n }\n\n const keyPrefix = `${dbNamespace}::${key}::`;\n for (const cacheKey of promptCache.keys()) {\n if (cacheKey.startsWith(keyPrefix)) {\n promptCache.delete(cacheKey);\n }\n }\n}\n\nexport function clearPromptCache(): void {\n promptCache.clear();\n // Raise the floor instead of resetting counters: a resolution that started\n // before the clear must be refused its write, and raising a single floor\n // covers keys with no generation entry, which a per-key bump cannot reach.\n // With the floor carrying the refusal, the per-key entries can be dropped.\n clearedThrough = nextGeneration++;\n cacheGenerations.clear();\n}\n","import {\n INFERENCE_TIERS,\n type InferenceLatency,\n type InferenceTierRequest,\n isInferenceTier,\n isInferenceTierRequest,\n isReasoningEffort,\n REASONING_EFFORTS,\n type ReasoningEffort,\n type TrackedPromptCall,\n} from '@happyvertical/smrt-core';\nimport type {\n NormalizedPromptAI,\n PromptAIInput,\n PromptConfigOverrideInput,\n PromptDefinitionInput,\n PromptEditableConfig,\n PromptLayer,\n PromptPackageConfig,\n PromptParams,\n PromptProfileConfig,\n ResolvedPrompt,\n ResolvedPromptAI,\n} from './types.js';\n\nconst DEFAULT_EDITABLE: PromptEditableConfig = {\n template: false,\n profile: false,\n model: false,\n params: false,\n};\n\nconst TOP_LEVEL_RESERVED_KEYS = new Set([\n 'key',\n 'editable',\n 'template',\n 'ai',\n 'profile',\n 'provider',\n 'model',\n 'effort',\n 'params',\n 'temperature',\n 'maxTokens',\n]);\n\nconst AI_RESERVED_KEYS = new Set([\n 'profile',\n 'provider',\n 'model',\n 'effort',\n 'params',\n 'temperature',\n 'maxTokens',\n]);\n\n// `tier` and `promptKey` come only from the resolution (an effective tier\n// profile), never from tenant-editable params, so `allowedProfileNames`\n// cannot be bypassed through params (#4755).\nconst AI_ROUTING_PARAM_KEYS = new Set([\n 'profile',\n 'provider',\n 'type',\n 'model',\n 'defaultModel',\n // Inference tier routing (#4750) comes only from the validated profile;\n // a (tenant-editable) params layer can never pick or spoof it.\n 'tier',\n 'latency',\n 'promptKey',\n // The ladder floor is read from the code default only (#4752).\n 'minimumTier',\n // Reasoning effort is the validated `effort` field (#5005), never an open\n // param a tenant override could widen.\n 'effort',\n 'reasoning',\n]);\n\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function normalizeEditableConfig(\n editable?: Partial<PromptEditableConfig>,\n): PromptEditableConfig {\n return {\n template: editable?.template ?? DEFAULT_EDITABLE.template,\n profile: editable?.profile ?? DEFAULT_EDITABLE.profile,\n model: editable?.model ?? DEFAULT_EDITABLE.model,\n params: editable?.params ?? DEFAULT_EDITABLE.params,\n };\n}\n\nfunction extractPromptParams(\n source: Record<string, unknown>,\n reservedKeys: Set<string>,\n): PromptParams {\n const params: PromptParams = {};\n\n if (isPlainObject(source.params)) {\n Object.assign(params, sanitizePromptParams(source.params));\n }\n\n if ('temperature' in source && source.temperature !== undefined) {\n params.temperature = source.temperature;\n }\n\n if ('maxTokens' in source && source.maxTokens !== undefined) {\n params.maxTokens = source.maxTokens;\n }\n\n for (const [key, value] of Object.entries(source)) {\n if (reservedKeys.has(key) || value === undefined) {\n continue;\n }\n assignPromptParam(params, key, value);\n }\n\n return params;\n}\n\nfunction assignPromptParam(\n params: PromptParams,\n key: string,\n value: unknown,\n): void {\n if (AI_ROUTING_PARAM_KEYS.has(key) || value === undefined) {\n return;\n }\n\n params[key] = value;\n}\n\nexport function sanitizePromptParams(\n params: PromptParams | null | undefined,\n): PromptParams {\n const sanitized: PromptParams = {};\n\n if (!params) {\n return sanitized;\n }\n\n for (const [key, value] of Object.entries(params)) {\n assignPromptParam(sanitized, key, value);\n }\n\n return sanitized;\n}\n\nexport function mergePromptParams(\n ...paramLayers: Array<PromptParams | null | undefined>\n): PromptParams {\n const merged: PromptParams = {};\n\n for (const layer of paramLayers) {\n if (!layer) {\n continue;\n }\n\n for (const [key, value] of Object.entries(layer)) {\n assignPromptParam(merged, key, value);\n }\n }\n\n return merged;\n}\n\n/**\n * A prompt's reasoning effort: absent, or one of core's `REASONING_EFFORTS`.\n * Anything else throws, naming the allowed values.\n */\nexport function validatePromptEffort(\n value: unknown,\n): ReasoningEffort | undefined {\n if (value === undefined || value === null) return undefined;\n if (!isReasoningEffort(value)) {\n throw new Error(\n `Prompt ai.effort must be one of ${REASONING_EFFORTS.join(', ')}; got \"${String(value)}\".`,\n );\n }\n return value;\n}\n\nfunction normalizeAIInput(ai?: PromptAIInput | null): NormalizedPromptAI {\n if (!isPlainObject(ai)) {\n return { params: {} };\n }\n\n const profile =\n typeof ai.profile === 'string' || ai.profile === null\n ? ai.profile\n : undefined;\n const model =\n typeof ai.model === 'string' || ai.model === null ? ai.model : undefined;\n if (ai.minimumTier !== undefined && !isInferenceTier(ai.minimumTier)) {\n throw new Error(\n `Prompt ai.minimumTier must be one of ${INFERENCE_TIERS.join(', ')}; got \"${String(ai.minimumTier)}\".`,\n );\n }\n\n const latency =\n ai.latency === 'interactive' || ai.latency === 'background'\n ? ai.latency\n : undefined;\n const effort = validatePromptEffort(ai.effort);\n\n return {\n profile: profile ?? undefined,\n model: model ?? undefined,\n ...(latency ? { latency } : {}),\n ...(ai.minimumTier ? { minimumTier: ai.minimumTier } : {}),\n ...(effort ? { effort } : {}),\n params: extractPromptParams(ai, AI_RESERVED_KEYS),\n };\n}\n\nexport function normalizePromptDefinitionInput(input: PromptDefinitionInput): {\n key: string;\n template: string;\n description: string;\n ai: NormalizedPromptAI;\n editable: PromptEditableConfig;\n} {\n return {\n key: input.key,\n template: input.template,\n description: input.description ?? '',\n ai: normalizeAIInput(input.ai),\n editable: normalizeEditableConfig(input.editable),\n };\n}\n\nexport function normalizePromptLayer(\n input?: PromptConfigOverrideInput | null,\n): PromptLayer {\n if (!isPlainObject(input)) {\n return {};\n }\n\n const nestedAi = isPlainObject(input.ai)\n ? normalizeAIInput(input.ai)\n : { params: {} };\n const topLevelParams = extractPromptParams(input, TOP_LEVEL_RESERVED_KEYS);\n\n return {\n template:\n input.template === undefined\n ? undefined\n : input.template === null\n ? null\n : String(input.template),\n profile:\n input.profile === undefined\n ? nestedAi.profile\n : input.profile === null\n ? null\n : String(input.profile),\n model:\n input.model === undefined\n ? nestedAi.model\n : input.model === null\n ? null\n : String(input.model),\n effort:\n input.effort === undefined\n ? nestedAi.effort\n : input.effort === null\n ? null\n : validatePromptEffort(input.effort),\n params: mergePromptParams(topLevelParams, nestedAi.params),\n };\n}\n\nexport function mergePromptLayers(\n ...layers: Array<PromptLayer | null | undefined>\n): {\n template: string;\n ai: NormalizedPromptAI;\n} {\n let template = '';\n let profile: string | undefined;\n let model: string | undefined;\n let effort: ReasoningEffort | undefined;\n let params: PromptParams = {};\n\n for (const layer of layers) {\n if (!layer) {\n continue;\n }\n\n if (layer.template !== undefined && layer.template !== null) {\n template = layer.template;\n }\n\n if (layer.profile !== undefined && layer.profile !== null) {\n profile = layer.profile;\n }\n\n if (layer.model !== undefined && layer.model !== null) {\n model = layer.model;\n }\n\n if (layer.effort !== undefined && layer.effort !== null) {\n effort = validatePromptEffort(layer.effort);\n }\n\n if (layer.params !== undefined && layer.params !== null) {\n params = mergePromptParams(params, layer.params);\n }\n }\n\n return {\n template,\n ai: {\n profile,\n model,\n ...(effort ? { effort } : {}),\n params,\n },\n };\n}\n\nexport function normalizeProfileConfig(profile: PromptProfileConfig): {\n provider: string;\n model: string;\n params: PromptParams;\n} {\n const source = isPlainObject(profile) ? profile : {};\n const params = extractPromptParams(source, new Set(['provider', 'model']));\n\n return {\n provider: String(profile.provider),\n model: String(profile.model),\n params,\n };\n}\n\nexport function validateProfileName(\n profileName: string,\n config: PromptPackageConfig,\n): void {\n if (profileName.trim() === '') {\n throw new Error('Prompt profile names cannot be empty');\n }\n\n const allowedProfileNames = config.allowedProfileNames;\n if (\n Array.isArray(allowedProfileNames) &&\n !allowedProfileNames.includes(profileName)\n ) {\n throw new Error(\n `Prompt profile \"${profileName}\" is not in the allowed profile list`,\n );\n }\n\n // Tier names (and `auto`) are reserved profile names that resolve through\n // the core inference seam (#4750); a same-named configured profile wins.\n if (!config.profiles?.[profileName] && !isInferenceTierRequest(profileName)) {\n throw new Error(`Prompt profile \"${profileName}\" is not configured`);\n }\n}\n\nexport function validateModelName(\n modelName: string,\n config: PromptPackageConfig,\n): void {\n if (modelName.trim() === '') {\n throw new Error('Prompt model overrides cannot be empty');\n }\n\n const allowedModels = config.allowedModels;\n if (Array.isArray(allowedModels) && !allowedModels.includes(modelName)) {\n throw new Error(\n `Prompt model \"${modelName}\" is not in the allowed model list`,\n );\n }\n}\n\nexport function buildResolvedAI(\n ai: NormalizedPromptAI,\n config: PromptPackageConfig,\n options: {\n /**\n * The registered code default's profile (`definePrompt({ ai })`), passed\n * only when no config, stored or runtime layer set a profile.\n */\n defaultProfile?: string;\n } = {},\n): ResolvedPromptAI {\n let provider: string | undefined;\n let model = ai.model;\n let params = ai.params;\n let tier: ResolvedPromptAI['tier'];\n\n if (ai.profile) {\n // `allowedProfileNames` limits what config and stored overrides may\n // select. A tier the code default itself declares (#4755) is not such a\n // choice, so an app's allow-list cannot break framework prompts.\n const codeDefaultTier =\n ai.profile === options.defaultProfile &&\n !config.profiles?.[ai.profile] &&\n isInferenceTierRequest(ai.profile);\n if (!codeDefaultTier) validateProfileName(ai.profile, config);\n const configuredProfile = config.profiles?.[ai.profile];\n if (configuredProfile) {\n const profileConfig = normalizeProfileConfig(configuredProfile);\n provider = profileConfig.provider;\n model = model ?? profileConfig.model;\n params = mergePromptParams(profileConfig.params, params);\n } else if (isInferenceTierRequest(ai.profile)) {\n // Bound later through the core inference seam by `resolvePrompt()`.\n tier = ai.profile;\n } else {\n throw new Error(`Prompt profile \"${ai.profile}\" is not configured`);\n }\n }\n\n if (ai.model) {\n validateModelName(ai.model, config);\n }\n\n if (ai.model && !ai.profile) {\n throw new Error(\n 'Direct prompt model overrides require an effective prompt profile',\n );\n }\n\n if (model && !ai.model && config.allowedModels) {\n validateModelName(model, config);\n }\n\n const resolved: ResolvedPromptAI = {\n ...params,\n profile: ai.profile,\n provider,\n model,\n ...(tier ? { tier } : {}),\n ...(ai.effort ? { effort: ai.effort } : {}),\n ...(config.allowedModels\n ? { allowedModels: [...config.allowedModels] }\n : {}),\n params,\n };\n\n if (typeof params.temperature === 'number') {\n resolved.temperature = params.temperature;\n }\n\n if (typeof params.maxTokens === 'number') {\n resolved.maxTokens = params.maxTokens;\n }\n\n return resolved;\n}\n\nconst TEMPLATE_HASH_LENGTH = 12;\n\n/**\n * Short SHA-256 fingerprint of an effective (unrendered) prompt template: the\n * first 12 lowercase hex characters. Recorded as the `templateHash` usage tag\n * so an override edit starts a new usage series (#4751).\n *\n * Uses Web Crypto (`globalThis.crypto.subtle`), available in Node and every\n * browser, so the package root stays free of `node:crypto`.\n */\nexport async function promptTemplateHash(template: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(template),\n );\n let hex = '';\n for (const byte of new Uint8Array(digest)) {\n hex += byte.toString(16).padStart(2, '0');\n if (hex.length >= TEMPLATE_HASH_LENGTH) break;\n }\n return hex.slice(0, TEMPLATE_HASH_LENGTH);\n}\n\n/** The `ai.message()` options {@link promptMessageOptions} returns. */\nexport interface PromptMessageOptions extends PromptParams {\n model?: string;\n /**\n * Inference tier of a tier profile (#4750). Object call sites pass these\n * options through `SmrtObject.prepareAiOperation()`, which picks the tier\n * client and strips `tier`/`promptKey` before the provider sees them.\n */\n tier?: InferenceTierRequest;\n /** Set with `tier`: the prompt key for the call-time resolver request. */\n promptKey?: string;\n /** Set with `tier`: the code default's `ai.latency` hint (#4755). */\n latency?: InferenceLatency;\n temperature?: number;\n maxTokens?: number;\n /** Degradation floor sent with `tier` (#4752). */\n minimumTier?: ResolvedPromptAI['minimumTier'];\n /** The prompt's effort (#5005). A caller's own `reasoning` wins. */\n reasoning?: { effort: ReasoningEffort };\n usageTags?: Record<string, string>;\n}\n\n/** Extra call options merged by {@link promptMessageOptions}. */\nexport interface PromptMessageOptionsExtra {\n /** The caller's own usage tags; they win over the resolution's tags. */\n usageTags?: Record<string, string>;\n /**\n * `false` omits `tier`/`promptKey` for a call site that sends the options\n * straight to a client it already holds (no `prepareAiOperation()`), so\n * the tier keys never reach a provider; the call runs on that client.\n * Default `true`.\n */\n routeTier?: boolean;\n}\n\n/**\n * Turn a resolved prompt's AI settings into `ai.message()` call options:\n * params, `model`, `temperature`, `maxTokens`, the resolution's\n * `usageTags` (`promptKey`, `promptLayer`, `templateHash`) and, for a tier\n * profile, `tier` + `promptKey` (#4750). Send them through\n * `SmrtObject.prepareAiOperation()` so the tier keys never reach a provider.\n *\n * The prompt's `effort` becomes `reasoning: { effort }` (#5005). Precedence,\n * high to low: the caller's own `reasoning` option (spread after these), the\n * prompt's effort, the tier binding's `params.reasoning` (core spreads a\n * target's params under the call options), the provider's default.\n *\n * Tag precedence, low to high: a `usageTags` object carried in the prompt's\n * params (tenant-editable: reserved tags such as runId or tier tags are\n * dropped from it), the resolution's identity tags, then `extra.usageTags`.\n */\nexport function promptMessageOptions(\n ai: ResolvedPromptAI,\n extra: PromptMessageOptionsExtra = {},\n): PromptMessageOptions {\n // Tier routing keys never ride in on params, even for a hand-built object.\n const {\n tier: _tier,\n latency: _latency,\n promptKey: _promptKey,\n // Never spread raw: only the sanitized copy below may reach the call.\n usageTags: paramTags,\n ...params\n } = ai.params || {};\n const routeTier = extra.routeTier !== false;\n const usageTags = {\n ...paramUsageTags(paramTags),\n ...(ai.usageTags ?? {}),\n ...(extra.usageTags ?? {}),\n };\n return {\n ...params,\n ...(ai.model ? { model: ai.model } : {}),\n ...(routeTier && ai.tier ? { tier: ai.tier } : {}),\n ...(routeTier && ai.tier && ai.promptKey\n ? { promptKey: ai.promptKey }\n : {}),\n ...(routeTier && ai.tier && ai.latency ? { latency: ai.latency } : {}),\n ...(routeTier && ai.tier && ai.minimumTier\n ? { minimumTier: ai.minimumTier }\n : {}),\n ...(typeof ai.temperature === 'number'\n ? { temperature: ai.temperature }\n : {}),\n ...(typeof ai.maxTokens === 'number' ? { maxTokens: ai.maxTokens } : {}),\n ...(ai.effort ? { reasoning: { effort: ai.effort } } : {}),\n ...(Object.keys(usageTags).length > 0 ? { usageTags } : {}),\n };\n}\n\n/**\n * Usage tags that feed indexed columns, tenant checks or report accounting\n * (#4751, #4750, #4752, #4753). A tenant-editable params layer must never\n * set them: a forged `runId` could make another tenant's run look shared and\n * block its outcome labels, and forged tier or substitution tags would skew\n * the report. Only the resolution and the calling code may set these.\n */\nconst RESERVED_USAGE_TAGS = new Set([\n 'promptKey',\n 'promptLayer',\n 'templateHash',\n 'runId',\n 'tierRequested',\n 'tierResolved',\n 'substitutions',\n 'fusionKey',\n]);\n\n/** Free-form tags from params, minus the reserved ones. */\nfunction paramUsageTags(value: unknown): Record<string, string> {\n if (!isPlainObject(value)) return {};\n const tags: Record<string, string> = {};\n for (const [key, tag] of Object.entries(value)) {\n if (RESERVED_USAGE_TAGS.has(key)) continue;\n if (tag !== undefined && tag !== null) tags[key] = String(tag);\n }\n return tags;\n}\n\nexport function renderPromptTemplate(\n template: string,\n variables?: Record<string, unknown>,\n): string {\n if (!variables || Object.keys(variables).length === 0) {\n return template;\n }\n\n return template.replace(/\\{([^{}]+)\\}/g, (_match, rawKey: string) => {\n const key = rawKey.trim();\n const value = variables[key];\n\n if (value === undefined || value === null) {\n return '';\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (Array.isArray(value) || isPlainObject(value)) {\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n }\n\n return String(value);\n });\n}\n\nexport function parsePromptParams(\n raw: string | null | undefined,\n): PromptParams {\n if (!raw) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(raw);\n return isPlainObject(parsed) ? sanitizePromptParams(parsed) : {};\n } catch {\n return {};\n }\n}\n\nexport function serializePromptParams(\n params: PromptParams | null | undefined,\n): string | null {\n if (params === null || params === undefined) {\n return null;\n }\n\n return JSON.stringify(sanitizePromptParams(params));\n}\n\n/**\n * What smrt-core's tracked client takes for a resolved prompt (#5005): the\n * key, the template hash, and the tier, latency and floor the prompt asks\n * for. `resolvePrompt()` is the only place a key comes from, so every tracked\n * call is a call of a registered prompt; core never imports this package.\n *\n * const resolved = await resolvePrompt('chat.assistant.system', { db });\n * const ai = await tracked.client(trackedPromptCall(resolved), { runContext });\n */\nexport function trackedPromptCall(\n resolved: ResolvedPrompt,\n extra: { usageTags?: Record<string, string> } = {},\n): TrackedPromptCall {\n const { ai } = resolved;\n const { promptKey: _key, templateHash, ...tags } = ai.usageTags ?? {};\n return {\n promptKey: resolved.key,\n ...(templateHash ? { templateHash } : {}),\n ...(ai.tier ? { tier: ai.tier } : {}),\n ...(ai.tier && ai.latency ? { latency: ai.latency } : {}),\n ...(ai.tier && ai.minimumTier ? { minimumTier: ai.minimumTier } : {}),\n usageTags: { ...tags, ...(extra.usageTags ?? {}) } as Record<\n string,\n string\n >,\n };\n}\n","import type { PromptDefinition, PromptDefinitionInput } from './types.js';\nimport { normalizePromptDefinitionInput } from './utils.js';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __smrtPromptRegistry: Map<string, PromptDefinition> | undefined;\n}\n\nfunction getRegistry(): Map<string, PromptDefinition> {\n if (!globalThis.__smrtPromptRegistry) {\n globalThis.__smrtPromptRegistry = new Map<string, PromptDefinition>();\n }\n\n return globalThis.__smrtPromptRegistry;\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n return `{${entries\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)\n .join(',')}}`;\n }\n\n return JSON.stringify(value);\n}\n\nexport const PromptRegistry = {\n register(input: PromptDefinitionInput): PromptDefinition {\n if (!input.key || input.key.trim() === '') {\n throw new Error('Prompt definitions require a non-empty key');\n }\n\n const definition = normalizePromptDefinitionInput(input);\n const registry = getRegistry();\n const existing = registry.get(definition.key);\n\n if (existing) {\n const existingSignature = stableStringify(existing);\n const incomingSignature = stableStringify(definition);\n\n if (existingSignature !== incomingSignature) {\n throw new Error(\n `Prompt \"${definition.key}\" is already registered with a different definition`,\n );\n }\n\n return existing;\n }\n\n registry.set(definition.key, definition);\n return definition;\n },\n\n get(key: string): PromptDefinition | undefined {\n return getRegistry().get(key);\n },\n\n has(key: string): boolean {\n return getRegistry().has(key);\n },\n\n getAll(): PromptDefinition[] {\n return Array.from(getRegistry().values());\n },\n\n clear(): void {\n getRegistry().clear();\n },\n};\n\nexport function definePrompt(input: PromptDefinitionInput): PromptDefinition {\n return PromptRegistry.register(input);\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport {\n field,\n RuntimeError,\n SmrtObject,\n type SmrtObjectOptions,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { invalidatePromptCache } from '../cache.js';\nimport { PromptRegistry } from '../prompt-registry.js';\nimport {\n APP_PROMPT_SCOPE_ID,\n type PromptLayer,\n type PromptPackageConfig,\n type PromptParams,\n} from '../types.js';\nimport {\n mergePromptLayers,\n normalizePromptLayer,\n parsePromptParams,\n serializePromptParams,\n validateModelName,\n validateProfileName,\n} from '../utils.js';\n\nexport interface PromptOverrideOptions extends SmrtObjectOptions {\n key?: string;\n tenantId?: string | null;\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n params?: string | PromptParams | null;\n}\n\ntype PromptOverrideIdentity = {\n key: string;\n tenantId: string | null;\n};\n\ntype PromptTransactionHandle = DatabaseInterface & {\n commit: () => Promise<void>;\n rollback: () => Promise<void>;\n};\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\n// Override rows are authorization state: any scope (app-wide, or another\n// tenant) can be written, and the object is not tenant-scoped by the request\n// context — `tenantId` is an ordinary settable field. Generated REST routes\n// and MCP tools only check authentication, so they are closed (#3013, mirrored\n// from `@happyvertical/smrt-features`). Hosts write overrides server-side\n// through `PromptOverrideService`, which requires an explicit authorizer for\n// every write (or `PromptOverrideCollection.setTemplateOverride()` /\n// `removeOverride()` after their own authorization decision). The CLI is\n// closed too: generated CLI commands dispatch through the generated API.\n@smrt({\n tableName: '_smrt_prompt_overrides',\n conflictColumns: ['key', 'context'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class PromptOverride extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-prompts\";\n @field({ required: true, requiredFor: 'identity' })\n key: string = '';\n\n // Not tenant-scoped (any scope is writable), but the value is a tenant id:\n // uuid on Postgres, so it compares with every other tenant_id column.\n @field({ sqlType: 'UUID', nullable: true })\n tenantId: string | null = null;\n\n @field({ type: 'text', nullable: true })\n template: string | null = null;\n\n @field({ type: 'text', nullable: true })\n profile: string | null = null;\n\n @field({ type: 'text', nullable: true })\n model: string | null = null;\n\n @field({ type: 'text', nullable: true })\n params: string | null = null;\n\n constructor(options: PromptOverrideOptions = {}) {\n super(options);\n\n if (options.key !== undefined) this.key = options.key;\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.template !== undefined) this.template = options.template;\n if (options.profile !== undefined) this.profile = options.profile;\n if (options.model !== undefined) this.model = options.model;\n if (options.params !== undefined) {\n if (typeof options.params === 'string' || options.params === null) {\n this.params = options.params;\n } else {\n this.params = serializePromptParams(options.params);\n }\n }\n }\n\n getParams(): PromptParams {\n return parsePromptParams(this.params);\n }\n\n setParams(params: PromptParams | null): void {\n this.params = serializePromptParams(params);\n }\n\n toPromptLayer(): PromptLayer {\n return {\n template: this.template,\n profile: this.profile,\n model: this.model,\n params: this.params === null ? null : this.getParams(),\n };\n }\n\n override async save(options?: SmrtSaveOptions): Promise<this> {\n const previousIdentity = await this.getPersistedIdentity();\n this.normalizeParamsForPersistence();\n await this.validatePromptOverride();\n // Use context as the uniqueness scope so app-level rows remain unique even\n // though tenantId is nullable and would otherwise allow multiple NULL rows.\n this.context = this.tenantId ?? APP_PROMPT_SCOPE_ID;\n const identityChanged =\n previousIdentity &&\n (previousIdentity.key !== this.key ||\n previousIdentity.tenantId !== this.tenantId);\n\n const result =\n identityChanged && previousIdentity\n ? await this.saveAfterIdentityChange(options)\n : await super.save(options);\n\n if (identityChanged && previousIdentity) {\n invalidatePromptCache(\n previousIdentity.key,\n previousIdentity.tenantId,\n this.db,\n );\n }\n invalidatePromptCache(this.key, this.tenantId, this.db);\n return result;\n }\n\n private async saveAfterIdentityChange(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n if (typeof this.db.beginTransaction === 'function') {\n return this.saveAfterIdentityChangeInTransaction(options);\n }\n\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n private async saveAfterIdentityChangeInTransaction(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const originalDb = this._db;\n const originalOptionsDb = this.options.db;\n const tx = (await this.db.beginTransaction?.()) as\n | PromptTransactionHandle\n | undefined;\n\n if (!tx) {\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n try {\n this._db = tx;\n this.options.db = tx;\n // The caller's revision guards the ORIGINAL row (checked by the delete);\n // the replacement is a fresh insert and must not carry the update guard.\n await super.delete(\n options?.expectedUpdatedAt === undefined\n ? undefined\n : { expectedUpdatedAt: options.expectedUpdatedAt },\n );\n const result = await super.save(withoutRevisionGuard(options));\n await tx.commit();\n return result;\n } catch (error) {\n try {\n await tx.rollback();\n } catch {\n // Preserve the original save error; rollback failures are secondary.\n }\n throw error;\n } finally {\n this._db = originalDb;\n this.options.db = originalOptionsDb;\n }\n }\n\n private async saveAfterIdentityChangeWithDeferredDelete(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const previousId = this.id;\n if (!previousId) {\n return super.save(options);\n }\n\n // Without a transaction, a check here and the later unguarded delete are\n // not atomic: a concurrent update could be deleted. Fail closed rather\n // than accept a revision guard that cannot be honoured (#4408).\n if (options?.expectedUpdatedAt !== undefined) {\n throw new RuntimeError(\n `${this.constructor.name} identity changes honour expectedUpdatedAt only inside a transaction`,\n 'RUNTIME_REVISION_GUARD_REQUIRES_TRANSACTION',\n { className: this.constructor.name, id: previousId },\n );\n }\n\n const replacementId = crypto.randomUUID();\n let replacementSaved = false;\n this.id = replacementId;\n\n try {\n const result = await super.save(withoutRevisionGuard(options));\n replacementSaved = true;\n await this.db.delete(this.tableName, { id: previousId });\n return result;\n } catch (error) {\n if (replacementSaved) {\n try {\n await this.db.delete(this.tableName, { id: replacementId });\n } catch {\n // Best effort cleanup keeps the original row as the source of truth.\n }\n }\n\n this.id = previousId;\n throw error;\n }\n }\n\n override async delete(): Promise<void> {\n const key = this.key;\n const tenantId = this.tenantId;\n await super.delete();\n invalidatePromptCache(key, tenantId, this.db);\n }\n\n private async validatePromptOverride(): Promise<void> {\n if (!this.key || this.key.trim() === '') {\n throw new Error('PromptOverride.key is required');\n }\n\n const definition = PromptRegistry.get(this.key);\n if (!definition) {\n throw new Error(`Unknown prompt key \"${this.key}\"`);\n }\n\n const config = getPromptConfig();\n const editable = definition.editable;\n\n if (this.template !== null && !editable.template) {\n throw new Error(`Prompt \"${this.key}\" does not allow template overrides`);\n }\n\n if (this.profile !== null && !editable.profile) {\n throw new Error(`Prompt \"${this.key}\" does not allow profile overrides`);\n }\n\n if (this.model !== null && !editable.model) {\n throw new Error(`Prompt \"${this.key}\" does not allow model overrides`);\n }\n\n if (this.params !== null && !editable.params) {\n throw new Error(`Prompt \"${this.key}\" does not allow params overrides`);\n }\n\n if (this.params !== null) {\n try {\n const parsed = JSON.parse(this.params);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Prompt params must be a JSON object');\n }\n } catch (error) {\n throw new Error(\n `Prompt \"${this.key}\" has invalid params JSON: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n if (this.profile !== null) {\n validateProfileName(this.profile, config);\n }\n\n if (this.model !== null) {\n validateModelName(this.model, config);\n }\n\n const lowerLayers = await this.getLowerPrecedenceLayers();\n const currentLayer = this.toPromptLayer();\n const merged = mergePromptLayers(...lowerLayers, currentLayer);\n\n if (currentLayer.model && !merged.ai.profile) {\n throw new Error(\n `Prompt \"${this.key}\" model overrides require an effective prompt profile`,\n );\n }\n }\n\n private async getLowerPrecedenceLayers(): Promise<PromptLayer[]> {\n const definition = PromptRegistry.get(this.key);\n const config = getPromptConfig();\n const layers: PromptLayer[] = [];\n\n if (definition) {\n layers.push({\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n params: definition.ai.params,\n });\n }\n\n layers.push(normalizePromptLayer(config.prompts?.[this.key]));\n\n const { PromptOverrideCollection } = await import(\n '../collections/PromptOverrideCollection.js'\n );\n const collection = await PromptOverrideCollection.create({\n db: this.options.db ?? this.options.persistence,\n });\n\n if (this.tenantId) {\n const appOverride = await collection.getAppOverride(this.key, {\n excludeId: this.id ?? undefined,\n });\n if (appOverride) {\n layers.push(appOverride.toPromptLayer());\n }\n }\n\n return layers;\n }\n\n private normalizeParamsForPersistence(): void {\n const rawParams = this.params as unknown;\n\n if (rawParams === null || rawParams === undefined) {\n this.params = null;\n return;\n }\n\n if (typeof rawParams === 'string') {\n this.params = rawParams;\n return;\n }\n\n if (typeof rawParams === 'object' && !Array.isArray(rawParams)) {\n this.params = serializePromptParams(rawParams as PromptParams);\n return;\n }\n\n throw new Error(\n `Prompt \"${this.key}\" params must be a JSON object or JSON string`,\n );\n }\n\n private async getPersistedIdentity(): Promise<PromptOverrideIdentity | null> {\n if (!this.id) {\n return null;\n }\n\n const existing = await this.db.get(this.tableName, { id: this.id });\n if (!existing) {\n return null;\n }\n\n return {\n key: String((existing as Record<string, unknown>).key ?? this.key),\n tenantId:\n (existing as Record<string, unknown>).tenantId !== undefined\n ? ((existing as Record<string, unknown>).tenantId as string | null)\n : (((existing as Record<string, unknown>).tenant_id as\n | string\n | null\n | undefined) ?? null),\n };\n }\n}\n\n/** The replacement row of an identity change is an insert, not a guarded update. */\nfunction withoutRevisionGuard(\n options: SmrtSaveOptions | undefined,\n): SmrtSaveOptions | undefined {\n if (!options || options.expectedUpdatedAt === undefined) return options;\n const { expectedUpdatedAt: _expected, ...rest } = options;\n return rest;\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { PromptOverride } from '../models/PromptOverride.js';\nimport type { PromptOverrideScopeType } from '../types.js';\n\nexport class PromptOverrideCollection extends SmrtCollection<PromptOverride> {\n static readonly _itemClass = PromptOverride;\n\n private excludeOverrideId(\n items: PromptOverride[],\n excludeId?: string,\n ): PromptOverride[] {\n return items.filter((item) => (excludeId ? item.id !== excludeId : true));\n }\n\n async getAppOverride(\n key: string,\n options: { excludeId?: string } = {},\n ): Promise<PromptOverride | null> {\n const items = await this.list({ where: { key, tenantId: null } });\n return this.excludeOverrideId(items, options.excludeId)[0] ?? null;\n }\n\n async getTenantOverride(\n key: string,\n tenantId: string,\n options: { excludeId?: string } = {},\n ): Promise<PromptOverride | null> {\n const items = await this.list({ where: { key, tenantId } });\n return this.excludeOverrideId(items, options.excludeId)[0] ?? null;\n }\n\n async getResolutionLayers(\n key: string,\n tenantId?: string | null,\n options: { excludeId?: string } = {},\n ): Promise<{ app: PromptOverride | null; tenant: PromptOverride | null }> {\n const [app, tenant] = await Promise.all([\n this.getAppOverride(key, options),\n tenantId != null\n ? this.getTenantOverride(key, tenantId, options)\n : Promise.resolve(null),\n ]);\n\n return {\n app,\n tenant,\n };\n }\n\n /**\n * The override row for every key in `keys` at one scope, in a single query.\n *\n * Used by `PromptSettingsService.listPromptSettings()` to enumerate the\n * whole registry's override state without one round trip per key. Because\n * this is an enumeration read — a host-configured\n * `defaultListLimit`/`maxListLimit` on the collection's options would\n * silently drop keys past the cap, changing which prompts a management\n * screen reports as overridden, with no error (the #3056 hazard class in\n * `@happyvertical/smrt-features`'s `getOverrideMap`) — callers that need the\n * full map construct this collection through\n * `PromptSettingsService.create()`, which strips those bounds.\n */\n async getOverrideMapForKeys(\n keys: string[],\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<Map<string, PromptOverride>> {\n const result = new Map<string, PromptOverride>();\n if (keys.length === 0) {\n return result;\n }\n\n const tenantId = scopeType === 'app' ? null : scopeId;\n const rows = await this.list({ where: { key: keys, tenantId } });\n for (const row of rows) {\n result.set(row.key, row);\n }\n\n return result;\n }\n\n /** The override row for a scope request, in the vocabulary used at the write boundary. */\n async findByScope(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<PromptOverride | null> {\n return scopeType === 'app'\n ? this.getAppOverride(key)\n : this.getTenantOverride(key, scopeId);\n }\n\n /**\n * Set (or clear, with `template: null`) the `template` field of the override\n * row for one scope, creating the row if it did not exist. Other fields\n * (`profile`, `model`, `params`) on an existing row are left untouched, per\n * this package's field-by-field inheritance model.\n */\n async setTemplateOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n const existing = await this.findByScope(key, scopeType, scopeId);\n\n if (existing) {\n existing.template = template;\n await existing.save();\n return existing;\n }\n\n const created = await this.create({\n key,\n tenantId: scopeType === 'app' ? null : scopeId,\n template,\n });\n await created.save();\n return created;\n }\n\n /** Remove the override row for one scope entirely, if one exists. */\n async removeOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<boolean> {\n const existing = await this.findByScope(key, scopeType, scopeId);\n if (!existing) {\n return false;\n }\n\n await existing.delete();\n return true;\n }\n}\n","import type { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport type { PromptOverride } from './models/PromptOverride.js';\nimport { APP_PROMPT_SCOPE_ID, type PromptOverrideScopeType } from './types.js';\n\n/** One override write the host must authorize before it runs (mirrors #3013). */\nexport interface PromptOverrideWriteRequest {\n operation: 'set' | 'remove';\n key: string;\n scopeType: PromptOverrideScopeType;\n scopeId: string;\n /** Present for `set`. `null` clears the template field. */\n template?: string | null;\n}\n\n/**\n * The host's explicit authorization decision for one override write. Return\n * `true` only when the current caller may write that exact scope; anything\n * else denies.\n */\nexport type PromptOverrideAuthorizer = (\n request: PromptOverrideWriteRequest,\n) => boolean | Promise<boolean>;\n\n/** Thrown when the authorizer does not return `true`. Nothing is written. */\nexport class PromptOverrideAuthorizationError extends Error {\n readonly status = 403;\n constructor(readonly request: PromptOverrideWriteRequest) {\n super(\n `Prompt override ${request.operation} denied for ${request.scopeType} scope`,\n );\n this.name = 'PromptOverrideAuthorizationError';\n }\n}\n\n/**\n * Thrown when a write names a scope the resolver never reads: an unknown scope\n * type, an app scope other than {@link APP_PROMPT_SCOPE_ID}, or a blank /\n * untrimmed / non-string tenant id. Checked before the authorizer runs, so a\n * malformed tenant scope can never resolve to the app-wide row. Nothing is\n * written.\n */\nexport class InvalidPromptScopeError extends Error {\n readonly status = 400;\n constructor(\n readonly scopeType: string,\n readonly scopeId: string,\n reason: string,\n ) {\n super(`Invalid prompt override scope (${scopeType}): ${reason}`);\n this.name = 'InvalidPromptScopeError';\n }\n}\n\n/** Reject any scope the resolver does not read (see {@link InvalidPromptScopeError}). */\nexport function assertValidPromptScope(\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n): void {\n if (scopeType !== 'app' && scopeType !== 'tenant') {\n throw new InvalidPromptScopeError(\n String(scopeType),\n String(scopeId),\n 'scope type must be \"app\" or \"tenant\"',\n );\n }\n if (typeof scopeId !== 'string') {\n throw new InvalidPromptScopeError(\n scopeType,\n String(scopeId),\n 'scope id must be a string',\n );\n }\n if (scopeType === 'app' && scopeId !== APP_PROMPT_SCOPE_ID) {\n throw new InvalidPromptScopeError(\n scopeType,\n scopeId,\n `the app scope is only ever \"${APP_PROMPT_SCOPE_ID}\"`,\n );\n }\n if (\n scopeType === 'tenant' &&\n (!scopeId.trim() ||\n scopeId !== scopeId.trim() ||\n scopeId === APP_PROMPT_SCOPE_ID)\n ) {\n throw new InvalidPromptScopeError(\n scopeType,\n scopeId,\n 'a tenant scope id must be non-blank, already trimmed, and not the app scope id',\n );\n }\n}\n\n/**\n * Authorized write path for prompt overrides (mirrors `FeatureOverrideService`,\n * #3013). Override rows are authorization state for every scope and\n * `PromptOverride` is not tenant-scoped by the request context, so generated\n * surfaces are closed. Hosts that let callers change prompt text construct\n * this service with an authorizer bound to the current caller and write\n * through it; every write asks the authorizer first and fails closed.\n */\nexport class PromptOverrideService {\n constructor(\n private readonly overrides: PromptOverrideCollection,\n private readonly authorize: PromptOverrideAuthorizer,\n ) {}\n\n async setTemplateOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n await this.require({ operation: 'set', key, scopeType, scopeId, template });\n return this.overrides.setTemplateOverride(\n key,\n scopeType,\n scopeId,\n template,\n );\n }\n\n async removeOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<boolean> {\n await this.require({ operation: 'remove', key, scopeType, scopeId });\n return this.overrides.removeOverride(key, scopeType, scopeId);\n }\n\n private async require(request: PromptOverrideWriteRequest): Promise<void> {\n assertValidPromptScope(request.scopeType, request.scopeId);\n let allowed = false;\n try {\n allowed = (await this.authorize(request)) === true;\n } catch {\n allowed = false;\n }\n if (!allowed) throw new PromptOverrideAuthorizationError(request);\n }\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport { getTenantId } from '@happyvertical/smrt-tenancy';\nimport {\n getCachedPromptBase,\n getPromptCacheGeneration,\n setCachedPromptBase,\n} from './cache.js';\nimport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport { PromptRegistry } from './prompt-registry.js';\nimport type {\n PromptCacheValue,\n PromptLayer,\n PromptPackageConfig,\n PromptSourceLayer,\n ResolvedPrompt,\n ResolvePromptOptions,\n} from './types.js';\nimport {\n buildResolvedAI,\n mergePromptLayers,\n normalizePromptLayer,\n promptTemplateHash,\n renderPromptTemplate,\n} from './utils.js';\n\n/** True when `layer` sets the template (null and undefined inherit). */\nfunction suppliesTemplate(layer: PromptLayer | null | undefined): boolean {\n return layer?.template !== undefined && layer.template !== null;\n}\n\n/** True when `layer` sets the profile (null and undefined inherit). */\nfunction suppliesProfile(layer: PromptLayer | null | undefined): boolean {\n return layer?.profile !== undefined && layer.profile !== null;\n}\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\nasync function loadPromptBase(\n key: string,\n options: ResolvePromptOptions,\n): Promise<PromptCacheValue> {\n const definition = PromptRegistry.get(key);\n if (!definition) {\n throw new Error(`Unknown prompt key \"${key}\"`);\n }\n\n const tenantId =\n options.tenantId !== undefined ? options.tenantId : (getTenantId() ?? null);\n\n let collection: PromptOverrideCollection | null = null;\n let cacheDb: ResolvePromptOptions['db'] | undefined = options.db;\n if (options.db) {\n const initializedCollection = await PromptOverrideCollection.create({\n db: options.db,\n });\n collection = initializedCollection;\n cacheDb = initializedCollection.db as ResolvePromptOptions['db'];\n }\n\n const cached = getCachedPromptBase(key, tenantId, cacheDb);\n if (cached) {\n return cached;\n }\n\n // Capture the invalidation generation before the asynchronous layer loads. A\n // write that lands while they are in flight bumps it, and the cache write\n // below is then refused rather than repopulating the key the write just\n // invalidated with the pre-write value.\n const loadedAtGeneration = getPromptCacheGeneration(key, cacheDb);\n\n const config = getPromptConfig();\n // Each layer is named so the resolution can report which one supplied the\n // effective template (the `promptLayer` usage tag, #4751).\n const layers: Array<{\n name: PromptCacheValue['templateLayer'];\n layer: PromptLayer;\n }> = [\n {\n name: 'default',\n layer: {\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n effort: definition.ai.effort ?? null,\n params: definition.ai.params,\n },\n },\n { name: 'config', layer: normalizePromptLayer(config.prompts?.[key]) },\n ];\n\n if (collection) {\n const stored = await collection.getResolutionLayers(key, tenantId);\n\n if (stored.app) {\n layers.push({ name: 'app', layer: stored.app.toPromptLayer() });\n }\n\n if (stored.tenant) {\n layers.push({ name: 'tenant', layer: stored.tenant.toPromptLayer() });\n }\n }\n\n const merged = mergePromptLayers(...layers.map(({ layer }) => layer));\n let templateLayer: PromptCacheValue['templateLayer'] = 'default';\n let profileLayer: PromptCacheValue['profileLayer'] = 'default';\n for (const { name, layer } of layers) {\n if (suppliesTemplate(layer)) templateLayer = name;\n if (suppliesProfile(layer)) profileLayer = name;\n }\n const value: PromptCacheValue = {\n key,\n template: merged.template,\n templateLayer,\n profileLayer,\n ai: merged.ai,\n };\n\n setCachedPromptBase(key, tenantId, cacheDb, value, loadedAtGeneration);\n return value;\n}\n\nexport async function resolvePrompt(\n key: string,\n options: ResolvePromptOptions = {},\n): Promise<ResolvedPrompt> {\n const config = getPromptConfig();\n const base = await loadPromptBase(key, options);\n const runtimeOverride = normalizePromptLayer(options.override);\n const merged = mergePromptLayers(\n {\n template: base.template,\n profile: base.ai.profile ?? null,\n model: base.ai.model ?? null,\n effort: base.ai.effort ?? null,\n params: base.ai.params,\n },\n runtimeOverride,\n );\n\n const promptLayer: PromptSourceLayer = suppliesTemplate(runtimeOverride)\n ? 'runtime'\n : base.templateLayer;\n // Only a profile the code default itself supplied is exempt from\n // `allowedProfileNames`; any config, stored or runtime layer that sets one\n // (even the same tier again) is a choice the allow-list governs.\n const profileFromDefault =\n base.profileLayer === 'default' && !suppliesProfile(runtimeOverride);\n const ai = buildResolvedAI(merged.ai, config, {\n defaultProfile: profileFromDefault\n ? PromptRegistry.get(key)?.ai.profile\n : undefined,\n });\n if (ai.tier) {\n // The tier binds once, at call time, through the core inference seam\n // (`SmrtObject.prepareAiOperation()` / `getAiClient(tier)`), with this\n // key so prompt-scoped bindings apply (#4750).\n ai.promptKey = key;\n // The latency hint belongs to the call site, so only the code default\n // declares it (#4755).\n const latency = PromptRegistry.get(key)?.ai.latency;\n if (latency) ai.latency = latency;\n // The degradation floor is the code default's alone (#4752).\n const minimumTier = PromptRegistry.get(key)?.ai.minimumTier;\n if (minimumTier) ai.minimumTier = minimumTier;\n }\n\n return {\n key,\n template: merged.template,\n text: renderPromptTemplate(merged.template, options.variables),\n ai: {\n ...ai,\n usageTags: {\n promptKey: key,\n promptLayer,\n templateHash: await promptTemplateHash(merged.template),\n },\n },\n };\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport type {\n SmrtClassOptions,\n SmrtCollectionOptions,\n} from '@happyvertical/smrt-core';\nimport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport type { PromptOverride } from './models/PromptOverride.js';\nimport {\n assertValidPromptScope,\n type PromptOverrideAuthorizer,\n PromptOverrideService,\n} from './prompt-override-service.js';\nimport { PromptRegistry } from './prompt-registry.js';\nimport {\n APP_PROMPT_SCOPE_ID,\n type PromptDefinition,\n type PromptEditableConfig,\n type PromptLayer,\n type PromptOverrideScopeType,\n type PromptPackageConfig,\n} from './types.js';\nimport { mergePromptLayers, normalizePromptLayer } from './utils.js';\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\n/**\n * The caller's options with its list bounds removed.\n *\n * `SmrtCollection.create()` forwards `defaultListLimit`/`maxListLimit` from\n * any options bag it is handed (#2367), so a host that sets those\n * application-wide would silently cap the bulk override-enumeration read\n * {@link PromptSettingsService.listPromptSettings} runs\n * (`getOverrideMapForKeys`) — a management screen showing every prompt, not a\n * user-facing page of results. A dropped row here is an override an operator\n * cannot see, and the prompt then reports as unoverridden, silently (the\n * `#3056` hazard class in `@happyvertical/smrt-features`'s `getOverrideMap`,\n * applied here proactively rather than left for a follow-up). Only the list\n * bounds are stripped; the database and every other option still apply.\n */\nfunction withoutListBounds(\n options: SmrtClassOptions | SmrtCollectionOptions,\n): SmrtCollectionOptions {\n return { ...options, defaultListLimit: undefined, maxListLimit: undefined };\n}\n\n/** The level that supplied a prompt's effective template. */\nexport type PromptSettingsLevel = 'default' | 'config' | 'app' | 'tenant';\n\n/**\n * One prompt, rendered for a management screen: the code-owned definition,\n * the text actually in effect for the requested tenant, and the raw override\n * state at each scope so the UI can show *why* it is in effect and what\n * reverting a scope produces.\n */\nexport interface PromptSettingsRow {\n /**\n * The persisted identifier. Renaming it orphans every existing override —\n * see the warning on {@link PromptSettingsService}.\n */\n key: string;\n /** Human description from the definition; may be empty. */\n description: string;\n /** Which fields a stored override may change, from the definition. */\n editable: PromptEditableConfig;\n /** The code-registered template, before the config layer or any override. */\n defaultTemplate: string;\n /**\n * What {@link resolvePrompt} resolves the template to for the requested\n * context — the text the application actually uses (unrendered: no\n * `{variable}` substitution).\n */\n effectiveTemplate: string;\n /** The app-level override row's `template` field, or `null` when there is none. */\n appTemplate: string | null;\n /**\n * The tenant-level override row's `template` field, or `null` when there is\n * none (or when no `tenantId` was requested).\n */\n tenantTemplate: string | null;\n /**\n * What the **app** scope's \"revert to default\" produces: the code default\n * merged with the config-file layer. Always knowable — nothing sits above\n * the app scope — unlike {@link inheritedTemplate}.\n */\n appDefaultTemplate: string;\n /**\n * What the **tenant** scope's \"revert to default\" produces: the code\n * default, the config-file layer, and the app-level override, merged with\n * no tenant override of its own. `null` when no `tenantId` was requested.\n *\n * This is the value a \"revert to default\" control for the tenant scope must\n * show or apply — never {@link defaultTemplate}, which ignores the config\n * layer and any app-level override and would silently discard them.\n */\n inheritedTemplate: string | null;\n /** Which level supplied {@link effectiveTemplate}. */\n supplyingLevel: PromptSettingsLevel;\n}\n\n/** Selection for {@link PromptSettingsService.listPromptSettings}. */\nexport interface ListPromptSettingsOptions {\n /**\n * Tenant whose overrides and effective template to report. Omit for an\n * app-only view.\n */\n tenantId?: string | null;\n /**\n * Restrict to an explicit allowlist of keys. Keys with no definition are\n * simply absent from the result — this filters, it does not validate.\n */\n keys?: string[];\n}\n\n/** One override write requested through {@link PromptSettingsService}. */\nexport interface SetPromptOverrideRequest {\n key: string;\n scopeType: PromptOverrideScopeType;\n scopeId: string;\n /** `null` clears the override, returning the scope to whatever it inherits. */\n template: string | null;\n}\n\n/**\n * Thrown when a write names a `key` that has no registered {@link PromptDefinition}.\n * Nothing is written.\n *\n * This is the generalized form of the per-app \"is this one of my keys?\" guard\n * every consumer would otherwise hand-roll to keep a form post from creating an\n * override for an arbitrary string.\n */\nexport class UnknownPromptKeyError extends Error {\n readonly status = 400;\n constructor(readonly key: string) {\n super(`Unknown prompt key: ${key}`);\n this.name = 'UnknownPromptKeyError';\n }\n}\n\n/**\n * Thrown when a write would set a field the definition's `editable` config\n * does not allow overriding. Nothing is written.\n */\nexport class PromptFieldNotEditableError extends Error {\n readonly status = 400;\n constructor(\n readonly key: string,\n readonly field: string,\n ) {\n super(`Prompt \"${key}\" does not allow ${field} overrides`);\n this.name = 'PromptFieldNotEditableError';\n }\n}\n\n/** Options for {@link PromptSettingsService.create}. */\nexport interface PromptSettingsServiceOptions {\n /**\n * The host's authorization decision for each override write, bound to the\n * current caller. **Omitting it makes the service read-only**: every write\n * then fails closed with `PromptOverrideAuthorizationError`. This package\n * never decides who may write.\n */\n authorize?: PromptOverrideAuthorizer;\n}\n\n/**\n * Read and write side of a prompt management screen, so consumers do not\n * re-derive the row shape or the unknown-key guard.\n *\n * **Authorization stays with the consumer.** This service makes no\n * authorization decision of its own: reads are unfiltered, and every write is\n * delegated to {@link PromptOverrideService}, which asks the host-supplied\n * {@link PromptOverrideAuthorizer} first and fails closed. Call it only from\n * server code that has already established who the caller is. See\n * `packages/prompts/README.md` for the consumer recipe.\n *\n * **Prompt keys are persisted identifiers.** Overrides are stored keyed by the\n * exact `key` string and resolved by that string at runtime. Renaming a key\n * orphans every existing override, silently reverting all tenants to the\n * registry default. Treat a key as immutable once shipped; a rename needs a\n * data migration, not an edit.\n */\nexport class PromptSettingsService {\n private readonly writes: PromptOverrideService;\n\n constructor(\n private readonly overrides: PromptOverrideCollection,\n authorize?: PromptOverrideAuthorizer,\n ) {\n this.writes = new PromptOverrideService(\n overrides,\n authorize ?? (() => false),\n );\n }\n\n /**\n * Build a service over the given database options.\n *\n * The internal bulk override-enumeration read {@link listPromptSettings}\n * runs is always issued without the caller's\n * `defaultListLimit`/`maxListLimit` — see {@link withoutListBounds}. Only\n * that read is affected; a `db` option is still honored.\n *\n * @param options - SMRT database options, as passed to any collection.\n * @param serviceOptions - Host authorizer. Omit for a read-only (load-function) service.\n */\n static async create(\n options: SmrtClassOptions = {},\n serviceOptions: PromptSettingsServiceOptions = {},\n ): Promise<PromptSettingsService> {\n const overrides = await PromptOverrideCollection.create(\n withoutListBounds(options),\n );\n return new PromptSettingsService(\n overrides as PromptOverrideCollection,\n serviceOptions.authorize,\n );\n }\n\n /**\n * One {@link PromptSettingsRow} per matching registered prompt, ordered by\n * key, so a rendered list is stable across loads.\n *\n * Makes no authorization decision — the caller has already decided that this\n * principal may see this tenant's prompts.\n */\n async listPromptSettings(\n options: ListPromptSettingsOptions = {},\n ): Promise<PromptSettingsRow[]> {\n const definitions = this.loadDefinitions(options);\n const keys = definitions.map((definition) => definition.key);\n const tenantId = options.tenantId;\n\n // Two bulk reads instead of up to 2N: see getOverrideMapForKeys for why\n // these must run through a bounds-stripped collection (#3056 class).\n const [appOverrides, tenantOverrides] = await Promise.all([\n this.overrides.getOverrideMapForKeys(keys, 'app', APP_PROMPT_SCOPE_ID),\n tenantId\n ? this.overrides.getOverrideMapForKeys(keys, 'tenant', tenantId)\n : Promise.resolve(new Map<string, PromptOverride>()),\n ]);\n\n return definitions.map((definition) =>\n this.toRow(\n definition,\n tenantId,\n appOverrides.get(definition.key) ?? null,\n tenantOverrides.get(definition.key) ?? null,\n ),\n );\n }\n\n /** The single row for one key, or `null` when no definition owns that key. */\n async getPromptSetting(\n key: string,\n tenantId?: string | null,\n ): Promise<PromptSettingsRow | null> {\n const definition = PromptRegistry.get(key);\n if (!definition) {\n return null;\n }\n\n const [appOverride, tenantOverride] = await Promise.all([\n this.overrides.getAppOverride(key),\n tenantId\n ? this.overrides.getTenantOverride(key, tenantId)\n : Promise.resolve(null),\n ]);\n\n return this.toRow(definition, tenantId, appOverride, tenantOverride);\n }\n\n /**\n * Apply one override change to the `template` field.\n *\n * Refuses any `key` without a registered {@link PromptDefinition}, any scope\n * the resolver would never read back, and a non-`null` template when the\n * definition's `editable.template` is `false`, then delegates to\n * {@link PromptOverrideService} so the host authorizer decides whether this\n * caller may write this scope. `template: null` clears the override.\n *\n * @throws {UnknownPromptKeyError} when the key has no definition.\n * @throws {InvalidPromptScopeError} when the scope is not one the resolver reads.\n * @throws {PromptFieldNotEditableError} when the definition disallows template overrides.\n * @throws `PromptOverrideAuthorizationError` when the authorizer declines.\n */\n async setPromptOverride(\n request: SetPromptOverrideRequest,\n ): Promise<PromptOverride> {\n const { key, scopeType, scopeId, template } = request;\n\n assertValidPromptScope(scopeType, scopeId);\n const definition = this.assertKnownPromptKey(key);\n\n if (template !== null && !definition.editable.template) {\n throw new PromptFieldNotEditableError(key, 'template');\n }\n\n return this.writes.setTemplateOverride(key, scopeType, scopeId, template);\n }\n\n /** {@link setPromptOverride} for the app-wide scope. */\n async setAppPromptOverride(\n key: string,\n template: string | null,\n ): Promise<PromptOverride> {\n return this.setPromptOverride({\n key,\n scopeType: 'app',\n scopeId: APP_PROMPT_SCOPE_ID,\n template,\n });\n }\n\n /** {@link setPromptOverride} for one tenant. */\n async setTenantPromptOverride(\n key: string,\n tenantId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n return this.setPromptOverride({\n key,\n scopeType: 'tenant',\n scopeId: tenantId,\n template,\n });\n }\n\n private assertKnownPromptKey(key: string): PromptDefinition {\n const trimmed = typeof key === 'string' ? key.trim() : '';\n if (!trimmed || trimmed !== key) {\n throw new UnknownPromptKeyError(String(key));\n }\n const definition = PromptRegistry.get(trimmed);\n if (!definition) {\n throw new UnknownPromptKeyError(trimmed);\n }\n return definition;\n }\n\n private loadDefinitions(\n options: ListPromptSettingsOptions,\n ): PromptDefinition[] {\n const all = PromptRegistry.getAll();\n const allowed = options.keys ? new Set(options.keys) : null;\n const selected = allowed\n ? all.filter((definition) => allowed.has(definition.key))\n : all;\n\n return [...selected].sort((a, b) => a.key.localeCompare(b.key));\n }\n\n private toRow(\n definition: PromptDefinition,\n tenantId: string | null | undefined,\n appOverride: PromptOverride | null,\n tenantOverride: PromptOverride | null,\n ): PromptSettingsRow {\n const { key } = definition;\n const config = getPromptConfig();\n\n const registryLayer: PromptLayer = {\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n effort: definition.ai.effort ?? null,\n params: definition.ai.params,\n };\n const configLayer = normalizePromptLayer(config.prompts?.[key]);\n\n const appLayer = appOverride ? appOverride.toPromptLayer() : null;\n const tenantLayer = tenantOverride ? tenantOverride.toPromptLayer() : null;\n\n // What the \"app\" scope's own revert-to-default produces: registry + config\n // only. This intentionally excludes the app override itself, so it must\n // NOT be reused as the app-only effective value below (that bug shipped\n // and broke both `effectiveTemplate` when no tenant is requested and every\n // tenant's inherited fallback until caught by this package's own tests).\n const appDefaultMerge = mergePromptLayers(registryLayer, configLayer);\n const inheritedMerge = tenantId\n ? mergePromptLayers(registryLayer, configLayer, appLayer)\n : null;\n // The effective template always includes the app override when present;\n // only the tenant layer is conditional on a requested tenantId.\n const effectiveMerge = mergePromptLayers(\n registryLayer,\n configLayer,\n appLayer,\n tenantId ? tenantLayer : null,\n );\n\n const appTemplate = appOverride?.template ?? null;\n const tenantTemplate = tenantId ? (tenantOverride?.template ?? null) : null;\n\n let supplyingLevel: PromptSettingsLevel = 'default';\n if (tenantId && tenantTemplate != null) {\n supplyingLevel = 'tenant';\n } else if (appTemplate != null) {\n supplyingLevel = 'app';\n } else if (configLayer.template != null) {\n supplyingLevel = 'config';\n }\n\n return {\n key,\n description: definition.description,\n editable: definition.editable,\n defaultTemplate: definition.template,\n effectiveTemplate: effectiveMerge.template,\n appTemplate,\n tenantTemplate,\n appDefaultTemplate: appDefaultMerge.template,\n inheritedTemplate: inheritedMerge ? inheritedMerge.template : null,\n supplyingLevel,\n };\n }\n}\n\n/**\n * Reject a scope the resolver would never read back.\n *\n * `PromptOverride` rows are looked up by the exact `(key, tenantId)` pair —\n * `tenantId: null` for the app scope, a tenant id otherwise. A row written\n * under a scope nothing queries is invisible state: it never takes effect,\n * and the host authorizer cannot catch it, because `scopeType: 'app'` with\n * someone else's tenant id looks like an ordinary app write to an authorizer\n * that only gates the app scope.\n */\n","/**\n * @happyvertical/smrt-prompts\n *\n * Code-first prompts with config overrides, stored app/tenant overrides,\n * and runtime resolution helpers for SMRT applications.\n *\n * @packageDocumentation\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n\nexport { clearPromptCache, getPromptCacheTtlMs } from './cache.js';\nexport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nexport {\n PromptOverride,\n type PromptOverrideOptions,\n} from './models/PromptOverride.js';\nexport {\n InvalidPromptScopeError,\n PromptOverrideAuthorizationError,\n type PromptOverrideAuthorizer,\n PromptOverrideService,\n type PromptOverrideWriteRequest,\n} from './prompt-override-service.js';\nexport { definePrompt, PromptRegistry } from './prompt-registry.js';\nexport { resolvePrompt } from './prompt-resolver.js';\nexport {\n type ListPromptSettingsOptions,\n PromptFieldNotEditableError,\n type PromptSettingsLevel,\n type PromptSettingsRow,\n PromptSettingsService,\n type PromptSettingsServiceOptions,\n type SetPromptOverrideRequest,\n UnknownPromptKeyError,\n} from './prompt-settings.js';\nexport type {\n NormalizedPromptAI,\n PromptAIInput,\n PromptConfigOverrideInput,\n PromptDefinition,\n PromptDefinitionInput,\n PromptEditableConfig,\n PromptLayer,\n PromptOverrideScopeType,\n PromptPackageConfig,\n PromptParams,\n PromptProfileConfig,\n PromptSourceLayer,\n PromptUsageTags,\n ResolvedPrompt,\n ResolvedPromptAI,\n ResolvePromptOptions,\n} from './types.js';\nexport { APP_PROMPT_SCOPE_ID } from './types.js';\nexport {\n type PromptMessageOptions,\n type PromptMessageOptionsExtra,\n promptMessageOptions,\n promptTemplateHash,\n trackedPromptCall,\n} from './utils.js';\n\n/** @internal */\nexport const PACKAGE_VERSION_INITIALIZED = true;\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,eAAe,wBAAwB,KAAK,MAAM,uzRAA2gU,CAAC;;;ACJ9jU,IAAM,sBAAsB;AAO5B,IAAM,8BAAc,IAAI,IAAwB;AAEhD,IAAM,mCAAmB,IAAI,IAAoB;AAMjD,IAAI,iBAAiB;AAQrB,IAAI,iBAAiB;AACrB,IAAM,gCAAgB,IAAI,QAAwB;AAClD,IAAI,WAAW;AAEf,SAAS,eAAe,IAAqB;CAC3C,IAAI,CAAC,IACH,OAAO;CAGT,IAAI,OAAO,OAAO,UAChB,OAAO,MAAM;CAGf,IAAI,OAAO,OAAO,UAAU;EAC1B,MAAM,WAAW;EACjB,IAAI,OAAO,SAAS,UAAU,YAAY;GACxC,IAAI,CAAC,cAAc,IAAI,QAAQ,GAC7B,cAAc,IAAI,UAAU,eAAe,YAAY;GAEzD,MAAM,YAAY,cAAc,IAAI,QAAQ;GAC5C,IAAI,WACF,OAAO;GAGT,OAAO;EACT;EAEA,IAAI;GACF,OAAO,aAAa,KAAK,UAAU,QAAQ;EAC7C,QAAQ;GACN,OAAO;EACT;CACF;CAEA,OAAO;AACT;AAEA,SAAS,cACP,KACA,UACA,IACQ;CACR,OAAO,GAAG,eAAe,EAAE,EAAC,IAAK,IAAG,IAAK,YAAY;AACvD;AAEA,SAAS,mBACP,KACA,IACQ;CACR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ACA,aAAa,WAAW;GACxB,UAAU,WAAW;GACrB,iBAAiB,WAAW;GAC5B,mBAAmB,eAAe;GAClC;GACA;GACA,oBAAoB,gBAAgB;GACpC,mBAAmB,iBAAiB,eAAe,WAAW;GAC9D;EACF;CACF;AACF;;;ACjWO,IAAM,8BAA8B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/cache.ts","../src/utils.ts","../src/prompt-registry.ts","../src/models/PromptOverride.ts","../src/collections/PromptOverrideCollection.ts","../src/prompt-override-service.ts","../src/scoped-overrides.ts","../src/prompt-resolver.ts","../src/prompt-settings.ts","../src/index.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-prompts\\\",\\\"packageVersion\\\":\\\"0.74.3\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-prompts:PromptOverrideCollection\\\":{\\\"name\\\":\\\"promptoverridecollection\\\",\\\"className\\\":\\\"PromptOverrideCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-prompts:PromptOverrideCollection\\\",\\\"collection\\\":\\\"promptoverrides\\\",\\\"filePath\\\":\\\"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\\\":\\\"src/models/PromptOverride.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-prompts\\\",\\\"fields\\\":{\\\"key\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"default\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true,\\\"default\\\":\\\"\\\"},\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"template\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"profile\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"model\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"params\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"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}\"));\n","import type { DatabaseInterface } from '@happyvertical/sql';\nimport type { PromptCacheValue } from './types.js';\n\nconst PROMPT_CACHE_TTL_MS = 30_000;\n\ntype CacheEntry = {\n expiresAt: number;\n value: PromptCacheValue;\n};\n\nconst promptCache = new Map<string, CacheEntry>();\n/** Monotonic per-`(db, key)` invalidation counter; see getPromptCacheGeneration. */\nconst cacheGenerations = new Map<string, number>();\n/**\n * Source of every generation value. Drawing from one counter instead of\n * incrementing each key independently makes a generation unique across every\n * key and every clear, which is what lets `clearedThrough` work as a floor.\n */\nlet nextGeneration = 1;\n/**\n * Floor that `clearPromptCache()` raises for *every* key, including keys with\n * no map entry. A key that has never been invalidated in this process reads as\n * generation 0, so a resolution that captured 0 before a clear would still see\n * 0 after it and write its pre-clear value back — the flush would be silently\n * undone for the rest of the TTL.\n */\nlet clearedThrough = 0;\nconst dbInstanceIds = new WeakMap<object, string>();\nlet nextDbId = 1;\n\nfunction getDbNamespace(db: unknown): string {\n if (!db) {\n return 'no-db';\n }\n\n if (typeof db === 'string') {\n return `db:${db}`;\n }\n\n if (typeof db === 'object') {\n const dbObject = db as Record<string, unknown>;\n if (typeof dbObject.query === 'function') {\n if (!dbInstanceIds.has(dbObject)) {\n dbInstanceIds.set(dbObject, `db-instance:${nextDbId++}`);\n }\n const namespace = dbInstanceIds.get(dbObject);\n if (namespace) {\n return namespace;\n }\n\n return 'db-instance:unknown';\n }\n\n try {\n return `db-config:${JSON.stringify(dbObject)}`;\n } catch {\n return 'db-config:opaque';\n }\n }\n\n return 'db:unknown';\n}\n\nfunction buildCacheKey(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): string {\n return `${getDbNamespace(db)}::${key}::${tenantId ?? 'app'}`;\n}\n\nfunction buildGenerationKey(\n key: string,\n db: DatabaseInterface | unknown,\n): string {\n return `${getDbNamespace(db)}::${key}`;\n}\n\nfunction bumpGeneration(key: string, db: DatabaseInterface | unknown): void {\n cacheGenerations.set(buildGenerationKey(key, db), nextGeneration++);\n}\n\nexport function getPromptCacheTtlMs(): number {\n return PROMPT_CACHE_TTL_MS;\n}\n\nexport function getCachedPromptBase(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): PromptCacheValue | null {\n const cacheKey = buildCacheKey(key, tenantId, db);\n const cached = promptCache.get(cacheKey);\n\n if (!cached) {\n return null;\n }\n\n if (cached.expiresAt <= Date.now()) {\n promptCache.delete(cacheKey);\n return null;\n }\n\n return cached.value;\n}\n\n/**\n * Reads the current invalidation generation for a key.\n *\n * A resolution captures this *before* its asynchronous layer loads and hands\n * it back to {@link setCachedPromptBase}. Any write that lands while those\n * loads are in flight bumps the generation, so the in-flight resolution —\n * which read the pre-write layers — is refused the cache write instead of\n * repopulating the key it just invalidated. Without this, a read that raced a\n * write served the pre-write value for the full TTL, and a raced `delete()`\n * resurrected the deleted override.\n *\n * Tracked per `(db, key)` rather than per `(db, key, tenantId)`: an app-level\n * row is inherited by every tenant, so a write to any scope of a key must\n * invalidate every scope of it. This matches the coarsest fan-out of\n * {@link invalidatePromptCache}.\n *\n * A key with no entry of its own reports the {@link clearPromptCache} floor\n * rather than a bare 0, so a clear refuses in-flight writes for keys that have\n * never been invalidated too.\n */\nexport function getPromptCacheGeneration(\n key: string,\n db: DatabaseInterface | unknown,\n): number {\n const generation = cacheGenerations.get(buildGenerationKey(key, db)) ?? 0;\n return generation > clearedThrough ? generation : clearedThrough;\n}\n\nexport function setCachedPromptBase(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n value: PromptCacheValue,\n loadedAtGeneration: number,\n): void {\n if (getPromptCacheGeneration(key, db) !== loadedAtGeneration) {\n // A write landed while this resolution was loading. Its value is already\n // stale, so drop it rather than poison the key for the whole TTL.\n return;\n }\n\n promptCache.set(buildCacheKey(key, tenantId, db), {\n expiresAt: Date.now() + PROMPT_CACHE_TTL_MS,\n value,\n });\n}\n\n/**\n * Invalidates a cached resolution. An app-level write (tenantId null) clears\n * every tenant's entry for that key, because each tenant inherits from it.\n */\nexport function invalidatePromptCache(\n key: string,\n tenantId: string | null | undefined,\n db: DatabaseInterface | unknown,\n): void {\n const dbNamespace = getDbNamespace(db);\n bumpGeneration(key, db);\n\n if (tenantId !== null && tenantId !== undefined) {\n promptCache.delete(buildCacheKey(key, tenantId, db));\n return;\n }\n\n const keyPrefix = `${dbNamespace}::${key}::`;\n for (const cacheKey of promptCache.keys()) {\n if (cacheKey.startsWith(keyPrefix)) {\n promptCache.delete(cacheKey);\n }\n }\n}\n\nexport function clearPromptCache(): void {\n promptCache.clear();\n // Raise the floor instead of resetting counters: a resolution that started\n // before the clear must be refused its write, and raising a single floor\n // covers keys with no generation entry, which a per-key bump cannot reach.\n // With the floor carrying the refusal, the per-key entries can be dropped.\n clearedThrough = nextGeneration++;\n cacheGenerations.clear();\n}\n","import {\n INFERENCE_TIERS,\n type InferenceLatency,\n type InferenceTierRequest,\n isInferenceTier,\n isInferenceTierRequest,\n isReasoningEffort,\n REASONING_EFFORTS,\n type ReasoningEffort,\n type TrackedPromptCall,\n} from '@happyvertical/smrt-core';\nimport type {\n NormalizedPromptAI,\n PromptAIInput,\n PromptConfigOverrideInput,\n PromptDefinitionInput,\n PromptEditableConfig,\n PromptLayer,\n PromptPackageConfig,\n PromptParams,\n PromptProfileConfig,\n ResolvedPrompt,\n ResolvedPromptAI,\n} from './types.js';\n\nconst DEFAULT_EDITABLE: PromptEditableConfig = {\n template: false,\n profile: false,\n model: false,\n params: false,\n};\n\nconst TOP_LEVEL_RESERVED_KEYS = new Set([\n 'key',\n 'editable',\n 'template',\n 'ai',\n 'profile',\n 'provider',\n 'model',\n 'effort',\n 'params',\n 'temperature',\n 'maxTokens',\n]);\n\nconst AI_RESERVED_KEYS = new Set([\n 'profile',\n 'provider',\n 'model',\n 'effort',\n 'params',\n 'temperature',\n 'maxTokens',\n]);\n\n// `tier` and `promptKey` come only from the resolution (an effective tier\n// profile), never from tenant-editable params, so `allowedProfileNames`\n// cannot be bypassed through params (#4755).\nconst AI_ROUTING_PARAM_KEYS = new Set([\n 'profile',\n 'provider',\n 'type',\n 'model',\n 'defaultModel',\n // Inference tier routing (#4750) comes only from the validated profile;\n // a (tenant-editable) params layer can never pick or spoof it.\n 'tier',\n 'latency',\n 'promptKey',\n // The ladder floor is read from the code default only (#4752).\n 'minimumTier',\n // Reasoning effort is the validated `effort` field (#5005), never an open\n // param a tenant override could widen.\n 'effort',\n 'reasoning',\n]);\n\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function normalizeEditableConfig(\n editable?: Partial<PromptEditableConfig>,\n): PromptEditableConfig {\n return {\n template: editable?.template ?? DEFAULT_EDITABLE.template,\n profile: editable?.profile ?? DEFAULT_EDITABLE.profile,\n model: editable?.model ?? DEFAULT_EDITABLE.model,\n params: editable?.params ?? DEFAULT_EDITABLE.params,\n };\n}\n\nfunction extractPromptParams(\n source: Record<string, unknown>,\n reservedKeys: Set<string>,\n): PromptParams {\n const params: PromptParams = {};\n\n if (isPlainObject(source.params)) {\n Object.assign(params, sanitizePromptParams(source.params));\n }\n\n if ('temperature' in source && source.temperature !== undefined) {\n params.temperature = source.temperature;\n }\n\n if ('maxTokens' in source && source.maxTokens !== undefined) {\n params.maxTokens = source.maxTokens;\n }\n\n for (const [key, value] of Object.entries(source)) {\n if (reservedKeys.has(key) || value === undefined) {\n continue;\n }\n assignPromptParam(params, key, value);\n }\n\n return params;\n}\n\nfunction assignPromptParam(\n params: PromptParams,\n key: string,\n value: unknown,\n): void {\n if (AI_ROUTING_PARAM_KEYS.has(key) || value === undefined) {\n return;\n }\n\n params[key] = value;\n}\n\nexport function sanitizePromptParams(\n params: PromptParams | null | undefined,\n): PromptParams {\n const sanitized: PromptParams = {};\n\n if (!params) {\n return sanitized;\n }\n\n for (const [key, value] of Object.entries(params)) {\n assignPromptParam(sanitized, key, value);\n }\n\n return sanitized;\n}\n\nexport function mergePromptParams(\n ...paramLayers: Array<PromptParams | null | undefined>\n): PromptParams {\n const merged: PromptParams = {};\n\n for (const layer of paramLayers) {\n if (!layer) {\n continue;\n }\n\n for (const [key, value] of Object.entries(layer)) {\n assignPromptParam(merged, key, value);\n }\n }\n\n return merged;\n}\n\n/**\n * A prompt's reasoning effort: absent, or one of core's `REASONING_EFFORTS`.\n * Anything else throws, naming the allowed values.\n */\nexport function validatePromptEffort(\n value: unknown,\n): ReasoningEffort | undefined {\n if (value === undefined || value === null) return undefined;\n if (!isReasoningEffort(value)) {\n throw new Error(\n `Prompt ai.effort must be one of ${REASONING_EFFORTS.join(', ')}; got \"${String(value)}\".`,\n );\n }\n return value;\n}\n\nfunction normalizeAIInput(ai?: PromptAIInput | null): NormalizedPromptAI {\n if (!isPlainObject(ai)) {\n return { params: {} };\n }\n\n const profile =\n typeof ai.profile === 'string' || ai.profile === null\n ? ai.profile\n : undefined;\n const model =\n typeof ai.model === 'string' || ai.model === null ? ai.model : undefined;\n if (ai.minimumTier !== undefined && !isInferenceTier(ai.minimumTier)) {\n throw new Error(\n `Prompt ai.minimumTier must be one of ${INFERENCE_TIERS.join(', ')}; got \"${String(ai.minimumTier)}\".`,\n );\n }\n\n const latency =\n ai.latency === 'interactive' || ai.latency === 'background'\n ? ai.latency\n : undefined;\n const effort = validatePromptEffort(ai.effort);\n\n return {\n profile: profile ?? undefined,\n model: model ?? undefined,\n ...(latency ? { latency } : {}),\n ...(ai.minimumTier ? { minimumTier: ai.minimumTier } : {}),\n ...(effort ? { effort } : {}),\n params: extractPromptParams(ai, AI_RESERVED_KEYS),\n };\n}\n\nexport function normalizePromptDefinitionInput(input: PromptDefinitionInput): {\n key: string;\n template: string;\n description: string;\n ai: NormalizedPromptAI;\n editable: PromptEditableConfig;\n} {\n return {\n key: input.key,\n template: input.template,\n description: input.description ?? '',\n ai: normalizeAIInput(input.ai),\n editable: normalizeEditableConfig(input.editable),\n };\n}\n\nexport function normalizePromptLayer(\n input?: PromptConfigOverrideInput | null,\n): PromptLayer {\n if (!isPlainObject(input)) {\n return {};\n }\n\n const nestedAi = isPlainObject(input.ai)\n ? normalizeAIInput(input.ai)\n : { params: {} };\n const topLevelParams = extractPromptParams(input, TOP_LEVEL_RESERVED_KEYS);\n\n return {\n template:\n input.template === undefined\n ? undefined\n : input.template === null\n ? null\n : String(input.template),\n profile:\n input.profile === undefined\n ? nestedAi.profile\n : input.profile === null\n ? null\n : String(input.profile),\n model:\n input.model === undefined\n ? nestedAi.model\n : input.model === null\n ? null\n : String(input.model),\n effort:\n input.effort === undefined\n ? nestedAi.effort\n : input.effort === null\n ? null\n : validatePromptEffort(input.effort),\n params: mergePromptParams(topLevelParams, nestedAi.params),\n };\n}\n\nexport function mergePromptLayers(\n ...layers: Array<PromptLayer | null | undefined>\n): {\n template: string;\n ai: NormalizedPromptAI;\n} {\n let template = '';\n let profile: string | undefined;\n let model: string | undefined;\n let effort: ReasoningEffort | undefined;\n let params: PromptParams = {};\n\n for (const layer of layers) {\n if (!layer) {\n continue;\n }\n\n if (layer.template !== undefined && layer.template !== null) {\n template = layer.template;\n }\n\n if (layer.profile !== undefined && layer.profile !== null) {\n profile = layer.profile;\n }\n\n if (layer.model !== undefined && layer.model !== null) {\n model = layer.model;\n }\n\n if (layer.effort !== undefined && layer.effort !== null) {\n effort = validatePromptEffort(layer.effort);\n }\n\n if (layer.params !== undefined && layer.params !== null) {\n params = mergePromptParams(params, layer.params);\n }\n }\n\n return {\n template,\n ai: {\n profile,\n model,\n ...(effort ? { effort } : {}),\n params,\n },\n };\n}\n\nexport function normalizeProfileConfig(profile: PromptProfileConfig): {\n provider: string;\n model: string;\n params: PromptParams;\n} {\n const source = isPlainObject(profile) ? profile : {};\n const params = extractPromptParams(source, new Set(['provider', 'model']));\n\n return {\n provider: String(profile.provider),\n model: String(profile.model),\n params,\n };\n}\n\nexport function validateProfileName(\n profileName: string,\n config: PromptPackageConfig,\n): void {\n if (profileName.trim() === '') {\n throw new Error('Prompt profile names cannot be empty');\n }\n\n const allowedProfileNames = config.allowedProfileNames;\n if (\n Array.isArray(allowedProfileNames) &&\n !allowedProfileNames.includes(profileName)\n ) {\n throw new Error(\n `Prompt profile \"${profileName}\" is not in the allowed profile list`,\n );\n }\n\n // Tier names (and `auto`) are reserved profile names that resolve through\n // the core inference seam (#4750); a same-named configured profile wins.\n if (!config.profiles?.[profileName] && !isInferenceTierRequest(profileName)) {\n throw new Error(`Prompt profile \"${profileName}\" is not configured`);\n }\n}\n\nexport function validateModelName(\n modelName: string,\n config: PromptPackageConfig,\n): void {\n if (modelName.trim() === '') {\n throw new Error('Prompt model overrides cannot be empty');\n }\n\n const allowedModels = config.allowedModels;\n if (Array.isArray(allowedModels) && !allowedModels.includes(modelName)) {\n throw new Error(\n `Prompt model \"${modelName}\" is not in the allowed model list`,\n );\n }\n}\n\nexport function buildResolvedAI(\n ai: NormalizedPromptAI,\n config: PromptPackageConfig,\n options: {\n /**\n * The registered code default's profile (`definePrompt({ ai })`), passed\n * only when no config, stored or runtime layer set a profile.\n */\n defaultProfile?: string;\n } = {},\n): ResolvedPromptAI {\n let provider: string | undefined;\n let model = ai.model;\n let params = ai.params;\n let tier: ResolvedPromptAI['tier'];\n\n if (ai.profile) {\n // `allowedProfileNames` limits what config and stored overrides may\n // select. A tier the code default itself declares (#4755) is not such a\n // choice, so an app's allow-list cannot break framework prompts.\n const codeDefaultTier =\n ai.profile === options.defaultProfile &&\n !config.profiles?.[ai.profile] &&\n isInferenceTierRequest(ai.profile);\n if (!codeDefaultTier) validateProfileName(ai.profile, config);\n const configuredProfile = config.profiles?.[ai.profile];\n if (configuredProfile) {\n const profileConfig = normalizeProfileConfig(configuredProfile);\n provider = profileConfig.provider;\n model = model ?? profileConfig.model;\n params = mergePromptParams(profileConfig.params, params);\n } else if (isInferenceTierRequest(ai.profile)) {\n // Bound later through the core inference seam by `resolvePrompt()`.\n tier = ai.profile;\n } else {\n throw new Error(`Prompt profile \"${ai.profile}\" is not configured`);\n }\n }\n\n if (ai.model) {\n validateModelName(ai.model, config);\n }\n\n if (ai.model && !ai.profile) {\n throw new Error(\n 'Direct prompt model overrides require an effective prompt profile',\n );\n }\n\n if (model && !ai.model && config.allowedModels) {\n validateModelName(model, config);\n }\n\n const resolved: ResolvedPromptAI = {\n ...params,\n profile: ai.profile,\n provider,\n model,\n ...(tier ? { tier } : {}),\n ...(ai.effort ? { effort: ai.effort } : {}),\n ...(config.allowedModels\n ? { allowedModels: [...config.allowedModels] }\n : {}),\n params,\n };\n\n if (typeof params.temperature === 'number') {\n resolved.temperature = params.temperature;\n }\n\n if (typeof params.maxTokens === 'number') {\n resolved.maxTokens = params.maxTokens;\n }\n\n return resolved;\n}\n\nconst TEMPLATE_HASH_LENGTH = 12;\n\n/**\n * Short SHA-256 fingerprint of an effective (unrendered) prompt template: the\n * first 12 lowercase hex characters. Recorded as the `templateHash` usage tag\n * so an override edit starts a new usage series (#4751).\n *\n * Uses Web Crypto (`globalThis.crypto.subtle`), available in Node and every\n * browser, so the package root stays free of `node:crypto`.\n */\nexport async function promptTemplateHash(template: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(template),\n );\n let hex = '';\n for (const byte of new Uint8Array(digest)) {\n hex += byte.toString(16).padStart(2, '0');\n if (hex.length >= TEMPLATE_HASH_LENGTH) break;\n }\n return hex.slice(0, TEMPLATE_HASH_LENGTH);\n}\n\n/** The `ai.message()` options {@link promptMessageOptions} returns. */\nexport interface PromptMessageOptions extends PromptParams {\n model?: string;\n /**\n * Inference tier of a tier profile (#4750). Object call sites pass these\n * options through `SmrtObject.prepareAiOperation()`, which picks the tier\n * client and strips `tier`/`promptKey` before the provider sees them.\n */\n tier?: InferenceTierRequest;\n /** Set with `tier`: the prompt key for the call-time resolver request. */\n promptKey?: string;\n /** Set with `tier`: the code default's `ai.latency` hint (#4755). */\n latency?: InferenceLatency;\n temperature?: number;\n maxTokens?: number;\n /** Degradation floor sent with `tier` (#4752). */\n minimumTier?: ResolvedPromptAI['minimumTier'];\n /** The prompt's effort (#5005). A caller's own `reasoning` wins. */\n reasoning?: { effort: ReasoningEffort };\n usageTags?: Record<string, string>;\n}\n\n/** Extra call options merged by {@link promptMessageOptions}. */\nexport interface PromptMessageOptionsExtra {\n /** The caller's own usage tags; they win over the resolution's tags. */\n usageTags?: Record<string, string>;\n /**\n * `false` omits `tier`/`promptKey` for a call site that sends the options\n * straight to a client it already holds (no `prepareAiOperation()`), so\n * the tier keys never reach a provider; the call runs on that client.\n * Default `true`.\n */\n routeTier?: boolean;\n}\n\n/**\n * Turn a resolved prompt's AI settings into `ai.message()` call options:\n * params, `model`, `temperature`, `maxTokens`, the resolution's\n * `usageTags` (`promptKey`, `promptLayer`, `templateHash`) and, for a tier\n * profile, `tier` + `promptKey` (#4750). Send them through\n * `SmrtObject.prepareAiOperation()` so the tier keys never reach a provider.\n *\n * The prompt's `effort` becomes `reasoning: { effort }` (#5005). Precedence,\n * high to low: the caller's own `reasoning` option (spread after these), the\n * prompt's effort, the tier binding's `params.reasoning` (core spreads a\n * target's params under the call options), the provider's default.\n *\n * Tag precedence, low to high: a `usageTags` object carried in the prompt's\n * params (tenant-editable: reserved tags such as runId or tier tags are\n * dropped from it), the resolution's identity tags, then `extra.usageTags`.\n */\nexport function promptMessageOptions(\n ai: ResolvedPromptAI,\n extra: PromptMessageOptionsExtra = {},\n): PromptMessageOptions {\n // Tier routing keys never ride in on params, even for a hand-built object.\n const {\n tier: _tier,\n latency: _latency,\n promptKey: _promptKey,\n // Never spread raw: only the sanitized copy below may reach the call.\n usageTags: paramTags,\n ...params\n } = ai.params || {};\n const routeTier = extra.routeTier !== false;\n const usageTags = {\n ...paramUsageTags(paramTags),\n ...(ai.usageTags ?? {}),\n ...(extra.usageTags ?? {}),\n };\n return {\n ...params,\n ...(ai.model ? { model: ai.model } : {}),\n ...(routeTier && ai.tier ? { tier: ai.tier } : {}),\n ...(routeTier && ai.tier && ai.promptKey\n ? { promptKey: ai.promptKey }\n : {}),\n ...(routeTier && ai.tier && ai.latency ? { latency: ai.latency } : {}),\n ...(routeTier && ai.tier && ai.minimumTier\n ? { minimumTier: ai.minimumTier }\n : {}),\n ...(typeof ai.temperature === 'number'\n ? { temperature: ai.temperature }\n : {}),\n ...(typeof ai.maxTokens === 'number' ? { maxTokens: ai.maxTokens } : {}),\n ...(ai.effort ? { reasoning: { effort: ai.effort } } : {}),\n ...(Object.keys(usageTags).length > 0 ? { usageTags } : {}),\n };\n}\n\n/**\n * Usage tags that feed indexed columns, tenant checks or report accounting\n * (#4751, #4750, #4752, #4753). A tenant-editable params layer must never\n * set them: a forged `runId` could make another tenant's run look shared and\n * block its outcome labels, and forged tier or substitution tags would skew\n * the report. Only the resolution and the calling code may set these.\n */\nconst RESERVED_USAGE_TAGS = new Set([\n 'promptKey',\n 'promptLayer',\n 'templateHash',\n 'runId',\n 'tierRequested',\n 'tierResolved',\n 'substitutions',\n 'fusionKey',\n]);\n\n/** Free-form tags from params, minus the reserved ones. */\nfunction paramUsageTags(value: unknown): Record<string, string> {\n if (!isPlainObject(value)) return {};\n const tags: Record<string, string> = {};\n for (const [key, tag] of Object.entries(value)) {\n if (RESERVED_USAGE_TAGS.has(key)) continue;\n if (tag !== undefined && tag !== null) tags[key] = String(tag);\n }\n return tags;\n}\n\nexport function renderPromptTemplate(\n template: string,\n variables?: Record<string, unknown>,\n): string {\n if (!variables || Object.keys(variables).length === 0) {\n return template;\n }\n\n return template.replace(/\\{([^{}]+)\\}/g, (_match, rawKey: string) => {\n const key = rawKey.trim();\n const value = variables[key];\n\n if (value === undefined || value === null) {\n return '';\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (Array.isArray(value) || isPlainObject(value)) {\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n }\n\n return String(value);\n });\n}\n\nexport function parsePromptParams(\n raw: string | null | undefined,\n): PromptParams {\n if (!raw) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(raw);\n return isPlainObject(parsed) ? sanitizePromptParams(parsed) : {};\n } catch {\n return {};\n }\n}\n\nexport function serializePromptParams(\n params: PromptParams | null | undefined,\n): string | null {\n if (params === null || params === undefined) {\n return null;\n }\n\n return JSON.stringify(sanitizePromptParams(params));\n}\n\n/**\n * What smrt-core's tracked client takes for a resolved prompt (#5005): the\n * key, the template hash, and the tier, latency and floor the prompt asks\n * for. `resolvePrompt()` is the only place a key comes from, so every tracked\n * call is a call of a registered prompt; core never imports this package.\n *\n * const resolved = await resolvePrompt('chat.assistant.system', { db });\n * const ai = await tracked.client(trackedPromptCall(resolved), { runContext });\n */\nexport function trackedPromptCall(\n resolved: ResolvedPrompt,\n extra: { usageTags?: Record<string, string> } = {},\n): TrackedPromptCall {\n const { ai } = resolved;\n const { promptKey: _key, templateHash, ...tags } = ai.usageTags ?? {};\n return {\n promptKey: resolved.key,\n ...(templateHash ? { templateHash } : {}),\n ...(ai.tier ? { tier: ai.tier } : {}),\n ...(ai.tier && ai.latency ? { latency: ai.latency } : {}),\n ...(ai.tier && ai.minimumTier ? { minimumTier: ai.minimumTier } : {}),\n usageTags: { ...tags, ...(extra.usageTags ?? {}) } as Record<\n string,\n string\n >,\n };\n}\n","import type { PromptDefinition, PromptDefinitionInput } from './types.js';\nimport { normalizePromptDefinitionInput } from './utils.js';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __smrtPromptRegistry: Map<string, PromptDefinition> | undefined;\n}\n\nfunction getRegistry(): Map<string, PromptDefinition> {\n if (!globalThis.__smrtPromptRegistry) {\n globalThis.__smrtPromptRegistry = new Map<string, PromptDefinition>();\n }\n\n return globalThis.__smrtPromptRegistry;\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n return `{${entries\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)\n .join(',')}}`;\n }\n\n return JSON.stringify(value);\n}\n\nexport const PromptRegistry = {\n register(input: PromptDefinitionInput): PromptDefinition {\n if (!input.key || input.key.trim() === '') {\n throw new Error('Prompt definitions require a non-empty key');\n }\n\n const definition = normalizePromptDefinitionInput(input);\n const registry = getRegistry();\n const existing = registry.get(definition.key);\n\n if (existing) {\n const existingSignature = stableStringify(existing);\n const incomingSignature = stableStringify(definition);\n\n if (existingSignature !== incomingSignature) {\n throw new Error(\n `Prompt \"${definition.key}\" is already registered with a different definition`,\n );\n }\n\n return existing;\n }\n\n registry.set(definition.key, definition);\n return definition;\n },\n\n get(key: string): PromptDefinition | undefined {\n return getRegistry().get(key);\n },\n\n has(key: string): boolean {\n return getRegistry().has(key);\n },\n\n getAll(): PromptDefinition[] {\n return Array.from(getRegistry().values());\n },\n\n clear(): void {\n getRegistry().clear();\n },\n};\n\nexport function definePrompt(input: PromptDefinitionInput): PromptDefinition {\n return PromptRegistry.register(input);\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport {\n field,\n RuntimeError,\n SmrtObject,\n type SmrtObjectOptions,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { invalidatePromptCache } from '../cache.js';\nimport { PromptRegistry } from '../prompt-registry.js';\nimport {\n APP_PROMPT_SCOPE_ID,\n type PromptLayer,\n type PromptPackageConfig,\n type PromptParams,\n} from '../types.js';\nimport {\n mergePromptLayers,\n normalizePromptLayer,\n parsePromptParams,\n serializePromptParams,\n validateModelName,\n validateProfileName,\n} from '../utils.js';\n\nexport interface PromptOverrideOptions extends SmrtObjectOptions {\n key?: string;\n tenantId?: string | null;\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n params?: string | PromptParams | null;\n}\n\ntype PromptOverrideIdentity = {\n key: string;\n tenantId: string | null;\n};\n\ntype PromptTransactionHandle = DatabaseInterface & {\n commit: () => Promise<void>;\n rollback: () => Promise<void>;\n};\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\n// Override rows are authorization state: any scope (app-wide, or another\n// tenant) can be written, and the object is not tenant-scoped by the request\n// context — `tenantId` is an ordinary settable field. Generated REST routes\n// and MCP tools only check authentication, so they are closed (#3013, mirrored\n// from `@happyvertical/smrt-features`). Hosts write overrides server-side\n// through `PromptOverrideService`, which requires an explicit authorizer for\n// every write (or `PromptOverrideCollection.setTemplateOverride()` /\n// `removeOverride()` after their own authorization decision). The CLI is\n// closed too: generated CLI commands dispatch through the generated API.\n@smrt({\n tableName: '_smrt_prompt_overrides',\n conflictColumns: ['key', 'context'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class PromptOverride extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-prompts\";\n @field({ required: true, requiredFor: 'identity' })\n key: string = '';\n\n // Not tenant-scoped (any scope is writable), but the value is a tenant id:\n // uuid on Postgres, so it compares with every other tenant_id column.\n @field({ sqlType: 'UUID', nullable: true })\n tenantId: string | null = null;\n\n @field({ type: 'text', nullable: true })\n template: string | null = null;\n\n @field({ type: 'text', nullable: true })\n profile: string | null = null;\n\n @field({ type: 'text', nullable: true })\n model: string | null = null;\n\n @field({ type: 'text', nullable: true })\n params: string | null = null;\n\n constructor(options: PromptOverrideOptions = {}) {\n super(options);\n\n if (options.key !== undefined) this.key = options.key;\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.template !== undefined) this.template = options.template;\n if (options.profile !== undefined) this.profile = options.profile;\n if (options.model !== undefined) this.model = options.model;\n if (options.params !== undefined) {\n if (typeof options.params === 'string' || options.params === null) {\n this.params = options.params;\n } else {\n this.params = serializePromptParams(options.params);\n }\n }\n }\n\n getParams(): PromptParams {\n return parsePromptParams(this.params);\n }\n\n setParams(params: PromptParams | null): void {\n this.params = serializePromptParams(params);\n }\n\n toPromptLayer(): PromptLayer {\n return {\n template: this.template,\n profile: this.profile,\n model: this.model,\n params: this.params === null ? null : this.getParams(),\n };\n }\n\n override async save(options?: SmrtSaveOptions): Promise<this> {\n const previousIdentity = await this.getPersistedIdentity();\n this.normalizeParamsForPersistence();\n await this.validatePromptOverride();\n // Use context as the uniqueness scope so app-level rows remain unique even\n // though tenantId is nullable and would otherwise allow multiple NULL rows.\n this.context = this.tenantId ?? APP_PROMPT_SCOPE_ID;\n const identityChanged =\n previousIdentity &&\n (previousIdentity.key !== this.key ||\n previousIdentity.tenantId !== this.tenantId);\n\n const result =\n identityChanged && previousIdentity\n ? await this.saveAfterIdentityChange(options)\n : await super.save(options);\n\n if (identityChanged && previousIdentity) {\n invalidatePromptCache(\n previousIdentity.key,\n previousIdentity.tenantId,\n this.db,\n );\n }\n invalidatePromptCache(this.key, this.tenantId, this.db);\n return result;\n }\n\n private async saveAfterIdentityChange(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n if (typeof this.db.beginTransaction === 'function') {\n return this.saveAfterIdentityChangeInTransaction(options);\n }\n\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n private async saveAfterIdentityChangeInTransaction(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const originalDb = this._db;\n const originalOptionsDb = this.options.db;\n const tx = (await this.db.beginTransaction?.()) as\n | PromptTransactionHandle\n | undefined;\n\n if (!tx) {\n return this.saveAfterIdentityChangeWithDeferredDelete(options);\n }\n\n try {\n this._db = tx;\n this.options.db = tx;\n // The caller's revision guards the ORIGINAL row (checked by the delete);\n // the replacement is a fresh insert and must not carry the update guard.\n await super.delete(\n options?.expectedUpdatedAt === undefined\n ? undefined\n : { expectedUpdatedAt: options.expectedUpdatedAt },\n );\n const result = await super.save(withoutRevisionGuard(options));\n await tx.commit();\n return result;\n } catch (error) {\n try {\n await tx.rollback();\n } catch {\n // Preserve the original save error; rollback failures are secondary.\n }\n throw error;\n } finally {\n this._db = originalDb;\n this.options.db = originalOptionsDb;\n }\n }\n\n private async saveAfterIdentityChangeWithDeferredDelete(\n options?: SmrtSaveOptions,\n ): Promise<this> {\n const previousId = this.id;\n if (!previousId) {\n return super.save(options);\n }\n\n // Without a transaction, a check here and the later unguarded delete are\n // not atomic: a concurrent update could be deleted. Fail closed rather\n // than accept a revision guard that cannot be honoured (#4408).\n if (options?.expectedUpdatedAt !== undefined) {\n throw new RuntimeError(\n `${this.constructor.name} identity changes honour expectedUpdatedAt only inside a transaction`,\n 'RUNTIME_REVISION_GUARD_REQUIRES_TRANSACTION',\n { className: this.constructor.name, id: previousId },\n );\n }\n\n const replacementId = crypto.randomUUID();\n let replacementSaved = false;\n this.id = replacementId;\n\n try {\n const result = await super.save(withoutRevisionGuard(options));\n replacementSaved = true;\n await this.db.delete(this.tableName, { id: previousId });\n return result;\n } catch (error) {\n if (replacementSaved) {\n try {\n await this.db.delete(this.tableName, { id: replacementId });\n } catch {\n // Best effort cleanup keeps the original row as the source of truth.\n }\n }\n\n this.id = previousId;\n throw error;\n }\n }\n\n override async delete(): Promise<void> {\n const key = this.key;\n const tenantId = this.tenantId;\n await super.delete();\n invalidatePromptCache(key, tenantId, this.db);\n }\n\n private async validatePromptOverride(): Promise<void> {\n if (!this.key || this.key.trim() === '') {\n throw new Error('PromptOverride.key is required');\n }\n\n const definition = PromptRegistry.get(this.key);\n if (!definition) {\n throw new Error(`Unknown prompt key \"${this.key}\"`);\n }\n\n const config = getPromptConfig();\n const editable = definition.editable;\n\n if (this.template !== null && !editable.template) {\n throw new Error(`Prompt \"${this.key}\" does not allow template overrides`);\n }\n\n if (this.profile !== null && !editable.profile) {\n throw new Error(`Prompt \"${this.key}\" does not allow profile overrides`);\n }\n\n if (this.model !== null && !editable.model) {\n throw new Error(`Prompt \"${this.key}\" does not allow model overrides`);\n }\n\n if (this.params !== null && !editable.params) {\n throw new Error(`Prompt \"${this.key}\" does not allow params overrides`);\n }\n\n if (this.params !== null) {\n try {\n const parsed = JSON.parse(this.params);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Prompt params must be a JSON object');\n }\n } catch (error) {\n throw new Error(\n `Prompt \"${this.key}\" has invalid params JSON: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n if (this.profile !== null) {\n validateProfileName(this.profile, config);\n }\n\n if (this.model !== null) {\n validateModelName(this.model, config);\n }\n\n const lowerLayers = await this.getLowerPrecedenceLayers();\n const currentLayer = this.toPromptLayer();\n const merged = mergePromptLayers(...lowerLayers, currentLayer);\n\n if (currentLayer.model && !merged.ai.profile) {\n throw new Error(\n `Prompt \"${this.key}\" model overrides require an effective prompt profile`,\n );\n }\n }\n\n private async getLowerPrecedenceLayers(): Promise<PromptLayer[]> {\n const definition = PromptRegistry.get(this.key);\n const config = getPromptConfig();\n const layers: PromptLayer[] = [];\n\n if (definition) {\n layers.push({\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n params: definition.ai.params,\n });\n }\n\n layers.push(normalizePromptLayer(config.prompts?.[this.key]));\n\n const { PromptOverrideCollection } = await import(\n '../collections/PromptOverrideCollection.js'\n );\n const collection = await PromptOverrideCollection.create({\n db: this.options.db ?? this.options.persistence,\n });\n\n if (this.tenantId) {\n const appOverride = await collection.getAppOverride(this.key, {\n excludeId: this.id ?? undefined,\n });\n if (appOverride) {\n layers.push(appOverride.toPromptLayer());\n }\n }\n\n return layers;\n }\n\n private normalizeParamsForPersistence(): void {\n const rawParams = this.params as unknown;\n\n if (rawParams === null || rawParams === undefined) {\n this.params = null;\n return;\n }\n\n if (typeof rawParams === 'string') {\n this.params = rawParams;\n return;\n }\n\n if (typeof rawParams === 'object' && !Array.isArray(rawParams)) {\n this.params = serializePromptParams(rawParams as PromptParams);\n return;\n }\n\n throw new Error(\n `Prompt \"${this.key}\" params must be a JSON object or JSON string`,\n );\n }\n\n private async getPersistedIdentity(): Promise<PromptOverrideIdentity | null> {\n if (!this.id) {\n return null;\n }\n\n const existing = await this.db.get(this.tableName, { id: this.id });\n if (!existing) {\n return null;\n }\n\n return {\n key: String((existing as Record<string, unknown>).key ?? this.key),\n tenantId:\n (existing as Record<string, unknown>).tenantId !== undefined\n ? ((existing as Record<string, unknown>).tenantId as string | null)\n : (((existing as Record<string, unknown>).tenant_id as\n | string\n | null\n | undefined) ?? null),\n };\n }\n}\n\n/** The replacement row of an identity change is an insert, not a guarded update. */\nfunction withoutRevisionGuard(\n options: SmrtSaveOptions | undefined,\n): SmrtSaveOptions | undefined {\n if (!options || options.expectedUpdatedAt === undefined) return options;\n const { expectedUpdatedAt: _expected, ...rest } = options;\n return rest;\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { PromptOverride } from '../models/PromptOverride.js';\nimport type { PromptOverrideScopeType } from '../types.js';\n\nexport class PromptOverrideCollection extends SmrtCollection<PromptOverride> {\n static readonly _itemClass = PromptOverride;\n\n private excludeOverrideId(\n items: PromptOverride[],\n excludeId?: string,\n ): PromptOverride[] {\n return items.filter((item) => (excludeId ? item.id !== excludeId : true));\n }\n\n async getAppOverride(\n key: string,\n options: { excludeId?: string } = {},\n ): Promise<PromptOverride | null> {\n const items = await this.list({ where: { key, tenantId: null } });\n return this.excludeOverrideId(items, options.excludeId)[0] ?? null;\n }\n\n async getTenantOverride(\n key: string,\n tenantId: string,\n options: { excludeId?: string } = {},\n ): Promise<PromptOverride | null> {\n const items = await this.list({ where: { key, tenantId } });\n return this.excludeOverrideId(items, options.excludeId)[0] ?? null;\n }\n\n async getResolutionLayers(\n key: string,\n tenantId?: string | null,\n options: { excludeId?: string } = {},\n ): Promise<{ app: PromptOverride | null; tenant: PromptOverride | null }> {\n const [app, tenant] = await Promise.all([\n this.getAppOverride(key, options),\n tenantId != null\n ? this.getTenantOverride(key, tenantId, options)\n : Promise.resolve(null),\n ]);\n\n return {\n app,\n tenant,\n };\n }\n\n /**\n * The override row for every key in `keys` at one scope, in a single query.\n *\n * Used by `PromptSettingsService.listPromptSettings()` to enumerate the\n * whole registry's override state without one round trip per key. Because\n * this is an enumeration read — a host-configured\n * `defaultListLimit`/`maxListLimit` on the collection's options would\n * silently drop keys past the cap, changing which prompts a management\n * screen reports as overridden, with no error (the #3056 hazard class in\n * `@happyvertical/smrt-features`'s `getOverrideMap`) — callers that need the\n * full map construct this collection through\n * `PromptSettingsService.create()`, which strips those bounds.\n */\n async getOverrideMapForKeys(\n keys: string[],\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<Map<string, PromptOverride>> {\n const result = new Map<string, PromptOverride>();\n if (keys.length === 0) {\n return result;\n }\n\n const tenantId = scopeType === 'app' ? null : scopeId;\n const rows = await this.list({ where: { key: keys, tenantId } });\n for (const row of rows) {\n result.set(row.key, row);\n }\n\n return result;\n }\n\n /** The override row for a scope request, in the vocabulary used at the write boundary. */\n async findByScope(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<PromptOverride | null> {\n return scopeType === 'app'\n ? this.getAppOverride(key)\n : this.getTenantOverride(key, scopeId);\n }\n\n /**\n * Set (or clear, with `template: null`) the `template` field of the override\n * row for one scope, creating the row if it did not exist. Other fields\n * (`profile`, `model`, `params`) on an existing row are left untouched, per\n * this package's field-by-field inheritance model.\n */\n async setTemplateOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n const existing = await this.findByScope(key, scopeType, scopeId);\n\n if (existing) {\n existing.template = template;\n await existing.save();\n return existing;\n }\n\n const created = await this.create({\n key,\n tenantId: scopeType === 'app' ? null : scopeId,\n template,\n });\n await created.save();\n return created;\n }\n\n /** Remove the override row for one scope entirely, if one exists. */\n async removeOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<boolean> {\n const existing = await this.findByScope(key, scopeType, scopeId);\n if (!existing) {\n return false;\n }\n\n await existing.delete();\n return true;\n }\n}\n","import type { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport type { PromptOverride } from './models/PromptOverride.js';\nimport { APP_PROMPT_SCOPE_ID, type PromptOverrideScopeType } from './types.js';\n\n/** One override write the host must authorize before it runs (mirrors #3013). */\nexport interface PromptOverrideWriteRequest {\n operation: 'set' | 'remove';\n key: string;\n scopeType: PromptOverrideScopeType;\n scopeId: string;\n /** Present for `set`. `null` clears the template field. */\n template?: string | null;\n}\n\n/**\n * The host's explicit authorization decision for one override write. Return\n * `true` only when the current caller may write that exact scope; anything\n * else denies.\n */\nexport type PromptOverrideAuthorizer = (\n request: PromptOverrideWriteRequest,\n) => boolean | Promise<boolean>;\n\n/** Thrown when the authorizer does not return `true`. Nothing is written. */\nexport class PromptOverrideAuthorizationError extends Error {\n readonly status = 403;\n constructor(readonly request: PromptOverrideWriteRequest) {\n super(\n `Prompt override ${request.operation} denied for ${request.scopeType} scope`,\n );\n this.name = 'PromptOverrideAuthorizationError';\n }\n}\n\n/**\n * Thrown when a write names a scope the resolver never reads: an unknown scope\n * type, an app scope other than {@link APP_PROMPT_SCOPE_ID}, or a blank /\n * untrimmed / non-string tenant id. Checked before the authorizer runs, so a\n * malformed tenant scope can never resolve to the app-wide row. Nothing is\n * written.\n */\nexport class InvalidPromptScopeError extends Error {\n readonly status = 400;\n constructor(\n readonly scopeType: string,\n readonly scopeId: string,\n reason: string,\n ) {\n super(`Invalid prompt override scope (${scopeType}): ${reason}`);\n this.name = 'InvalidPromptScopeError';\n }\n}\n\n/** Reject any scope the resolver does not read (see {@link InvalidPromptScopeError}). */\nexport function assertValidPromptScope(\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n): void {\n if (scopeType !== 'app' && scopeType !== 'tenant') {\n throw new InvalidPromptScopeError(\n String(scopeType),\n String(scopeId),\n 'scope type must be \"app\" or \"tenant\"',\n );\n }\n if (typeof scopeId !== 'string') {\n throw new InvalidPromptScopeError(\n scopeType,\n String(scopeId),\n 'scope id must be a string',\n );\n }\n if (scopeType === 'app' && scopeId !== APP_PROMPT_SCOPE_ID) {\n throw new InvalidPromptScopeError(\n scopeType,\n scopeId,\n `the app scope is only ever \"${APP_PROMPT_SCOPE_ID}\"`,\n );\n }\n if (\n scopeType === 'tenant' &&\n (!scopeId.trim() ||\n scopeId !== scopeId.trim() ||\n scopeId === APP_PROMPT_SCOPE_ID)\n ) {\n throw new InvalidPromptScopeError(\n scopeType,\n scopeId,\n 'a tenant scope id must be non-blank, already trimmed, and not the app scope id',\n );\n }\n}\n\n/**\n * Authorized write path for prompt overrides (mirrors `FeatureOverrideService`,\n * #3013). Override rows are authorization state for every scope and\n * `PromptOverride` is not tenant-scoped by the request context, so generated\n * surfaces are closed. Hosts that let callers change prompt text construct\n * this service with an authorizer bound to the current caller and write\n * through it; every write asks the authorizer first and fails closed.\n */\nexport class PromptOverrideService {\n constructor(\n private readonly overrides: PromptOverrideCollection,\n private readonly authorize: PromptOverrideAuthorizer,\n ) {}\n\n async setTemplateOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n await this.require({ operation: 'set', key, scopeType, scopeId, template });\n return this.overrides.setTemplateOverride(\n key,\n scopeType,\n scopeId,\n template,\n );\n }\n\n async removeOverride(\n key: string,\n scopeType: PromptOverrideScopeType,\n scopeId: string,\n ): Promise<boolean> {\n await this.require({ operation: 'remove', key, scopeType, scopeId });\n return this.overrides.removeOverride(key, scopeType, scopeId);\n }\n\n private async require(request: PromptOverrideWriteRequest): Promise<void> {\n assertValidPromptScope(request.scopeType, request.scopeId);\n let allowed = false;\n try {\n allowed = (await this.authorize(request)) === true;\n } catch {\n allowed = false;\n }\n if (!allowed) throw new PromptOverrideAuthorizationError(request);\n }\n}\n","import {\n type AsyncContext,\n createAsyncContext,\n} from '@happyvertical/smrt-core';\nimport type { PromptConfigOverrideInput } from './types.js';\n\n/**\n * Request-scoped ambient prompt overrides (#5065).\n *\n * The store sits on a `globalThis` key, like the prompt registry and tenancy's\n * context, so duplicated module instances share one scope stack.\n */\ntype ScopedOverrides = ReadonlyMap<string, PromptConfigOverrideInput>;\n\nconst STORAGE = Symbol.for('smrt.prompts.scopedOverrides');\nconst shared = globalThis as unknown as Record<symbol, unknown>;\n\nfunction context(): AsyncContext<ScopedOverrides> {\n shared[STORAGE] ??= createAsyncContext<ScopedOverrides>();\n return shared[STORAGE] as AsyncContext<ScopedOverrides>;\n}\n\n/** Whether an ambient scope can reach async work started inside it. */\nexport function scopedOverridesPropagate(): boolean {\n return context().propagatesAcrossAwait;\n}\n\n/** Run `fn` with `overrides` layered over any enclosing scope (inner wins per key). */\nexport function runWithScopedOverrides<T>(\n overrides: Readonly<Record<string, PromptConfigOverrideInput>>,\n fn: () => T,\n): T {\n const merged = new Map(context().getStore());\n for (const [key, override] of Object.entries(overrides)) {\n merged.set(key, { ...override });\n }\n return context().run(merged, fn);\n}\n\n/** The ambient override for `key` in the current async scope, if any. */\nexport function getScopedPromptOverride(\n key: string,\n): PromptConfigOverrideInput | undefined {\n return context().getStore()?.get(key);\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport { getTenantId } from '@happyvertical/smrt-tenancy';\nimport {\n getCachedPromptBase,\n getPromptCacheGeneration,\n setCachedPromptBase,\n} from './cache.js';\nimport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport { PromptRegistry } from './prompt-registry.js';\nimport {\n getScopedPromptOverride,\n runWithScopedOverrides,\n scopedOverridesPropagate,\n} from './scoped-overrides.js';\nimport type {\n PromptCacheValue,\n PromptConfigOverrideInput,\n PromptLayer,\n PromptPackageConfig,\n PromptSourceLayer,\n ResolvedPrompt,\n ResolvePromptOptions,\n} from './types.js';\nimport {\n buildResolvedAI,\n mergePromptLayers,\n normalizePromptLayer,\n promptTemplateHash,\n renderPromptTemplate,\n} from './utils.js';\n\n/** True when `layer` sets the template (null and undefined inherit). */\nfunction suppliesTemplate(layer: PromptLayer | null | undefined): boolean {\n return layer?.template !== undefined && layer.template !== null;\n}\n\n/** True when `layer` sets the profile (null and undefined inherit). */\nfunction suppliesProfile(layer: PromptLayer | null | undefined): boolean {\n return layer?.profile !== undefined && layer.profile !== null;\n}\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\nasync function loadPromptBase(\n key: string,\n options: ResolvePromptOptions,\n): Promise<PromptCacheValue> {\n const definition = PromptRegistry.get(key);\n if (!definition) {\n throw new Error(`Unknown prompt key \"${key}\"`);\n }\n\n const tenantId =\n options.tenantId !== undefined ? options.tenantId : (getTenantId() ?? null);\n\n let collection: PromptOverrideCollection | null = null;\n let cacheDb: ResolvePromptOptions['db'] | undefined = options.db;\n if (options.db) {\n const initializedCollection = await PromptOverrideCollection.create({\n db: options.db,\n });\n collection = initializedCollection;\n cacheDb = initializedCollection.db as ResolvePromptOptions['db'];\n }\n\n const cached = getCachedPromptBase(key, tenantId, cacheDb);\n if (cached) {\n return cached;\n }\n\n // Capture the invalidation generation before the asynchronous layer loads. A\n // write that lands while they are in flight bumps it, and the cache write\n // below is then refused rather than repopulating the key the write just\n // invalidated with the pre-write value.\n const loadedAtGeneration = getPromptCacheGeneration(key, cacheDb);\n\n const config = getPromptConfig();\n // Each layer is named so the resolution can report which one supplied the\n // effective template (the `promptLayer` usage tag, #4751).\n const layers: Array<{\n name: PromptCacheValue['templateLayer'];\n layer: PromptLayer;\n }> = [\n {\n name: 'default',\n layer: {\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n effort: definition.ai.effort ?? null,\n params: definition.ai.params,\n },\n },\n { name: 'config', layer: normalizePromptLayer(config.prompts?.[key]) },\n ];\n\n if (collection) {\n const stored = await collection.getResolutionLayers(key, tenantId);\n\n if (stored.app) {\n layers.push({ name: 'app', layer: stored.app.toPromptLayer() });\n }\n\n if (stored.tenant) {\n layers.push({ name: 'tenant', layer: stored.tenant.toPromptLayer() });\n }\n }\n\n const merged = mergePromptLayers(...layers.map(({ layer }) => layer));\n let templateLayer: PromptCacheValue['templateLayer'] = 'default';\n let profileLayer: PromptCacheValue['profileLayer'] = 'default';\n for (const { name, layer } of layers) {\n if (suppliesTemplate(layer)) templateLayer = name;\n if (suppliesProfile(layer)) profileLayer = name;\n }\n const value: PromptCacheValue = {\n key,\n template: merged.template,\n templateLayer,\n profileLayer,\n ai: merged.ai,\n };\n\n setCachedPromptBase(key, tenantId, cacheDb, value, loadedAtGeneration);\n return value;\n}\n\nexport async function resolvePrompt(\n key: string,\n options: ResolvePromptOptions = {},\n): Promise<ResolvedPrompt> {\n const config = getPromptConfig();\n const base = await loadPromptBase(key, options);\n // The ambient layer (#5065) is applied here, after the cached base, so a\n // draft never reaches the prompt cache. The explicit override sits above it.\n const ambientOverride = normalizePromptLayer(getScopedPromptOverride(key));\n const explicitOverride = normalizePromptLayer(options.override);\n const merged = mergePromptLayers(\n {\n template: base.template,\n profile: base.ai.profile ?? null,\n model: base.ai.model ?? null,\n effort: base.ai.effort ?? null,\n params: base.ai.params,\n },\n ambientOverride,\n explicitOverride,\n );\n\n const promptLayer: PromptSourceLayer =\n suppliesTemplate(ambientOverride) || suppliesTemplate(explicitOverride)\n ? 'runtime'\n : base.templateLayer;\n // Only a profile the code default itself supplied is exempt from\n // `allowedProfileNames`; any config, stored or runtime layer that sets one\n // (even the same tier again) is a choice the allow-list governs.\n const profileFromDefault =\n base.profileLayer === 'default' &&\n !suppliesProfile(ambientOverride) &&\n !suppliesProfile(explicitOverride);\n const ai = buildResolvedAI(merged.ai, config, {\n defaultProfile: profileFromDefault\n ? PromptRegistry.get(key)?.ai.profile\n : undefined,\n });\n if (ai.tier) {\n // The tier binds once, at call time, through the core inference seam\n // (`SmrtObject.prepareAiOperation()` / `getAiClient(tier)`), with this\n // key so prompt-scoped bindings apply (#4750).\n ai.promptKey = key;\n // The latency hint belongs to the call site, so only the code default\n // declares it (#4755).\n const latency = PromptRegistry.get(key)?.ai.latency;\n if (latency) ai.latency = latency;\n // The degradation floor is the code default's alone (#4752).\n const minimumTier = PromptRegistry.get(key)?.ai.minimumTier;\n if (minimumTier) ai.minimumTier = minimumTier;\n }\n\n return {\n key,\n template: merged.template,\n text: renderPromptTemplate(merged.template, options.variables),\n ai: {\n ...ai,\n usageTags: {\n promptKey: key,\n promptLayer,\n templateHash: await promptTemplateHash(merged.template),\n },\n },\n };\n}\n\n/**\n * Run `fn` with prompt overrides keyed by prompt key (#5065), so real call\n * sites that never forward `override` resolve a draft:\n *\n * ```ts\n * await withPromptOverrides(\n * { 'content.review': { template: draft, profile: 'cheap' } },\n * () => content.review(),\n * );\n * ```\n *\n * The layer sits above stored overrides and below an explicit\n * `resolvePrompt(key, { override })`, is tagged `promptLayer: 'runtime'`, and\n * never enters the prompt cache. Nested scopes: the inner wins per key, outer\n * keys stay visible. It follows `await` in the same async tree, not work\n * enqueued as a job. Throws unless the host set `allowScopedOverrides: true`\n * in the prompts config, when the runtime cannot propagate async context\n * (browsers: a silent no-op would run, and record, the live template), or\n * when an override is invalid (effort).\n */\nexport function withPromptOverrides<T>(\n overrides: Readonly<Record<string, PromptConfigOverrideInput>>,\n fn: () => T,\n): T {\n if (getPromptConfig().allowScopedOverrides !== true) {\n throw new Error(\n 'withPromptOverrides() is disabled: set `allowScopedOverrides: true` in the \"prompts\" package config to opt in',\n );\n }\n if (!scopedOverridesPropagate()) {\n throw new Error(\n 'withPromptOverrides() needs async context that survives await, which this runtime does not provide',\n );\n }\n for (const override of Object.values(overrides)) {\n normalizePromptLayer(override);\n }\n return runWithScopedOverrides(overrides, fn);\n}\n","import { getPackageConfig } from '@happyvertical/smrt-config';\nimport type {\n SmrtClassOptions,\n SmrtCollectionOptions,\n} from '@happyvertical/smrt-core';\nimport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nimport type { PromptOverride } from './models/PromptOverride.js';\nimport {\n assertValidPromptScope,\n type PromptOverrideAuthorizer,\n PromptOverrideService,\n} from './prompt-override-service.js';\nimport { PromptRegistry } from './prompt-registry.js';\nimport {\n APP_PROMPT_SCOPE_ID,\n type PromptDefinition,\n type PromptEditableConfig,\n type PromptLayer,\n type PromptOverrideScopeType,\n type PromptPackageConfig,\n} from './types.js';\nimport { mergePromptLayers, normalizePromptLayer } from './utils.js';\n\nfunction getPromptConfig(): PromptPackageConfig {\n return getPackageConfig<PromptPackageConfig>('prompts', {\n profiles: {},\n prompts: {},\n });\n}\n\n/**\n * The caller's options with its list bounds removed.\n *\n * `SmrtCollection.create()` forwards `defaultListLimit`/`maxListLimit` from\n * any options bag it is handed (#2367), so a host that sets those\n * application-wide would silently cap the bulk override-enumeration read\n * {@link PromptSettingsService.listPromptSettings} runs\n * (`getOverrideMapForKeys`) — a management screen showing every prompt, not a\n * user-facing page of results. A dropped row here is an override an operator\n * cannot see, and the prompt then reports as unoverridden, silently (the\n * `#3056` hazard class in `@happyvertical/smrt-features`'s `getOverrideMap`,\n * applied here proactively rather than left for a follow-up). Only the list\n * bounds are stripped; the database and every other option still apply.\n */\nfunction withoutListBounds(\n options: SmrtClassOptions | SmrtCollectionOptions,\n): SmrtCollectionOptions {\n return { ...options, defaultListLimit: undefined, maxListLimit: undefined };\n}\n\n/** The level that supplied a prompt's effective template. */\nexport type PromptSettingsLevel = 'default' | 'config' | 'app' | 'tenant';\n\n/**\n * One prompt, rendered for a management screen: the code-owned definition,\n * the text actually in effect for the requested tenant, and the raw override\n * state at each scope so the UI can show *why* it is in effect and what\n * reverting a scope produces.\n */\nexport interface PromptSettingsRow {\n /**\n * The persisted identifier. Renaming it orphans every existing override —\n * see the warning on {@link PromptSettingsService}.\n */\n key: string;\n /** Human description from the definition; may be empty. */\n description: string;\n /** Which fields a stored override may change, from the definition. */\n editable: PromptEditableConfig;\n /** The code-registered template, before the config layer or any override. */\n defaultTemplate: string;\n /**\n * What {@link resolvePrompt} resolves the template to for the requested\n * context — the text the application actually uses (unrendered: no\n * `{variable}` substitution).\n */\n effectiveTemplate: string;\n /** The app-level override row's `template` field, or `null` when there is none. */\n appTemplate: string | null;\n /**\n * The tenant-level override row's `template` field, or `null` when there is\n * none (or when no `tenantId` was requested).\n */\n tenantTemplate: string | null;\n /**\n * What the **app** scope's \"revert to default\" produces: the code default\n * merged with the config-file layer. Always knowable — nothing sits above\n * the app scope — unlike {@link inheritedTemplate}.\n */\n appDefaultTemplate: string;\n /**\n * What the **tenant** scope's \"revert to default\" produces: the code\n * default, the config-file layer, and the app-level override, merged with\n * no tenant override of its own. `null` when no `tenantId` was requested.\n *\n * This is the value a \"revert to default\" control for the tenant scope must\n * show or apply — never {@link defaultTemplate}, which ignores the config\n * layer and any app-level override and would silently discard them.\n */\n inheritedTemplate: string | null;\n /** Which level supplied {@link effectiveTemplate}. */\n supplyingLevel: PromptSettingsLevel;\n}\n\n/** Selection for {@link PromptSettingsService.listPromptSettings}. */\nexport interface ListPromptSettingsOptions {\n /**\n * Tenant whose overrides and effective template to report. Omit for an\n * app-only view.\n */\n tenantId?: string | null;\n /**\n * Restrict to an explicit allowlist of keys. Keys with no definition are\n * simply absent from the result — this filters, it does not validate.\n */\n keys?: string[];\n}\n\n/** One override write requested through {@link PromptSettingsService}. */\nexport interface SetPromptOverrideRequest {\n key: string;\n scopeType: PromptOverrideScopeType;\n scopeId: string;\n /** `null` clears the override, returning the scope to whatever it inherits. */\n template: string | null;\n}\n\n/**\n * Thrown when a write names a `key` that has no registered {@link PromptDefinition}.\n * Nothing is written.\n *\n * This is the generalized form of the per-app \"is this one of my keys?\" guard\n * every consumer would otherwise hand-roll to keep a form post from creating an\n * override for an arbitrary string.\n */\nexport class UnknownPromptKeyError extends Error {\n readonly status = 400;\n constructor(readonly key: string) {\n super(`Unknown prompt key: ${key}`);\n this.name = 'UnknownPromptKeyError';\n }\n}\n\n/**\n * Thrown when a write would set a field the definition's `editable` config\n * does not allow overriding. Nothing is written.\n */\nexport class PromptFieldNotEditableError extends Error {\n readonly status = 400;\n constructor(\n readonly key: string,\n readonly field: string,\n ) {\n super(`Prompt \"${key}\" does not allow ${field} overrides`);\n this.name = 'PromptFieldNotEditableError';\n }\n}\n\n/** Options for {@link PromptSettingsService.create}. */\nexport interface PromptSettingsServiceOptions {\n /**\n * The host's authorization decision for each override write, bound to the\n * current caller. **Omitting it makes the service read-only**: every write\n * then fails closed with `PromptOverrideAuthorizationError`. This package\n * never decides who may write.\n */\n authorize?: PromptOverrideAuthorizer;\n}\n\n/**\n * Read and write side of a prompt management screen, so consumers do not\n * re-derive the row shape or the unknown-key guard.\n *\n * **Authorization stays with the consumer.** This service makes no\n * authorization decision of its own: reads are unfiltered, and every write is\n * delegated to {@link PromptOverrideService}, which asks the host-supplied\n * {@link PromptOverrideAuthorizer} first and fails closed. Call it only from\n * server code that has already established who the caller is. See\n * `packages/prompts/README.md` for the consumer recipe.\n *\n * **Prompt keys are persisted identifiers.** Overrides are stored keyed by the\n * exact `key` string and resolved by that string at runtime. Renaming a key\n * orphans every existing override, silently reverting all tenants to the\n * registry default. Treat a key as immutable once shipped; a rename needs a\n * data migration, not an edit.\n */\nexport class PromptSettingsService {\n private readonly writes: PromptOverrideService;\n\n constructor(\n private readonly overrides: PromptOverrideCollection,\n authorize?: PromptOverrideAuthorizer,\n ) {\n this.writes = new PromptOverrideService(\n overrides,\n authorize ?? (() => false),\n );\n }\n\n /**\n * Build a service over the given database options.\n *\n * The internal bulk override-enumeration read {@link listPromptSettings}\n * runs is always issued without the caller's\n * `defaultListLimit`/`maxListLimit` — see {@link withoutListBounds}. Only\n * that read is affected; a `db` option is still honored.\n *\n * @param options - SMRT database options, as passed to any collection.\n * @param serviceOptions - Host authorizer. Omit for a read-only (load-function) service.\n */\n static async create(\n options: SmrtClassOptions = {},\n serviceOptions: PromptSettingsServiceOptions = {},\n ): Promise<PromptSettingsService> {\n const overrides = await PromptOverrideCollection.create(\n withoutListBounds(options),\n );\n return new PromptSettingsService(\n overrides as PromptOverrideCollection,\n serviceOptions.authorize,\n );\n }\n\n /**\n * One {@link PromptSettingsRow} per matching registered prompt, ordered by\n * key, so a rendered list is stable across loads.\n *\n * Makes no authorization decision — the caller has already decided that this\n * principal may see this tenant's prompts.\n */\n async listPromptSettings(\n options: ListPromptSettingsOptions = {},\n ): Promise<PromptSettingsRow[]> {\n const definitions = this.loadDefinitions(options);\n const keys = definitions.map((definition) => definition.key);\n const tenantId = options.tenantId;\n\n // Two bulk reads instead of up to 2N: see getOverrideMapForKeys for why\n // these must run through a bounds-stripped collection (#3056 class).\n const [appOverrides, tenantOverrides] = await Promise.all([\n this.overrides.getOverrideMapForKeys(keys, 'app', APP_PROMPT_SCOPE_ID),\n tenantId\n ? this.overrides.getOverrideMapForKeys(keys, 'tenant', tenantId)\n : Promise.resolve(new Map<string, PromptOverride>()),\n ]);\n\n return definitions.map((definition) =>\n this.toRow(\n definition,\n tenantId,\n appOverrides.get(definition.key) ?? null,\n tenantOverrides.get(definition.key) ?? null,\n ),\n );\n }\n\n /** The single row for one key, or `null` when no definition owns that key. */\n async getPromptSetting(\n key: string,\n tenantId?: string | null,\n ): Promise<PromptSettingsRow | null> {\n const definition = PromptRegistry.get(key);\n if (!definition) {\n return null;\n }\n\n const [appOverride, tenantOverride] = await Promise.all([\n this.overrides.getAppOverride(key),\n tenantId\n ? this.overrides.getTenantOverride(key, tenantId)\n : Promise.resolve(null),\n ]);\n\n return this.toRow(definition, tenantId, appOverride, tenantOverride);\n }\n\n /**\n * Apply one override change to the `template` field.\n *\n * Refuses any `key` without a registered {@link PromptDefinition}, any scope\n * the resolver would never read back, and a non-`null` template when the\n * definition's `editable.template` is `false`, then delegates to\n * {@link PromptOverrideService} so the host authorizer decides whether this\n * caller may write this scope. `template: null` clears the override.\n *\n * @throws {UnknownPromptKeyError} when the key has no definition.\n * @throws {InvalidPromptScopeError} when the scope is not one the resolver reads.\n * @throws {PromptFieldNotEditableError} when the definition disallows template overrides.\n * @throws `PromptOverrideAuthorizationError` when the authorizer declines.\n */\n async setPromptOverride(\n request: SetPromptOverrideRequest,\n ): Promise<PromptOverride> {\n const { key, scopeType, scopeId, template } = request;\n\n assertValidPromptScope(scopeType, scopeId);\n const definition = this.assertKnownPromptKey(key);\n\n if (template !== null && !definition.editable.template) {\n throw new PromptFieldNotEditableError(key, 'template');\n }\n\n return this.writes.setTemplateOverride(key, scopeType, scopeId, template);\n }\n\n /** {@link setPromptOverride} for the app-wide scope. */\n async setAppPromptOverride(\n key: string,\n template: string | null,\n ): Promise<PromptOverride> {\n return this.setPromptOverride({\n key,\n scopeType: 'app',\n scopeId: APP_PROMPT_SCOPE_ID,\n template,\n });\n }\n\n /** {@link setPromptOverride} for one tenant. */\n async setTenantPromptOverride(\n key: string,\n tenantId: string,\n template: string | null,\n ): Promise<PromptOverride> {\n return this.setPromptOverride({\n key,\n scopeType: 'tenant',\n scopeId: tenantId,\n template,\n });\n }\n\n private assertKnownPromptKey(key: string): PromptDefinition {\n const trimmed = typeof key === 'string' ? key.trim() : '';\n if (!trimmed || trimmed !== key) {\n throw new UnknownPromptKeyError(String(key));\n }\n const definition = PromptRegistry.get(trimmed);\n if (!definition) {\n throw new UnknownPromptKeyError(trimmed);\n }\n return definition;\n }\n\n private loadDefinitions(\n options: ListPromptSettingsOptions,\n ): PromptDefinition[] {\n const all = PromptRegistry.getAll();\n const allowed = options.keys ? new Set(options.keys) : null;\n const selected = allowed\n ? all.filter((definition) => allowed.has(definition.key))\n : all;\n\n return [...selected].sort((a, b) => a.key.localeCompare(b.key));\n }\n\n private toRow(\n definition: PromptDefinition,\n tenantId: string | null | undefined,\n appOverride: PromptOverride | null,\n tenantOverride: PromptOverride | null,\n ): PromptSettingsRow {\n const { key } = definition;\n const config = getPromptConfig();\n\n const registryLayer: PromptLayer = {\n template: definition.template,\n profile: definition.ai.profile ?? null,\n model: definition.ai.model ?? null,\n effort: definition.ai.effort ?? null,\n params: definition.ai.params,\n };\n const configLayer = normalizePromptLayer(config.prompts?.[key]);\n\n const appLayer = appOverride ? appOverride.toPromptLayer() : null;\n const tenantLayer = tenantOverride ? tenantOverride.toPromptLayer() : null;\n\n // What the \"app\" scope's own revert-to-default produces: registry + config\n // only. This intentionally excludes the app override itself, so it must\n // NOT be reused as the app-only effective value below (that bug shipped\n // and broke both `effectiveTemplate` when no tenant is requested and every\n // tenant's inherited fallback until caught by this package's own tests).\n const appDefaultMerge = mergePromptLayers(registryLayer, configLayer);\n const inheritedMerge = tenantId\n ? mergePromptLayers(registryLayer, configLayer, appLayer)\n : null;\n // The effective template always includes the app override when present;\n // only the tenant layer is conditional on a requested tenantId.\n const effectiveMerge = mergePromptLayers(\n registryLayer,\n configLayer,\n appLayer,\n tenantId ? tenantLayer : null,\n );\n\n const appTemplate = appOverride?.template ?? null;\n const tenantTemplate = tenantId ? (tenantOverride?.template ?? null) : null;\n\n let supplyingLevel: PromptSettingsLevel = 'default';\n if (tenantId && tenantTemplate != null) {\n supplyingLevel = 'tenant';\n } else if (appTemplate != null) {\n supplyingLevel = 'app';\n } else if (configLayer.template != null) {\n supplyingLevel = 'config';\n }\n\n return {\n key,\n description: definition.description,\n editable: definition.editable,\n defaultTemplate: definition.template,\n effectiveTemplate: effectiveMerge.template,\n appTemplate,\n tenantTemplate,\n appDefaultTemplate: appDefaultMerge.template,\n inheritedTemplate: inheritedMerge ? inheritedMerge.template : null,\n supplyingLevel,\n };\n }\n}\n\n/**\n * Reject a scope the resolver would never read back.\n *\n * `PromptOverride` rows are looked up by the exact `(key, tenantId)` pair —\n * `tenantId: null` for the app scope, a tenant id otherwise. A row written\n * under a scope nothing queries is invisible state: it never takes effect,\n * and the host authorizer cannot catch it, because `scopeType: 'app'` with\n * someone else's tenant id looks like an ordinary app write to an authorizer\n * that only gates the app scope.\n */\n","/**\n * @happyvertical/smrt-prompts\n *\n * Code-first prompts with config overrides, stored app/tenant overrides,\n * and runtime resolution helpers for SMRT applications.\n *\n * @packageDocumentation\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n\nexport { clearPromptCache, getPromptCacheTtlMs } from './cache.js';\nexport { PromptOverrideCollection } from './collections/PromptOverrideCollection.js';\nexport {\n PromptOverride,\n type PromptOverrideOptions,\n} from './models/PromptOverride.js';\nexport {\n InvalidPromptScopeError,\n PromptOverrideAuthorizationError,\n type PromptOverrideAuthorizer,\n PromptOverrideService,\n type PromptOverrideWriteRequest,\n} from './prompt-override-service.js';\nexport { definePrompt, PromptRegistry } from './prompt-registry.js';\nexport { resolvePrompt, withPromptOverrides } from './prompt-resolver.js';\nexport {\n type ListPromptSettingsOptions,\n PromptFieldNotEditableError,\n type PromptSettingsLevel,\n type PromptSettingsRow,\n PromptSettingsService,\n type PromptSettingsServiceOptions,\n type SetPromptOverrideRequest,\n UnknownPromptKeyError,\n} from './prompt-settings.js';\nexport type {\n NormalizedPromptAI,\n PromptAIInput,\n PromptConfigOverrideInput,\n PromptDefinition,\n PromptDefinitionInput,\n PromptEditableConfig,\n PromptLayer,\n PromptOverrideScopeType,\n PromptPackageConfig,\n PromptParams,\n PromptProfileConfig,\n PromptSourceLayer,\n PromptUsageTags,\n ResolvedPrompt,\n ResolvedPromptAI,\n ResolvePromptOptions,\n} from './types.js';\nexport { APP_PROMPT_SCOPE_ID } from './types.js';\nexport {\n type PromptMessageOptions,\n type PromptMessageOptionsExtra,\n promptMessageOptions,\n promptTemplateHash,\n trackedPromptCall,\n} from './utils.js';\n\n/** @internal */\nexport const PACKAGE_VERSION_INITIALIZED = true;\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,eAAe,wBAAwB,KAAK,MAAM,uzRAA2gU,CAAC;;;ACJ9jU,IAAM,sBAAsB;AAO5B,IAAM,8BAAc,IAAI,IAAwB;AAEhD,IAAM,mCAAmB,IAAI,IAAoB;AAMjD,IAAI,iBAAiB;AAQrB,IAAI,iBAAiB;AACrB,IAAM,gCAAgB,IAAI,QAAwB;AAClD,IAAI,WAAW;AAEf,SAAS,eAAe,IAAqB;CAC3C,IAAI,CAAC,IACH,OAAO;CAGT,IAAI,OAAO,OAAO,UAChB,OAAO,MAAM;CAGf,IAAI,OAAO,OAAO,UAAU;EAC1B,MAAM,WAAW;EACjB,IAAI,OAAO,SAAS,UAAU,YAAY;GACxC,IAAI,CAAC,cAAc,IAAI,QAAQ,GAC7B,cAAc,IAAI,UAAU,eAAe,YAAY;GAEzD,MAAM,YAAY,cAAc,IAAI,QAAQ;GAC5C,IAAI,WACF,OAAO;GAGT,OAAO;EACT;EAEA,IAAI;GACF,OAAO,aAAa,KAAK,UAAU,QAAQ;EAC7C,QAAQ;GACN,OAAO;EACT;CACF;CAEA,OAAO;AACT;AAEA,SAAS,cACP,KACA,UACA,IACQ;CACR,OAAO,GAAG,eAAe,EAAE,EAAC,IAAK,IAAG,IAAK,YAAY;AACvD;AAEA,SAAS,mBACP,KACA,IACQ;CACR,OAAO,GAAG,eAAe,EAAE,EAAC,IAAK;AACnC;AAEA,SAAS,eAAe,KAAa,IAAuC;CAC1E,iBAAiB,IAAI,mBAAmB,KAAK,EAAE,GAAG,gBAAgB;AACpE;AAEO,SAAS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mB;EACnB,MAAM,EAAE,QAAQ;EAChB,MAAM,SAAS,gBAAgB;EAE/B,MAAM,gBAA6B;GACjC,UAAU,WAAW;GACrB,SAAS,WAAW,GAAG,WAAW;GAClC,OAAO,WAAW,GAAG,SAAS;GAC9B,QAAQ,WAAW,GAAG,UAAU;GAChC,QAAQ,WAAW,GAAG;EACxB;EACA,MAAM,cAAc,qBAAqB,OAAO,UAAU,IAAI;EAE9D,MAAM,WAAW,cAAc,YAAY,cAAc,IAAI;EAC7D,MAAM,cAAc,iBAAiB,eAAe,cAAc,IAAI;EAOtE,MAAM,kBAAkB,kBAAkB,eAAe,WAAW;EACpE,MAAM,iBAAiB,WACnB,kBAAkB,eAAe,aAAa,QAAQ,IACtD;EAGJ,MAAM,iBAAiB,kBACrB,eACA,aACA,UACA,WAAW,cAAc,IAC3B;EAEA,MAAM,cAAc,aAAa,YAAY;EAC7C,MAAM,iBAAiB,WAAY,gBAAgB,YAAY,OAAQ;EAEvE,IAAI,iBAAsC;EAC1C,IAAI,YAAY,kBAAkB,MAChC,iBAAiB;OACnB,IAAW,eAAe,MACxB,iBAAiB;OACnB,IAAW,YAAY,YAAY,MACjC,iBAAiB;EAGnB,OAAO;GACL;GACA,aAAa,WAAW;GACxB,UAAU,WAAW;GACrB,iBAAiB,WAAW;GAC5B,mBAAmB,eAAe;GAClC;GACA;GACA,oBAAoB,gBAAgB;GACpC,mBAAmB,iBAAiB,eAAe,WAAW;GAC9D;EACF;CACF;AACF;;;ACjWO,IAAM,8BAA8B"}
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-prompts",
5
- "packageVersion": "0.74.1",
5
+ "packageVersion": "0.74.3",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-prompts:PromptOverrideCollection": {
8
8
  "name": "promptoverridecollection",
@@ -1,3 +1,24 @@
1
- import type { ResolvedPrompt, ResolvePromptOptions } from './types.js';
1
+ import type { PromptConfigOverrideInput, ResolvedPrompt, ResolvePromptOptions } from './types.js';
2
2
  export declare function resolvePrompt(key: string, options?: ResolvePromptOptions): Promise<ResolvedPrompt>;
3
+ /**
4
+ * Run `fn` with prompt overrides keyed by prompt key (#5065), so real call
5
+ * sites that never forward `override` resolve a draft:
6
+ *
7
+ * ```ts
8
+ * await withPromptOverrides(
9
+ * { 'content.review': { template: draft, profile: 'cheap' } },
10
+ * () => content.review(),
11
+ * );
12
+ * ```
13
+ *
14
+ * The layer sits above stored overrides and below an explicit
15
+ * `resolvePrompt(key, { override })`, is tagged `promptLayer: 'runtime'`, and
16
+ * never enters the prompt cache. Nested scopes: the inner wins per key, outer
17
+ * keys stay visible. It follows `await` in the same async tree, not work
18
+ * enqueued as a job. Throws unless the host set `allowScopedOverrides: true`
19
+ * in the prompts config, when the runtime cannot propagate async context
20
+ * (browsers: a silent no-op would run, and record, the live template), or
21
+ * when an override is invalid (effort).
22
+ */
23
+ export declare function withPromptOverrides<T>(overrides: Readonly<Record<string, PromptConfigOverrideInput>>, fn: () => T): T;
3
24
  //# sourceMappingURL=prompt-resolver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-resolver.d.ts","sourceRoot":"","sources":["../src/prompt-resolver.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAKV,cAAc,EACd,oBAAoB,EACrB,MAAM,YAAY,CAAC;AA8GpB,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,cAAc,CAAC,CAuDzB"}
1
+ {"version":3,"file":"prompt-resolver.d.ts","sourceRoot":"","sources":["../src/prompt-resolver.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAEV,yBAAyB,EAIzB,cAAc,EACd,oBAAoB,EACrB,MAAM,YAAY,CAAC;AA8GpB,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,cAAc,CAAC,CA8DzB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACnC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,CAAC,EAC9D,EAAE,EAAE,MAAM,CAAC,GACV,CAAC,CAeH"}
@@ -0,0 +1,8 @@
1
+ import type { PromptConfigOverrideInput } from './types.js';
2
+ /** Whether an ambient scope can reach async work started inside it. */
3
+ export declare function scopedOverridesPropagate(): boolean;
4
+ /** Run `fn` with `overrides` layered over any enclosing scope (inner wins per key). */
5
+ export declare function runWithScopedOverrides<T>(overrides: Readonly<Record<string, PromptConfigOverrideInput>>, fn: () => T): T;
6
+ /** The ambient override for `key` in the current async scope, if any. */
7
+ export declare function getScopedPromptOverride(key: string): PromptConfigOverrideInput | undefined;
8
+ //# sourceMappingURL=scoped-overrides.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scoped-overrides.d.ts","sourceRoot":"","sources":["../src/scoped-overrides.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAkB5D,uEAAuE;AACvE,wBAAgB,wBAAwB,IAAI,OAAO,CAElD;AAED,uFAAuF;AACvF,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,CAAC,EAC9D,EAAE,EAAE,MAAM,CAAC,GACV,CAAC,CAMH;AAED,yEAAyE;AACzE,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,MAAM,GACV,yBAAyB,GAAG,SAAS,CAEvC"}
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-prompts",
6
- "packageVersion": "0.74.1",
6
+ "packageVersion": "0.74.3",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "881544cb743b7cff36c159619c4c53cad5495c188acd8b1165a92a0da97501cb",
11
- "packageJson": "76d5e607c171995b045068b41d8a2c30980af047a6a0a167a131ca48415ea4a8",
12
- "agents": "a9d7c80306592b63a405d711c327c28f35376d9666b8cebbc0c8a6744e3059bd"
10
+ "manifest": "a9fa21f46ac187b5bd7bc11a5b26dc01ed5e02767df750af66d98072c4224211",
11
+ "packageJson": "88b86ba3decb14178277903da956427fa6f2ddbb548c84ac4e565e97858f4370",
12
+ "agents": "83f01f8adeeabc9813345d5fdbe49d74513259284804c88f1cb424c7da3d7966"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -369,6 +369,9 @@
369
369
  {
370
370
  "filePath": "src/public-surface.test.ts"
371
371
  },
372
+ {
373
+ "filePath": "src/scoped-overrides.test.ts"
374
+ },
372
375
  {
373
376
  "filePath": "src/tracked-prompt-call.test.ts"
374
377
  },
@@ -387,7 +390,7 @@
387
390
  "polymorphicAssociations": 0,
388
391
  "uuidColumns": 4
389
392
  },
390
- "agentDoc": "# smrt-prompts\n\nSMRT prompt registry and tenant-aware prompt override package. Code defines defaults; config layers and DB-stored overrides personalize at app and tenant levels.\n\n## Core pieces\n\n- `definePrompt()` registers code defaults in a global process registry (`globalThis.__smrtPromptRegistry`)\n- `resolvePrompt()` merges code defaults, file/config overrides (via `@happyvertical/smrt-config`), stored app-level overrides, stored tenant-level overrides, and a runtime override\n- `PromptOverride` (`_smrt_prompt_overrides` table) stores partial app-level and tenant-level overrides with write-time validation\n- `PromptOverrideCollection` — collection API, plus `setTemplateOverride()` / `removeOverride()` / `findByScope()` / `getOverrideMapForKeys()` for the write and enumeration paths below\n- `PromptOverrideService` — the only write path a host should use directly; asks a host-supplied authorizer before every write and fails closed (mirrors `FeatureOverrideService`, #3013); before authorizing it rejects any scope the resolver never reads (`InvalidPromptScopeError`: unknown type, app id other than `__app__`, blank/untrimmed/`__app__` tenant id), so a malformed tenant write cannot reach the app-wide row\n- `PromptSettingsService` — read/write helper for a management screen: `listPromptSettings()` returns one `PromptSettingsRow` per registered key (the effective template, `appTemplate`/`tenantTemplate` for the raw override at each scope, `appDefaultTemplate`/`inheritedTemplate` for what reverting each scope produces, and `supplyingLevel`); `setPromptOverride()` refuses unknown keys and fields the definition marks not editable, then delegates to `PromptOverrideService` (#3053)\n- `./svelte` subpath — `PromptSettingsPanel`, the presentational management panel (#3053)\n\n## Resolution layers (priority low → high)\n\n1. Code default — registered via `definePrompt({ key, template, ai })`\n2. File/config override — `getPackageConfig<PromptPackageConfig>('prompts', defaults)`\n3. App-level stored override — `PromptOverride` row with `tenantId = null`\n4. Tenant-level stored override — `PromptOverride` row with current tenant\n5. Runtime override — passed to `resolvePrompt({ overrides })`\n\nEach layer can override any subset of fields (template, profile, model, params). Inheritance is field-by-field.\n\n## Conventions\n\n- **Namespace prompt keys** by package or domain: `projects.issue.incorporateFeedback`, `content.summarize.headline`\n- **Stored overrides use nullable fields** so inheritance stays field-by-field — null means \"use the lower layer\"\n- **Provider selection is indirect** in v1: prompts select named profiles, and profiles resolve to provider/model in `smrt-config`\n- **`editable` flags are enforced on `PromptOverride.save()`** — definitions can lock specific fields against tenant override\n- **Reasoning effort** (#5005): `ai.effort` (`low | medium | high | xhigh | max`, core's `REASONING_EFFORTS`) is a named field, validated at the code default, config and runtime layers (an invalid value throws). Stored app/tenant overrides carry none, and params never carry `effort` or `reasoning` (stripped at every layer), so a tenant cannot widen it. `promptMessageOptions()` sends it as `reasoning: { effort }` with or without `routeTier`. Precedence: the caller's own `reasoning` (spread after), the prompt, the tier binding's `params.reasoning` (core spreads target params under call options), the provider default.\n- **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.\n\n## Generated surfaces\n\n`PromptOverride` ships with generated REST routes, MCP tools, and CLI commands\nclosed (`api: false`, `cli: false`, `mcp: false`, mirrors `FeatureOverride`,\n#3013). Override rows are authorization state for every scope and `tenantId` is\nan ordinary settable field, not request-derived tenant scoping — a generated\nauthentication-only surface would let any signed-in principal set another\ntenant's prompt text. Hosts write overrides server-side with\n`PromptOverrideService` (which requires an explicit authorizer for every\nwrite) or `PromptOverrideCollection.setTemplateOverride()` /\n`removeOverride()` only after their own authorization decision.\n\n## Management UI (`./svelte`)\n\n- Built like every other Svelte-shipping package here (`smrt-features`/`smrt-tenancy` are the closest models): `vite build --mode library && svelte-package -i src/svelte -o dist/svelte`, an `./svelte` export with a `svelte` condition, `svelte` as an **optional** peer dependency, plus `scripts/prune-svelte-package-artifacts.js` so `svelte-package` does not copy `__tests__/` into the published `dist/svelte`. The root export stays Svelte-free so server-only consumers are unaffected.\n- `PromptSettingsPanel` is presentational: rows and callbacks in, no fetching, no authorization. `src/svelte/types.ts` deliberately imports nothing from `smrt-core` or the `@smrt()` models, so the browser bundle stays thin; `PromptSettingsRow` is structurally assignable to `PromptSettingsView`.\n- Each row is its own `<form>` with a checkbox + `<textarea>` pair per scope (`tenantOverride`/`tenantTemplate`, and `appOverride`/`appTemplate` when `showApp` is set). The checkbox's presence in the submitted `FormData` — not whether the textarea is disabled — decides override vs. revert, because a plain HTML submit cannot un-disable a field the browser already marked disabled. `onSave` reads the same `FormData` when driving the panel from a client handler instead of `formAction`.\n- Two invariants, both regression-tested. (1) The \"revert\" preview never claims the bare registry default: `tenantRevertPreview()` shows `inheritedTemplate` (registry + config + app override), falling back to `appDefaultTemplate` only when the row does not carry it, and `appRevertPreview()` shows `appDefaultTemplate` (registry + config, never the app override itself). `PromptSettingsService` computes both explicitly rather than deriving one from the other — an earlier draft reused the app-only merge as the \"no tenant requested\" effective value and broke both. (2) The rows remount on `contextKey ?? prompts`, so an unsaved edit cannot survive a reload or a tenant switch and be submitted against the new rows.\n- **Authorization stays with the consumer.** `PromptSettingsService` reads are unfiltered and every write goes through `PromptOverrideService`; constructing the settings service without an `authorize` option makes it read-only (writes fail closed). Never add an authorization decision to this package.\n- `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.\n- `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.\n\n## Usage tags (#4751)\n\n`resolvePrompt()` returns `ai.usageTags = { promptKey, promptLayer,\ntemplateHash }`: `promptLayer` is the highest layer that supplied the template\n(`default | config | app | tenant | runtime`; a params-only layer does not\ncount), `templateHash` the first 12 hex chars of the SHA-256 of the unrendered\neffective template (Web Crypto, so the root stays free of `node:crypto`).\n`promptMessageOptions(ai, { usageTags? })` is the one helper that turns a\nresolution into `ai.message()` options; package copies re-export it. Tag\nprecedence, low to high: a `usageTags` object in params (tenant-editable, so\nreserved tags — identity, `runId`, tier, `substitutions`, `fusionKey` — are\ndropped from it), the resolution's tags, the caller's. Params never carry\n`tier`, `latency` or `promptKey` either: tier routing comes only from the\nvalidated profile. Every consumer\ncall site must forward them (`promptMessageOptions()` or a spread of\n`resolved.ai`); core lifts `promptKey` into `_smrt_ai_usage.prompt_key`\n(`../core/agents/ai-usage.md`).\n\n## Tracked calls (#5005)\n\n`trackedPromptCall(resolved)` turns a `resolvePrompt()` result into the\n`prompt` argument of core's tracked client\n(`createTrackedAiClient(...).client(trackedPromptCall(resolved), { runContext })`):\nthe key, the template hash, and the tier, latency and floor the prompt asks\nfor. Every tracked call carries a prompt key and `resolvePrompt` is where it\ncomes from; core never imports this package (the dependency stays core <-\nprompts). A prompt that makes calls from a package that is not a `SmrtObject`\n(chat, the app shell) registers with `definePrompt()` under its package\nnamespace (`chat.assistant.system`, `app-shell.assistant.system`) like any\nother, so app and tenant overrides apply to it.\n\n## Framework prompt tiers (#4755)\n\nEvery framework `definePrompt()` declares `ai.profile` as a tier: closed-\nvocabulary classification and yes/no predicates → `cheap`; summaries,\ndescriptions, translations, headlines → `good`; synthesis over user content\nthat is persisted or applied (feedback incorporation, reviews, corrections,\nfact extraction and reconciliation) → `great`; nothing defaults to `best`.\n`ai.latency` is `interactive` on request paths (chat, editor) and `background`\nfor jobs, else unset; only the code default declares it. Prompts that make no model call (persona instructions,\nchat system prompts) or call a non-text model (image generation) declare no\ntier. An explicit model on the call path wins over the tier. Each package's\n`AGENTS.md` records its choices; one test per package pins the tag set.\n\n## Prompt keys are persisted identifiers\n\nOverrides are stored keyed by the exact `key` string and resolved by that\nstring at runtime. **Renaming a key orphans every existing override and\nsilently reverts every tenant to the registry default**, and it also orphans\nthe key's `_smrt_ai_usage` series: history stays under the old `prompt_key`\nand outcome labels never join the new one. Treat a shipped key as immutable;\na rename needs a data migration over `_smrt_prompt_overrides.key`, not an edit.\n\n## Caching\n\n`resolvePrompt()` results are cached per `(key, tenantId)` with a TTL. The cache is invalidated on `PromptOverride.save()` and `.delete()`. Use `clearPromptCache()` for manual invalidation in tests.\n\n**A monotonic per-`(db, key)` invalidation generation guards the cache write.**\nA resolution captures `getPromptCacheGeneration(key, db)` before its\nasynchronous layer loads and hands it back to `setCachedPromptBase()`; a\nconcurrent `save()` / `delete()` bumps the generation and the in-flight\nresolution is then refused the cache write instead of repopulating the key it\njust invalidated with the pre-write value. Without it, \"a stale entry is never\nserved after a write\" held only until a read raced a write, and then failed for\nthe full 30s TTL (a raced `delete()` resurrected the deleted override).\nGenerations are tracked per `(db, key)`, not per tenant, because an app-level\nrow is inherited by every tenant. `clearPromptCache()` raises a single floor\n(`clearedThrough`) rather than resetting or per-key bumping: a key that has\nnever been invalidated has no map entry and reads as generation 0, so a per-key\nbump cannot reach it and a resolution that started before the clear would write\nits pre-clear value back. `smrt-languages` carries the same mechanism, keyed\nadditionally by locale. `smrt-playbooks` has the generation but not the floor\n(#2716).\n\n## Related\n\n- `@happyvertical/smrt-languages` — parallel package for language strings (uses the same architecture pattern)\n- `@happyvertical/smrt-features` — parallel package for feature flags\n",
393
+ "agentDoc": "# smrt-prompts\n\nSMRT prompt registry and tenant-aware prompt override package. Code defines defaults; config layers and DB-stored overrides personalize at app and tenant levels.\n\n## Core pieces\n\n- `definePrompt()` registers code defaults in a global process registry (`globalThis.__smrtPromptRegistry`)\n- `resolvePrompt()` merges code defaults, file/config overrides (via `@happyvertical/smrt-config`), stored app-level overrides, stored tenant-level overrides, and a runtime override\n- `PromptOverride` (`_smrt_prompt_overrides` table) stores partial app-level and tenant-level overrides with write-time validation\n- `PromptOverrideCollection` — collection API, plus `setTemplateOverride()` / `removeOverride()` / `findByScope()` / `getOverrideMapForKeys()` for the write and enumeration paths below\n- `PromptOverrideService` — the only write path a host should use directly; asks a host-supplied authorizer before every write and fails closed (mirrors `FeatureOverrideService`, #3013); before authorizing it rejects any scope the resolver never reads (`InvalidPromptScopeError`: unknown type, app id other than `__app__`, blank/untrimmed/`__app__` tenant id), so a malformed tenant write cannot reach the app-wide row\n- `PromptSettingsService` — read/write helper for a management screen: `listPromptSettings()` returns one `PromptSettingsRow` per registered key (the effective template, `appTemplate`/`tenantTemplate` for the raw override at each scope, `appDefaultTemplate`/`inheritedTemplate` for what reverting each scope produces, and `supplyingLevel`); `setPromptOverride()` refuses unknown keys and fields the definition marks not editable, then delegates to `PromptOverrideService` (#3053)\n- `./svelte` subpath — `PromptSettingsPanel`, the presentational management panel (#3053)\n\n## Resolution layers (priority low → high)\n\n1. Code default — registered via `definePrompt({ key, template, ai })`\n2. File/config override — `getPackageConfig<PromptPackageConfig>('prompts', defaults)`\n3. App-level stored override — `PromptOverride` row with `tenantId = null`\n4. Tenant-level stored override — `PromptOverride` row with current tenant\n5. Ambient scoped override (#5065) — `withPromptOverrides({ [key]: layer }, fn)`\n6. Runtime override — passed to `resolvePrompt(key, { override })`\n\nEach layer can override any subset of fields (template, profile, model, params). Inheritance is field-by-field.\n\n## Scoped ambient override (#5065)\n\n`withPromptOverrides(overrides, fn)` (`prompt-resolver.ts`, store in\n`scoped-overrides.ts`) runs `fn` so every `resolvePrompt()` inside it, with no\n`override` argument, applies `overrides[key]` as a layer between stored tenant\noverrides and the explicit `options.override` (which wins field by field). It is\nwhat lets a prompt arena run a draft through the app's real method. Facts:\n\n- Applied in `resolvePrompt()` after `loadPromptBase()`, so a draft never\n reaches the prompt cache; a template from it is tagged `promptLayer:\n 'runtime'` with the draft's `templateHash`.\n- Backed by core's `createAsyncContext()` (public from core), stored on\n `Symbol.for('smrt.prompts.scopedOverrides')` on `globalThis` so duplicated\n module instances share it. Nested scopes: inner wins per key (whole layer),\n outer keys stay visible.\n- Host opt-in, default off: `allowScopedOverrides: true` in the `prompts`\n package config; otherwise opening a scope throws. It also throws when the\n runtime's async context does not propagate across `await` (browsers), since\n a no-op would run and record the live template as the draft. Authorization\n stays with the host.\n- `allowedProfileNames`, `allowedModels` and effort validation apply exactly as\n to `options.override` (effort is validated when the scope opens).\n- It follows `await` in the same async tree only. Work enqueued as a job runs\n outside the scope and resolves the live template.\n\n## Conventions\n\n- **Namespace prompt keys** by package or domain: `projects.issue.incorporateFeedback`, `content.summarize.headline`\n- **Stored overrides use nullable fields** so inheritance stays field-by-field — null means \"use the lower layer\"\n- **Provider selection is indirect** in v1: prompts select named profiles, and profiles resolve to provider/model in `smrt-config`\n- **`editable` flags are enforced on `PromptOverride.save()`** — definitions can lock specific fields against tenant override\n- **Reasoning effort** (#5005): `ai.effort` (`low | medium | high | xhigh | max`, core's `REASONING_EFFORTS`) is a named field, validated at the code default, config and runtime layers (an invalid value throws). Stored app/tenant overrides carry none, and params never carry `effort` or `reasoning` (stripped at every layer), so a tenant cannot widen it. `promptMessageOptions()` sends it as `reasoning: { effort }` with or without `routeTier`. Precedence: the caller's own `reasoning` (spread after), the prompt, the tier binding's `params.reasoning` (core spreads target params under call options), the provider default.\n- **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.\n\n## Generated surfaces\n\n`PromptOverride` ships with generated REST routes, MCP tools, and CLI commands\nclosed (`api: false`, `cli: false`, `mcp: false`, mirrors `FeatureOverride`,\n#3013). Override rows are authorization state for every scope and `tenantId` is\nan ordinary settable field, not request-derived tenant scoping — a generated\nauthentication-only surface would let any signed-in principal set another\ntenant's prompt text. Hosts write overrides server-side with\n`PromptOverrideService` (which requires an explicit authorizer for every\nwrite) or `PromptOverrideCollection.setTemplateOverride()` /\n`removeOverride()` only after their own authorization decision.\n\n## Management UI (`./svelte`)\n\n- Built like every other Svelte-shipping package here (`smrt-features`/`smrt-tenancy` are the closest models): `vite build --mode library && svelte-package -i src/svelte -o dist/svelte`, an `./svelte` export with a `svelte` condition, `svelte` as an **optional** peer dependency, plus `scripts/prune-svelte-package-artifacts.js` so `svelte-package` does not copy `__tests__/` into the published `dist/svelte`. The root export stays Svelte-free so server-only consumers are unaffected.\n- `PromptSettingsPanel` is presentational: rows and callbacks in, no fetching, no authorization. `src/svelte/types.ts` deliberately imports nothing from `smrt-core` or the `@smrt()` models, so the browser bundle stays thin; `PromptSettingsRow` is structurally assignable to `PromptSettingsView`.\n- Each row is its own `<form>` with a checkbox + `<textarea>` pair per scope (`tenantOverride`/`tenantTemplate`, and `appOverride`/`appTemplate` when `showApp` is set). The checkbox's presence in the submitted `FormData` — not whether the textarea is disabled — decides override vs. revert, because a plain HTML submit cannot un-disable a field the browser already marked disabled. `onSave` reads the same `FormData` when driving the panel from a client handler instead of `formAction`.\n- Two invariants, both regression-tested. (1) The \"revert\" preview never claims the bare registry default: `tenantRevertPreview()` shows `inheritedTemplate` (registry + config + app override), falling back to `appDefaultTemplate` only when the row does not carry it, and `appRevertPreview()` shows `appDefaultTemplate` (registry + config, never the app override itself). `PromptSettingsService` computes both explicitly rather than deriving one from the other — an earlier draft reused the app-only merge as the \"no tenant requested\" effective value and broke both. (2) The rows remount on `contextKey ?? prompts`, so an unsaved edit cannot survive a reload or a tenant switch and be submitted against the new rows.\n- **Authorization stays with the consumer.** `PromptSettingsService` reads are unfiltered and every write goes through `PromptOverrideService`; constructing the settings service without an `authorize` option makes it read-only (writes fail closed). Never add an authorization decision to this package.\n- `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.\n- `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.\n\n## Usage tags (#4751)\n\n`resolvePrompt()` returns `ai.usageTags = { promptKey, promptLayer,\ntemplateHash }`: `promptLayer` is the highest layer that supplied the template\n(`default | config | app | tenant | runtime`; a params-only layer does not\ncount), `templateHash` the first 12 hex chars of the SHA-256 of the unrendered\neffective template (Web Crypto, so the root stays free of `node:crypto`).\n`promptMessageOptions(ai, { usageTags? })` is the one helper that turns a\nresolution into `ai.message()` options; package copies re-export it. Tag\nprecedence, low to high: a `usageTags` object in params (tenant-editable, so\nreserved tags — identity, `runId`, tier, `substitutions`, `fusionKey` — are\ndropped from it), the resolution's tags, the caller's. Params never carry\n`tier`, `latency` or `promptKey` either: tier routing comes only from the\nvalidated profile. Every consumer\ncall site must forward them (`promptMessageOptions()` or a spread of\n`resolved.ai`); core lifts `promptKey` into `_smrt_ai_usage.prompt_key`\n(`../core/agents/ai-usage.md`).\n\n## Tracked calls (#5005)\n\n`trackedPromptCall(resolved)` turns a `resolvePrompt()` result into the\n`prompt` argument of core's tracked client\n(`createTrackedAiClient(...).client(trackedPromptCall(resolved), { runContext })`):\nthe key, the template hash, and the tier, latency and floor the prompt asks\nfor. Every tracked call carries a prompt key and `resolvePrompt` is where it\ncomes from; core never imports this package (the dependency stays core <-\nprompts). A prompt that makes calls from a package that is not a `SmrtObject`\n(chat, the app shell) registers with `definePrompt()` under its package\nnamespace (`chat.assistant.system`, `app-shell.assistant.system`) like any\nother, so app and tenant overrides apply to it.\n\n## Framework prompt tiers (#4755)\n\nEvery framework `definePrompt()` declares `ai.profile` as a tier: closed-\nvocabulary classification and yes/no predicates → `cheap`; summaries,\ndescriptions, translations, headlines → `good`; synthesis over user content\nthat is persisted or applied (feedback incorporation, reviews, corrections,\nfact extraction and reconciliation) → `great`; nothing defaults to `best`.\n`ai.latency` is `interactive` on request paths (chat, editor) and `background`\nfor jobs, else unset; only the code default declares it. Prompts that make no model call (persona instructions,\nchat system prompts) or call a non-text model (image generation) declare no\ntier. An explicit model on the call path wins over the tier. Each package's\n`AGENTS.md` records its choices; one test per package pins the tag set.\n\n## Prompt keys are persisted identifiers\n\nOverrides are stored keyed by the exact `key` string and resolved by that\nstring at runtime. **Renaming a key orphans every existing override and\nsilently reverts every tenant to the registry default**, and it also orphans\nthe key's `_smrt_ai_usage` series: history stays under the old `prompt_key`\nand outcome labels never join the new one. Treat a shipped key as immutable;\na rename needs a data migration over `_smrt_prompt_overrides.key`, not an edit.\n\n## Caching\n\n`resolvePrompt()` results are cached per `(key, tenantId)` with a TTL. The cache is invalidated on `PromptOverride.save()` and `.delete()`. Use `clearPromptCache()` for manual invalidation in tests.\n\n**A monotonic per-`(db, key)` invalidation generation guards the cache write.**\nA resolution captures `getPromptCacheGeneration(key, db)` before its\nasynchronous layer loads and hands it back to `setCachedPromptBase()`; a\nconcurrent `save()` / `delete()` bumps the generation and the in-flight\nresolution is then refused the cache write instead of repopulating the key it\njust invalidated with the pre-write value. Without it, \"a stale entry is never\nserved after a write\" held only until a read raced a write, and then failed for\nthe full 30s TTL (a raced `delete()` resurrected the deleted override).\nGenerations are tracked per `(db, key)`, not per tenant, because an app-level\nrow is inherited by every tenant. `clearPromptCache()` raises a single floor\n(`clearedThrough`) rather than resetting or per-key bumping: a key that has\nnever been invalidated has no map entry and reads as generation 0, so a per-key\nbump cannot reach it and a resolution that started before the clear would write\nits pre-clear value back. `smrt-languages` carries the same mechanism, keyed\nadditionally by locale. `smrt-playbooks` has the generation but not the floor\n(#2716).\n\n## Related\n\n- `@happyvertical/smrt-languages` — parallel package for language strings (uses the same architecture pattern)\n- `@happyvertical/smrt-features` — parallel package for feature flags\n",
391
394
  "browser": {
392
395
  "status": "server-only",
393
396
  "issues": [
package/dist/types.d.ts CHANGED
@@ -91,6 +91,13 @@ export interface PromptPackageConfig {
91
91
  prompts?: Record<string, PromptConfigOverrideInput>;
92
92
  allowedProfileNames?: string[];
93
93
  allowedModels?: string[];
94
+ /**
95
+ * Host opt-in for `withPromptOverrides()` (#5065), default off. While off,
96
+ * opening a scope throws. Authorization stays with the host: set it only on
97
+ * a deployment (a prompt-arena or draft-preview surface) that has decided
98
+ * who may run draft templates.
99
+ */
100
+ allowScopedOverrides?: boolean;
94
101
  [key: string]: unknown;
95
102
  }
96
103
  export interface PromptLayer {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,aAAa,EACb,oBAAoB,EACpB,eAAe,EACf,gBAAgB,EACjB,MAAM,0BAA0B,CAAC;AAElC,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnD,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,OAAO,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AAG,IAAI,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,QAAQ,CAAC,EAAE,yBAAyB,CAAC;CACtC;AAED,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,gEAAgE;IAChE,aAAa,EAAE,OAAO,CAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC;IACrD;;;;OAIG;IACH,YAAY,EAAE,OAAO,CAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC;IACpD,EAAE,EAAE,kBAAkB,CAAC;CACxB"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n InferenceLatency,\n InferenceTier,\n InferenceTierRequest,\n ReasoningEffort,\n SmrtClassOptions,\n} from '@happyvertical/smrt-core';\n\nexport type PromptParams = Record<string, unknown>;\n\nexport interface PromptEditableConfig {\n template: boolean;\n profile: boolean;\n model: boolean;\n params: boolean;\n}\n\nexport interface PromptAIInput {\n /**\n * A configured profile name or an inference tier (`cheap`…`best`, `auto`;\n * #4750). Framework prompts declare a tier by the #4755 sweep rule.\n */\n profile?: string | null;\n /**\n * Latency hint for a tier binding (`interactive` on request paths,\n * `background` for jobs; #4755). Declared by the code default only: it is\n * a property of the call site, so config and overrides cannot change it.\n */\n latency?: InferenceLatency;\n model?: string | null;\n params?: PromptParams | null;\n temperature?: number;\n maxTokens?: number;\n /**\n * Lowest tier a tier-profile prompt may degrade to when its tier's chain\n * fails (#4752). Code default only: config and stored overrides cannot\n * lower it.\n */\n minimumTier?: InferenceTier;\n /**\n * Reasoning effort the prompt asks for (#5005): one of core's\n * `REASONING_EFFORTS`, validated, sent as `reasoning: { effort }`. A named\n * field, never a `params` entry: params (which a tenant override edits)\n * cannot carry `effort` or `reasoning`.\n */\n effort?: ReasoningEffort;\n [key: string]: unknown;\n}\n\nexport interface PromptDefinitionInput {\n key: string;\n template: string;\n /** Human-readable description shown by a management screen; defaults to `''`. */\n description?: string;\n ai?: PromptAIInput;\n editable?: Partial<PromptEditableConfig>;\n}\n\nexport interface PromptDefinition {\n key: string;\n template: string;\n description: string;\n ai: NormalizedPromptAI;\n editable: PromptEditableConfig;\n}\n\n/**\n * The two scopes a stored {@link PromptOverride} row may target: the\n * app-wide default (`tenantId` is `null`) or one tenant.\n */\nexport type PromptOverrideScopeType = 'app' | 'tenant';\n\n/**\n * Canonical scope id for the app-wide override scope, mirroring\n * `GLOBAL_FEATURE_SCOPE_ID` in `@happyvertical/smrt-features` (#3013). The\n * resolver and the write-authorization path both key off this exact value —\n * `PromptOverride` itself stores the app scope as `tenantId: null`, not this\n * string, so this constant only ever appears at the scope-request boundary\n * (`PromptOverrideService`, `PromptSettingsService`).\n */\nexport const APP_PROMPT_SCOPE_ID = '__app__';\n\nexport interface PromptProfileConfig {\n provider: string;\n model: string;\n params?: PromptParams | null;\n temperature?: number;\n maxTokens?: number;\n [key: string]: unknown;\n}\n\nexport interface PromptConfigOverrideInput {\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n /** Validated against core's `REASONING_EFFORTS`. */\n effort?: ReasoningEffort | null;\n params?: PromptParams | null;\n ai?: PromptAIInput | null;\n temperature?: number;\n maxTokens?: number;\n [key: string]: unknown;\n}\n\nexport interface PromptPackageConfig {\n profiles?: Record<string, PromptProfileConfig>;\n prompts?: Record<string, PromptConfigOverrideInput>;\n allowedProfileNames?: string[];\n allowedModels?: string[];\n [key: string]: unknown;\n}\n\nexport interface PromptLayer {\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n /** Code default, config or runtime only; stored overrides carry none. */\n effort?: ReasoningEffort | null;\n params?: PromptParams | null;\n}\n\nexport interface NormalizedPromptAI {\n profile?: string;\n model?: string;\n /** Code-declared latency hint; only a registered definition carries it. */\n latency?: InferenceLatency;\n /** From the code default only (#4752). */\n minimumTier?: InferenceTier;\n effort?: ReasoningEffort;\n params: PromptParams;\n}\n\n/**\n * The resolution layer that supplied a prompt's effective template, lowest to\n * highest priority. Recorded on every AI call as the `promptLayer` usage tag.\n */\nexport type PromptSourceLayer =\n | 'default'\n | 'config'\n | 'app'\n | 'tenant'\n | 'runtime';\n\n/**\n * Usage tags `resolvePrompt()` attaches to a resolution. They reach\n * `_smrt_ai_usage` through the AI SDK's per-call `usageTags`; `promptKey` is\n * also lifted into the indexed `prompt_key` column (#4751).\n */\nexport interface PromptUsageTags {\n /** The registered prompt key, e.g. `content.summarize.headline`. */\n promptKey: string;\n /** The highest layer that supplied the effective template. */\n promptLayer: PromptSourceLayer;\n /** First 12 hex chars of the SHA-256 of the effective (unrendered) template. */\n templateHash: string;\n [key: string]: string;\n}\n\nexport interface ResolvedPromptAI extends PromptParams {\n /**\n * Prompt-run observability tags (#4751). Always set by `resolvePrompt()`;\n * optional here so hand-built AI option objects stay assignable.\n */\n usageTags?: PromptUsageTags;\n profile?: string;\n provider?: string;\n model?: string;\n /**\n * Set when the effective profile is an inference tier name (or `auto`) with\n * no same-named entry in `PromptPackageConfig.profiles` (#4750). The tier\n * binds at call time through the core seam: forward `tier` and `promptKey`\n * to object AI operations (`prepareAiOperation()`), which pick the tier\n * client. `provider`/`model` stay unset unless the prompt names a model.\n */\n tier?: InferenceTierRequest;\n /** The prompt key, set with `tier` for the call-time resolver request. */\n promptKey?: string;\n /** Set with `tier`: the code default's latency hint (#4755). */\n latency?: InferenceLatency;\n /** The definition's `ai.minimumTier`, set with `tier` (#4752). */\n minimumTier?: InferenceTier;\n /** The prompt's validated reasoning effort (#5005). */\n effort?: ReasoningEffort;\n allowedModels?: string[];\n params: PromptParams;\n temperature?: number;\n maxTokens?: number;\n}\n\nexport interface ResolvedPrompt {\n key: string;\n template: string;\n text: string;\n ai: ResolvedPromptAI & { usageTags: PromptUsageTags };\n}\n\nexport interface ResolvePromptOptions {\n db?: SmrtClassOptions['db'];\n tenantId?: string | null;\n variables?: Record<string, unknown>;\n override?: PromptConfigOverrideInput;\n}\n\nexport interface PromptCacheValue {\n key: string;\n template: string;\n /** The highest stored/config layer that supplied `template`. */\n templateLayer: Exclude<PromptSourceLayer, 'runtime'>;\n /**\n * The highest stored/config layer that supplied `ai.profile`. Only a\n * profile the code default supplied is exempt from `allowedProfileNames`\n * (#4755).\n */\n profileLayer: Exclude<PromptSourceLayer, 'runtime'>;\n ai: NormalizedPromptAI;\n}\n"],"mappings":";AAgFO,IAAM,sBAAsB"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n InferenceLatency,\n InferenceTier,\n InferenceTierRequest,\n ReasoningEffort,\n SmrtClassOptions,\n} from '@happyvertical/smrt-core';\n\nexport type PromptParams = Record<string, unknown>;\n\nexport interface PromptEditableConfig {\n template: boolean;\n profile: boolean;\n model: boolean;\n params: boolean;\n}\n\nexport interface PromptAIInput {\n /**\n * A configured profile name or an inference tier (`cheap`…`best`, `auto`;\n * #4750). Framework prompts declare a tier by the #4755 sweep rule.\n */\n profile?: string | null;\n /**\n * Latency hint for a tier binding (`interactive` on request paths,\n * `background` for jobs; #4755). Declared by the code default only: it is\n * a property of the call site, so config and overrides cannot change it.\n */\n latency?: InferenceLatency;\n model?: string | null;\n params?: PromptParams | null;\n temperature?: number;\n maxTokens?: number;\n /**\n * Lowest tier a tier-profile prompt may degrade to when its tier's chain\n * fails (#4752). Code default only: config and stored overrides cannot\n * lower it.\n */\n minimumTier?: InferenceTier;\n /**\n * Reasoning effort the prompt asks for (#5005): one of core's\n * `REASONING_EFFORTS`, validated, sent as `reasoning: { effort }`. A named\n * field, never a `params` entry: params (which a tenant override edits)\n * cannot carry `effort` or `reasoning`.\n */\n effort?: ReasoningEffort;\n [key: string]: unknown;\n}\n\nexport interface PromptDefinitionInput {\n key: string;\n template: string;\n /** Human-readable description shown by a management screen; defaults to `''`. */\n description?: string;\n ai?: PromptAIInput;\n editable?: Partial<PromptEditableConfig>;\n}\n\nexport interface PromptDefinition {\n key: string;\n template: string;\n description: string;\n ai: NormalizedPromptAI;\n editable: PromptEditableConfig;\n}\n\n/**\n * The two scopes a stored {@link PromptOverride} row may target: the\n * app-wide default (`tenantId` is `null`) or one tenant.\n */\nexport type PromptOverrideScopeType = 'app' | 'tenant';\n\n/**\n * Canonical scope id for the app-wide override scope, mirroring\n * `GLOBAL_FEATURE_SCOPE_ID` in `@happyvertical/smrt-features` (#3013). The\n * resolver and the write-authorization path both key off this exact value —\n * `PromptOverride` itself stores the app scope as `tenantId: null`, not this\n * string, so this constant only ever appears at the scope-request boundary\n * (`PromptOverrideService`, `PromptSettingsService`).\n */\nexport const APP_PROMPT_SCOPE_ID = '__app__';\n\nexport interface PromptProfileConfig {\n provider: string;\n model: string;\n params?: PromptParams | null;\n temperature?: number;\n maxTokens?: number;\n [key: string]: unknown;\n}\n\nexport interface PromptConfigOverrideInput {\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n /** Validated against core's `REASONING_EFFORTS`. */\n effort?: ReasoningEffort | null;\n params?: PromptParams | null;\n ai?: PromptAIInput | null;\n temperature?: number;\n maxTokens?: number;\n [key: string]: unknown;\n}\n\nexport interface PromptPackageConfig {\n profiles?: Record<string, PromptProfileConfig>;\n prompts?: Record<string, PromptConfigOverrideInput>;\n allowedProfileNames?: string[];\n allowedModels?: string[];\n /**\n * Host opt-in for `withPromptOverrides()` (#5065), default off. While off,\n * opening a scope throws. Authorization stays with the host: set it only on\n * a deployment (a prompt-arena or draft-preview surface) that has decided\n * who may run draft templates.\n */\n allowScopedOverrides?: boolean;\n [key: string]: unknown;\n}\n\nexport interface PromptLayer {\n template?: string | null;\n profile?: string | null;\n model?: string | null;\n /** Code default, config or runtime only; stored overrides carry none. */\n effort?: ReasoningEffort | null;\n params?: PromptParams | null;\n}\n\nexport interface NormalizedPromptAI {\n profile?: string;\n model?: string;\n /** Code-declared latency hint; only a registered definition carries it. */\n latency?: InferenceLatency;\n /** From the code default only (#4752). */\n minimumTier?: InferenceTier;\n effort?: ReasoningEffort;\n params: PromptParams;\n}\n\n/**\n * The resolution layer that supplied a prompt's effective template, lowest to\n * highest priority. Recorded on every AI call as the `promptLayer` usage tag.\n */\nexport type PromptSourceLayer =\n | 'default'\n | 'config'\n | 'app'\n | 'tenant'\n | 'runtime';\n\n/**\n * Usage tags `resolvePrompt()` attaches to a resolution. They reach\n * `_smrt_ai_usage` through the AI SDK's per-call `usageTags`; `promptKey` is\n * also lifted into the indexed `prompt_key` column (#4751).\n */\nexport interface PromptUsageTags {\n /** The registered prompt key, e.g. `content.summarize.headline`. */\n promptKey: string;\n /** The highest layer that supplied the effective template. */\n promptLayer: PromptSourceLayer;\n /** First 12 hex chars of the SHA-256 of the effective (unrendered) template. */\n templateHash: string;\n [key: string]: string;\n}\n\nexport interface ResolvedPromptAI extends PromptParams {\n /**\n * Prompt-run observability tags (#4751). Always set by `resolvePrompt()`;\n * optional here so hand-built AI option objects stay assignable.\n */\n usageTags?: PromptUsageTags;\n profile?: string;\n provider?: string;\n model?: string;\n /**\n * Set when the effective profile is an inference tier name (or `auto`) with\n * no same-named entry in `PromptPackageConfig.profiles` (#4750). The tier\n * binds at call time through the core seam: forward `tier` and `promptKey`\n * to object AI operations (`prepareAiOperation()`), which pick the tier\n * client. `provider`/`model` stay unset unless the prompt names a model.\n */\n tier?: InferenceTierRequest;\n /** The prompt key, set with `tier` for the call-time resolver request. */\n promptKey?: string;\n /** Set with `tier`: the code default's latency hint (#4755). */\n latency?: InferenceLatency;\n /** The definition's `ai.minimumTier`, set with `tier` (#4752). */\n minimumTier?: InferenceTier;\n /** The prompt's validated reasoning effort (#5005). */\n effort?: ReasoningEffort;\n allowedModels?: string[];\n params: PromptParams;\n temperature?: number;\n maxTokens?: number;\n}\n\nexport interface ResolvedPrompt {\n key: string;\n template: string;\n text: string;\n ai: ResolvedPromptAI & { usageTags: PromptUsageTags };\n}\n\nexport interface ResolvePromptOptions {\n db?: SmrtClassOptions['db'];\n tenantId?: string | null;\n variables?: Record<string, unknown>;\n override?: PromptConfigOverrideInput;\n}\n\nexport interface PromptCacheValue {\n key: string;\n template: string;\n /** The highest stored/config layer that supplied `template`. */\n templateLayer: Exclude<PromptSourceLayer, 'runtime'>;\n /**\n * The highest stored/config layer that supplied `ai.profile`. Only a\n * profile the code default supplied is exempt from `allowedProfileNames`\n * (#4755).\n */\n profileLayer: Exclude<PromptSourceLayer, 'runtime'>;\n ai: NormalizedPromptAI;\n}\n"],"mappings":";AAgFO,IAAM,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-prompts",
3
- "version": "0.74.1",
3
+ "version": "0.74.3",
4
4
  "description": "Typed prompt registry, override resolution, and tenant-aware prompt settings for SMRT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,14 +24,14 @@
24
24
  "./manifest.json": "./dist/manifest.json"
25
25
  },
26
26
  "dependencies": {
27
- "@happyvertical/smrt-config": "0.74.1",
28
- "@happyvertical/smrt-core": "0.74.1",
29
- "@happyvertical/smrt-tenancy": "0.74.1",
30
- "@happyvertical/smrt-ui": "0.74.1",
27
+ "@happyvertical/smrt-config": "0.74.3",
28
+ "@happyvertical/smrt-core": "0.74.3",
29
+ "@happyvertical/smrt-tenancy": "0.74.3",
30
+ "@happyvertical/smrt-ui": "0.74.3",
31
31
  "@happyvertical/sql": "^0.116.6"
32
32
  },
33
33
  "devDependencies": {
34
- "@happyvertical/smrt-vitest": "0.74.1",
34
+ "@happyvertical/smrt-vitest": "0.74.3",
35
35
  "@sveltejs/package": "^2.5.8",
36
36
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
37
37
  "@types/node": "24.13.6",