@happyvertical/smrt-prompts 0.76.0 → 0.76.1
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 +3 -1
- package/README.md +135 -0
- package/dist/i18n/catalog.generated.d.ts.map +1 -1
- package/dist/i18n/catalog.js +172 -1
- package/dist/i18n/catalog.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +617 -68
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/prompt-arena-transports.d.ts +64 -0
- package/dist/prompt-arena-transports.d.ts.map +1 -0
- package/dist/prompt-arena.d.ts +127 -0
- package/dist/prompt-arena.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +16 -5
- package/dist/svelte/arena-types.d.ts +53 -0
- package/dist/svelte/arena-types.d.ts.map +1 -0
- package/dist/svelte/arena-types.js +1 -0
- package/dist/svelte/arena.messages.d.ts +37 -0
- package/dist/svelte/arena.messages.d.ts.map +1 -0
- package/dist/svelte/arena.messages.js +37 -0
- package/dist/svelte/components/PromptArenaPanel.svelte +223 -0
- package/dist/svelte/components/PromptArenaPanel.svelte.d.ts +17 -0
- package/dist/svelte/components/PromptArenaPanel.svelte.d.ts.map +1 -0
- package/dist/svelte/index.d.ts +2 -0
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +1 -0
- package/package.json +6 -6
package/dist/manifest.json
CHANGED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { SmrtMCPServer } from '@happyvertical/smrt-core';
|
|
2
|
+
import { type PromptArenaCaller, type PromptArenaDecision, type PromptArenaInput, type PromptArenaOperation, type PromptArenaService } from './prompt-arena.js';
|
|
3
|
+
/** Identical operation parameters for host REST routes and MCP tools. */
|
|
4
|
+
export interface PromptArenaOperationParams {
|
|
5
|
+
list: Record<string, never>;
|
|
6
|
+
execute: {
|
|
7
|
+
key: string;
|
|
8
|
+
draft: string;
|
|
9
|
+
inputs: Array<{
|
|
10
|
+
fixtureId: string;
|
|
11
|
+
} | {
|
|
12
|
+
input: PromptArenaInput;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
|
15
|
+
read: {
|
|
16
|
+
id: string;
|
|
17
|
+
};
|
|
18
|
+
judge: {
|
|
19
|
+
id: string;
|
|
20
|
+
pairId: string;
|
|
21
|
+
decision: PromptArenaDecision;
|
|
22
|
+
};
|
|
23
|
+
results: {
|
|
24
|
+
id: string;
|
|
25
|
+
};
|
|
26
|
+
promote: {
|
|
27
|
+
id: string;
|
|
28
|
+
scopeType: 'app' | 'tenant';
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export type PromptArenaPermissionRequest = {
|
|
32
|
+
[Operation in PromptArenaOperation]: {
|
|
33
|
+
operation: Operation;
|
|
34
|
+
caller: PromptArenaCaller;
|
|
35
|
+
params: PromptArenaOperationParams[Operation];
|
|
36
|
+
};
|
|
37
|
+
}[PromptArenaOperation];
|
|
38
|
+
export interface PromptArenaTransportOptions {
|
|
39
|
+
arena: PromptArenaService;
|
|
40
|
+
/** Host-authenticated request context for REST and MCP; never client arguments. */
|
|
41
|
+
currentCaller(): PromptArenaCaller | Promise<PromptArenaCaller>;
|
|
42
|
+
/**
|
|
43
|
+
* Bind the host's assertOperationPermission() here. It must throw on denial;
|
|
44
|
+
* explicit false / { allowed: false } decisions also deny. The same guard
|
|
45
|
+
* runs for both transports, in addition to the arena's own authorization.
|
|
46
|
+
*/
|
|
47
|
+
assertOperationPermission(request: PromptArenaPermissionRequest): void | boolean | {
|
|
48
|
+
allowed: boolean;
|
|
49
|
+
} | Promise<void | boolean | {
|
|
50
|
+
allowed: boolean;
|
|
51
|
+
}>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Real host-mountable REST handlers and MCP registrations over one dispatcher.
|
|
55
|
+
* The host authenticates both transports and establishes request-local tenancy.
|
|
56
|
+
* GET list/read/results accept query parameters; POST execute/judge/promote
|
|
57
|
+
* accept bounded JSON. The host owns URLs, CSRF protection and MCP sessions.
|
|
58
|
+
*/
|
|
59
|
+
export declare function createPromptArenaTransports(options: PromptArenaTransportOptions): {
|
|
60
|
+
api: Record<PromptArenaOperation, (request: Request) => Promise<Response>>;
|
|
61
|
+
/** Call once at host MCP startup, using core's existing server addTool API. */
|
|
62
|
+
registerMcp(server: Pick<SmrtMCPServer, "addTool">): void;
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=prompt-arena-transports.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-arena-transports.d.ts","sourceRoot":"","sources":["../src/prompt-arena-transports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAExB,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACxB,MAAM,mBAAmB,CAAC;AAE3B,yEAAyE;AACzE,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5B,OAAO,EAAE;QACP,GAAG,EAAE,MAAM,CAAC;QACZ,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,KAAK,CAAC;YAAE,SAAS,EAAE,MAAM,CAAA;SAAE,GAAG;YAAE,KAAK,EAAE,gBAAgB,CAAA;SAAE,CAAC,CAAC;KACpE,CAAC;IACF,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACrB,KAAK,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,mBAAmB,CAAA;KAAE,CAAC;IACrE,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACxB,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,KAAK,GAAG,QAAQ,CAAA;KAAE,CAAC;CACtD;AACD,MAAM,MAAM,4BAA4B,GAAG;KACxC,SAAS,IAAI,oBAAoB,GAAG;QACnC,SAAS,EAAE,SAAS,CAAC;QACrB,MAAM,EAAE,iBAAiB,CAAC;QAC1B,MAAM,EAAE,0BAA0B,CAAC,SAAS,CAAC,CAAC;KAC/C;CACF,CAAC,oBAAoB,CAAC,CAAC;AACxB,MAAM,WAAW,2BAA2B;IAC1C,KAAK,EAAE,kBAAkB,CAAC;IAC1B,mFAAmF;IACnF,aAAa,IAAI,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAChE;;;;OAIG;IACH,yBAAyB,CACvB,OAAO,EAAE,4BAA4B,GAEnC,IAAI,GACJ,OAAO,GACP;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GACpB,OAAO,CAAC,IAAI,GAAG,OAAO,GAAG;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CACpD;AAiKD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,2BAA2B;gDA8FQ,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC;IAGvE,+EAA+E;wBAC3D,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,GAAG,IAAI;EAa5D"}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createTrackedAiClient, type TrackedAiClientOptions } from '@happyvertical/smrt-core';
|
|
2
|
+
import type { DatabaseInterface } from '@happyvertical/sql';
|
|
3
|
+
import { type PromptSettingsService } from './prompt-settings.js';
|
|
4
|
+
import type { PromptOverrideScopeType } from './types.js';
|
|
5
|
+
/** JSON-only application input; each variant receives its own deep copy. */
|
|
6
|
+
export type PromptArenaInput = null | boolean | number | string | PromptArenaInput[] | {
|
|
7
|
+
[key: string]: PromptArenaInput;
|
|
8
|
+
};
|
|
9
|
+
export type PromptArenaSide = 'A' | 'B';
|
|
10
|
+
export type PromptArenaDecision = PromptArenaSide | 'tie';
|
|
11
|
+
export type PromptArenaOperation = 'list' | 'execute' | 'read' | 'judge' | 'results' | 'promote';
|
|
12
|
+
export interface PromptArenaCaller {
|
|
13
|
+
/** Derived by the host from its authenticated session, never request JSON. */
|
|
14
|
+
actorId: string;
|
|
15
|
+
tenantId: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface PromptArenaAccess extends PromptArenaCaller {
|
|
18
|
+
operation: PromptArenaOperation;
|
|
19
|
+
key?: string;
|
|
20
|
+
experimentId?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface PromptArenaRunner {
|
|
23
|
+
key: string;
|
|
24
|
+
fixtures?: Array<{
|
|
25
|
+
id: string;
|
|
26
|
+
label: string;
|
|
27
|
+
input: PromptArenaInput;
|
|
28
|
+
}>;
|
|
29
|
+
/** Validate application-specific input. Throw to reject it. */
|
|
30
|
+
validate(input: PromptArenaInput): void | Promise<void>;
|
|
31
|
+
/** Invoke the real application operation, injecting this tracked, fixed-settings client. */
|
|
32
|
+
run(input: PromptArenaInput, context: {
|
|
33
|
+
client: Awaited<ReturnType<ReturnType<typeof createTrackedAiClient>['client']>>;
|
|
34
|
+
db: DatabaseInterface;
|
|
35
|
+
tenantId: string | null;
|
|
36
|
+
}): Promise<string>;
|
|
37
|
+
}
|
|
38
|
+
export interface PromptArenaOptions {
|
|
39
|
+
/** Explicit server-side development-deployment opt-in; default off. */
|
|
40
|
+
enabled?: boolean;
|
|
41
|
+
db: DatabaseInterface;
|
|
42
|
+
/** Server-owned provider configuration, shared by both variants. */
|
|
43
|
+
ai: TrackedAiClientOptions['ai'];
|
|
44
|
+
/** Attribution for an already-constructed host client (as in core's tracked client). */
|
|
45
|
+
label?: TrackedAiClientOptions['label'];
|
|
46
|
+
authorize?: (request: PromptArenaAccess) => boolean | Promise<boolean>;
|
|
47
|
+
/** The existing independently authorized promotion write path. */
|
|
48
|
+
settings: PromptSettingsService;
|
|
49
|
+
}
|
|
50
|
+
export interface PromptArenaRunnable {
|
|
51
|
+
key: string;
|
|
52
|
+
template: string;
|
|
53
|
+
fixtures: Array<{
|
|
54
|
+
id: string;
|
|
55
|
+
label: string;
|
|
56
|
+
}>;
|
|
57
|
+
}
|
|
58
|
+
export interface PromptArenaPairView {
|
|
59
|
+
id: string;
|
|
60
|
+
/** Exact original application input associated with this pair's executions. */
|
|
61
|
+
input: PromptArenaInput;
|
|
62
|
+
status: 'complete' | 'failed';
|
|
63
|
+
outputs: Array<{
|
|
64
|
+
side: PromptArenaSide;
|
|
65
|
+
text?: string;
|
|
66
|
+
failed: boolean;
|
|
67
|
+
}>;
|
|
68
|
+
decision?: PromptArenaDecision;
|
|
69
|
+
/** Absent until a judgement commits. */
|
|
70
|
+
variants?: Array<{
|
|
71
|
+
side: PromptArenaSide;
|
|
72
|
+
variant: 'current' | 'draft';
|
|
73
|
+
runId: string;
|
|
74
|
+
usageIds: string[];
|
|
75
|
+
}>;
|
|
76
|
+
}
|
|
77
|
+
export interface PromptArenaExperimentView {
|
|
78
|
+
id: string;
|
|
79
|
+
key: string;
|
|
80
|
+
pairs: PromptArenaPairView[];
|
|
81
|
+
}
|
|
82
|
+
export interface PromptArenaMetric {
|
|
83
|
+
variant: 'current' | 'draft';
|
|
84
|
+
wins: number;
|
|
85
|
+
judgedPairs: number;
|
|
86
|
+
winRate: number | null;
|
|
87
|
+
tokens: number;
|
|
88
|
+
cost: number;
|
|
89
|
+
uncostedCalls: number;
|
|
90
|
+
latencyMs: number;
|
|
91
|
+
}
|
|
92
|
+
export declare class PromptArenaError extends Error {
|
|
93
|
+
readonly status: number;
|
|
94
|
+
constructor(message: string, status?: number);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Development-only, process-local arena. No generated routes or persistence of
|
|
98
|
+
* experiments. Keep one instance per host database, behind authenticated host
|
|
99
|
+
* endpoints. Every method fails closed through the host authorizer and checks
|
|
100
|
+
* the active tenant; registration is trusted server code, never an endpoint.
|
|
101
|
+
*/
|
|
102
|
+
export declare class PromptArenaService {
|
|
103
|
+
private readonly runners;
|
|
104
|
+
private readonly experiments;
|
|
105
|
+
private readonly options;
|
|
106
|
+
constructor(options: PromptArenaOptions);
|
|
107
|
+
register(runner: PromptArenaRunner): void;
|
|
108
|
+
list(caller: PromptArenaCaller): Promise<PromptArenaRunnable[]>;
|
|
109
|
+
execute(caller: PromptArenaCaller, request: {
|
|
110
|
+
key: string;
|
|
111
|
+
draft: string;
|
|
112
|
+
inputs: Array<{
|
|
113
|
+
fixtureId: string;
|
|
114
|
+
} | {
|
|
115
|
+
input: PromptArenaInput;
|
|
116
|
+
}>;
|
|
117
|
+
}): Promise<PromptArenaExperimentView>;
|
|
118
|
+
read(caller: PromptArenaCaller, id: string): Promise<PromptArenaExperimentView>;
|
|
119
|
+
judge(caller: PromptArenaCaller, id: string, pairId: string, decision: PromptArenaDecision): Promise<PromptArenaExperimentView>;
|
|
120
|
+
results(caller: PromptArenaCaller, id: string): Promise<PromptArenaMetric[]>;
|
|
121
|
+
promote(caller: PromptArenaCaller, id: string, scopeType: PromptOverrideScopeType): Promise<import("./index.js").PromptOverride>;
|
|
122
|
+
private require;
|
|
123
|
+
private owned;
|
|
124
|
+
private view;
|
|
125
|
+
private metrics;
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=prompt-arena.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-arena.d.ts","sourceRoot":"","sources":["../src/prompt-arena.ts"],"names":[],"mappings":"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"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-prompts",
|
|
6
|
-
"packageVersion": "0.76.
|
|
6
|
+
"packageVersion": "0.76.1",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "73f559e3598077f11382cc14d266aef5fff139aa64c6212e42118dcc09dbe478",
|
|
11
|
+
"packageJson": "e5712115a94524ff5ea1bebe6daab5109f4b67a88a1b460bd4cbce7fdda072d0",
|
|
12
|
+
"agents": "ce7cb8ce5050bfde84c379ead9506ef2945b00abedb5a4f620e8940dae61f774",
|
|
13
|
+
"moduleDoc:README.md": "c8d8e840153f61e59973c46956dacced1f770fc7b325a610d20add5eed64abcc"
|
|
13
14
|
},
|
|
14
15
|
"exports": [
|
|
15
16
|
".",
|
|
@@ -346,6 +347,9 @@
|
|
|
346
347
|
{
|
|
347
348
|
"filePath": "src/index.ts"
|
|
348
349
|
},
|
|
350
|
+
{
|
|
351
|
+
"filePath": "src/prompt-arena.test.ts"
|
|
352
|
+
},
|
|
349
353
|
{
|
|
350
354
|
"filePath": "src/prompt-effort.test.ts"
|
|
351
355
|
},
|
|
@@ -391,7 +395,14 @@
|
|
|
391
395
|
"polymorphicAssociations": 0,
|
|
392
396
|
"uuidColumns": 4
|
|
393
397
|
},
|
|
394
|
-
"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\n`./i18n/catalog` is a pure-data inventory of registered interface strings, generated\nwith `node scripts/generate-message-catalogs.mjs prompts`. It may be empty until\nthe package's interface strings are adopted; it never imports components.\n",
|
|
398
|
+
"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- `PromptArenaService` — opt-in process-local developer comparison runner; registered real host operations, scoped templates, fixed injected model settings, exact tracked run ids, blind pair judgements, transaction-bound evaluations, per-experiment metrics, and authorized winner promotion. Server integration: [README](README.md#developer-prompt-arena), [example](examples/arena-host.ts). Requires root DB outside transactions; host authentication and request-local tenant context.\n- `createPromptArenaTransports()` — six bounded REST Request handlers and six MCP registrations via core `SmrtMCPServer.addTool`, sharing one typed dispatcher and mandatory host `assertOperationPermission()`; caller identity comes from server context. The browser example calls those REST handlers. See [transport integration](README.md#matching-rest-mcp-and-ui-adapters).\n- `./svelte` subpath — `PromptSettingsPanel` and `PromptArenaPanel`, presentational management/arena panels (#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\n`./i18n/catalog` is a pure-data inventory of registered interface strings, generated\nwith `node scripts/generate-message-catalogs.mjs prompts`. It may be empty until\nthe package's interface strings are adopted; it never imports components.\n",
|
|
399
|
+
"moduleDocs": [
|
|
400
|
+
{
|
|
401
|
+
"path": "README.md",
|
|
402
|
+
"module": "README",
|
|
403
|
+
"content": "# @happyvertical/smrt-prompts\n\nTyped prompt definitions, tenant-aware prompt overrides, and runtime prompt resolution for s-m-r-t applications.\n\n## Installation\n\n```bash\npnpm add @happyvertical/smrt-prompts\n```\n\n## Quick start\n\n```typescript\nimport { definePrompt, resolvePrompt } from '@happyvertical/smrt-prompts';\n\n// 1. Register a prompt's defaults at startup\ndefinePrompt({\n key: 'projects.issue.incorporateFeedback',\n template: 'Rewrite the issue body incorporating this feedback: {feedback}',\n ai: {\n // An inference tier (`cheap | good | great | best | auto`) or a profile\n // named in config. With no `inference` config every tier runs on the\n // app's configured AI client.\n profile: 'great',\n params: { temperature: 0.4 },\n },\n});\n\n// 2. Resolve at runtime (auto-uses tenant context from AsyncLocalStorage)\nconst resolved = await resolvePrompt('projects.issue.incorporateFeedback', {\n vars: { feedback: '...' },\n});\n\n// resolved.template — the merged template with overrides applied\n// resolved.ai — the merged AI configuration (profile, model, params)\n```\n\n## What this package provides\n\n- **`definePrompt()`** — code-first prompt registration in a global process registry\n- **`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`\n- **`PromptOverride`** — model for app-level and tenant-level prompt settings, stored in `_smrt_prompt_overrides`\n- **`PromptOverrideService`** / **`PromptSettingsService`** — the authorized write path and the read/write helper for a management screen (see \"Management UI\" below)\n- **Named AI profiles** loaded from `packages.prompts` config — prompts select profile names, profiles resolve to provider/model in config\n- **Tracked calls and effort** — every model call carries a prompt key: `trackedPromptCall(resolved)` turns a resolution into the argument of core's tracked client, and `ai: { effort }` sets the prompt's reasoning effort (`low` to `max`). Concepts: [AI runs](../../docs/content/ai-runs.md)\n- **TTL cache** keyed by `(key, tenantId)`, invalidated on override save/delete\n\nStored overrides support partial fields, so applications can override only the template, profile, model, or AI params without forking the rest of a prompt.\n\n## Generated surfaces\n\n`PromptOverride` ships with generated REST routes, MCP tools, and CLI\ncommands closed (`api: false`, `cli: false`, `mcp: false`). Override rows are\nauthorization state for every scope, so write them only from server code\nthrough `PromptOverrideService`, which asks an authorizer you bind to the\ncurrent caller before every write and fails closed:\n\n```typescript\nconst service = new PromptOverrideService(overrides, (request) =>\n request.scopeType === 'tenant' && request.scopeId === session.tenantId &&\n session.permissions.has('prompts.manage'),\n);\nawait service.setTemplateOverride(key, 'tenant', session.tenantId, 'New text.');\n```\n\n## Management UI\n\nThe package ships the settings screen so consuming apps do not each rebuild\nit: `PromptSettingsService` (root export) produces the rows, and\n`PromptSettingsPanel` (the `./svelte` subpath) renders them. The root export\nstays Svelte-free, so a server-only consumer is unaffected; `svelte` is an\noptional peer dependency.\n\n### Consumer recipe\n\n**1. Register the prompt in code** (see Quick start above), including\n`editable` if you want tenants or the app-wide default to be overridable:\n\n```typescript\ndefinePrompt({\n key: 'projects.issue.incorporateFeedback',\n template: 'Rewrite the issue body incorporating this feedback: {feedback}',\n description: 'Rewrites an issue body from reviewer feedback.',\n editable: { template: true },\n});\n```\n\n**2. Load the rows in your server load.** The load is where *your* permission\ncheck lives — the package makes no authorization decision:\n\n```typescript\n// src/routes/settings/prompts/+page.server.ts\nexport async function load(event) {\n const auth = requirePermission(event, APP_PERMISSIONS.tenantAdmin);\n const settings = await PromptSettingsService.create({ db });\n return {\n tenantId: auth.tenantId,\n prompts: await settings.listPromptSettings({ tenantId: auth.tenantId }),\n };\n}\n```\n\n`listPromptSettings()` returns one `PromptSettingsRow` per registered\nkey — the effective template for the requested tenant, the raw override text\nat each scope (`appTemplate`/`tenantTemplate`), what reverting each scope\nproduces (`appDefaultTemplate`/`inheritedTemplate`), and `supplyingLevel`. The\nrow is structurally assignable to the panel's `PromptSettingsView`, so no\nmapping step is needed.\n\n**3. Render the panel:**\n\n```svelte\n<script lang=\"ts\">\n import { PromptSettingsPanel } from '@happyvertical/smrt-prompts/svelte';\n let { data, form } = $props();\n</script>\n\n<PromptSettingsPanel\n prompts={data.prompts}\n contextKey={data.tenantId}\n formAction=\"?/savePrompt\"\n message={form?.message}\n error={form?.error}\n/>\n```\n\nThe panel is presentational: it takes rows and callbacks, fetches nothing and\nauthorizes nothing. Each row renders the key, description, effective text, and\nwhich level supplied it, plus a checkbox + text editor for the tenant scope\n(and, when `showApp`/`appEditable` are set, the app scope). Unchecking the box\nreverts that scope — the preview text next to it shows exactly what reverting\nproduces. Supply `onSave` instead of `formAction` to drive it from a client\nhandler.\n\n**4. Wire the write with your own permission check.** `setPromptOverride()`\nrefuses any key without a definition and any field the definition's\n`editable` config disallows, then delegates to `PromptOverrideService`, which\nasks your authorizer and fails closed:\n\n```typescript\nexport const actions = {\n savePrompt: async (event) => {\n const auth = requirePermission(event, APP_PERMISSIONS.tenantAdmin);\n const form = await event.request.formData();\n const settings = await PromptSettingsService.create(\n { db },\n {\n // Your decision, bound to this caller. Returning anything but `true` denies.\n authorize: (request) =>\n request.scopeType === 'tenant' && request.scopeId === auth.tenantId,\n },\n );\n\n try {\n await settings.setTenantPromptOverride(\n String(form.get('key') ?? ''),\n auth.tenantId,\n form.has('tenantOverride') ? String(form.get('tenantTemplate') ?? '') : null,\n );\n } catch (error) {\n if (error instanceof UnknownPromptKeyError) return fail(400, { error: 'Unknown prompt.' });\n if (error instanceof PromptFieldNotEditableError) return fail(400, { error: 'Not editable.' });\n if (error instanceof InvalidPromptScopeError) return fail(400, { error: 'Invalid scope.' });\n if (error instanceof PromptOverrideAuthorizationError) return fail(403, { error: 'Not permitted.' });\n throw error;\n }\n return { message: 'Prompt overrides saved.' };\n },\n};\n```\n\nConstructing the service **without** an `authorize` option makes it\nread-only: every write then fails closed with\n`PromptOverrideAuthorizationError`. That is the right shape for a load\nfunction.\n\n### What the consumer still owns\n\n- the route, its navigation entry, and the page shell;\n- the permission check on both the load and the action;\n- the `authorize` callback (this package never decides who may write);\n- resolving the session's `tenantId` — a tenant id from the URL or a form\n field is a selector, not authorization;\n- registering prompts with `definePrompt()` at startup.\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**,\nsilently reverting all tenants to the registry default — the change looks\nharmless in a diff and shows up as prompt text mysteriously resetting. Treat a\nkey as immutable once shipped. A rename needs a data migration that rewrites\n`_smrt_prompt_overrides.key`, not an edit.\n\n## Documentation\n\n- See [`AGENTS.md`](./AGENTS.md) for package-internal patterns\n- See [`docs/content/standards.md`](../../docs/content/standards.md) for monorepo conventions\n- See related: [`@happyvertical/smrt-languages`](../languages) (mirrors this package for language strings), [`@happyvertical/smrt-features`](../features) (feature flags — same management-UI treatment, #3052)\n\n## Developer prompt arena\n\n`PromptArenaService` runs one current resolved template and one edited draft\nthrough a host-registered **in-process application operation**. It is opt-in:\nconstruct it with `enabled: true` only on a development deployment and enable\n`packages.prompts.allowScopedOverrides` in configuration. Keep one instance per\nhost database. There are no generated arena HTTP, CLI or MCP endpoints.\n\nThe [server integration example](examples/arena-host.ts) shows registration,\nfixtures, input validation, request-local authorization and handler adapters.\nThe host authenticates requests, establishes the active tenant, protects writes\nagainst CSRF, and bounds request bodies. Actor/tenant values come from the host\nsession; never accept them from request JSON. Every operation calls the host\n`authorize` function and fails closed; reads and writes also enforce the active\ntenant and the experiment's tenant. App/global scope is explicit `null`, never\nan omitted tenant filter. Promotion additionally passes through the existing\n`PromptSettingsService` authorizer and editable-template guard.\n\nThe registered runner validates JSON input, then invokes the **same application\nmethod** used by ordinary traffic with the supplied tracked AI client. That\nmethod resolves its prompt normally. The arena opens a scoped override per\nvariant and injects a client with one fixed host provider configuration and the\nbaseline resolved model/parameters/effort. It deliberately bypasses inference\ntier routing, so a live binding or tier fallback cannot change the comparison's\nmodel. Model options (including tool/schema options, when needed) must live in\nthe prompt's AI params: the injected client replaces call-site options with\nthis snapshot, preserving only cancellation signals. A supplied client can set\n`label` for correct provider/model cost attribution, as in core's tracked client.\nRunners must await their model calls and use the injected client; detached\nwork, job queues and runners that secretly call another client are unsupported.\nThe two variants receive independent copies of equivalent JSON input. The host\nrunner is trusted server code and must not embed template identity in outputs.\n\nEach pair retains its exact original JSON input, and each input/variant gets\nits own service-owned tracked run. Usage is read through\ncore's public `listAiUsage` with that exact run id and explicit tenant; another\nexperiment or ordinary call with the same prompt/model/hash never enters the\nscoreboard. An execution failure is visible and an incomplete pair cannot be\njudged. Blind responses expose only opaque pair ids, sides A/B and output text;\nrun ids, usage ids and current/draft identities are revealed only after judgement.\n`results()` returns an empty array until every completed pair has been judged:\nper-variant token totals could otherwise reveal identity from output length.\nAfter judging it reports wins, judged-pair count, win rate, summed usage duration,\ntokens and estimated USD cost per variant, with an explicit uncosted-call count.\nTies count as judged pairs and award neither variant a win. Promotion requires\na strict winner by wins and can target the app or the experiment's tenant.\n\nJudging uses core's current `recordAiEvaluation` API (the successor to\n`recordAiUsageOutcome`), targeting each exact run with the metric\n`prompt-arena.preference`. Both evaluations commit on the same transaction\nexecutor. Duplicate/concurrent votes replay the first decision; conflicting\nvotes return 409. A failed second write rolls back the first and permits retry.\nThe service requires a **root connection outside caller-owned transactions**.\nIt refuses SDK transaction handles, registered transaction handles and active\nframework transactions that share an embedded root connection. Hosts using\nopaque transaction wrappers must never supply those wrappers to the arena.\n\nExperiments, outputs, metrics snapshots and idempotency are **process-local**.\nRestarting the host loses them; persisted usage/evaluations remain. This first\nrelease is a single-process developer tool: it provides no shared sessions,\nretention policy or cross-worker routing. Hosts should restrict fixture size and\nrestart/discard the service when finished. Transcript replay, job runners,\nmodel-setting variants and more than two variants are deferred.\n\n## Matching REST, MCP and UI adapters\n\n`createPromptArenaTransports()` exports real host-mountable Request handlers and\nMCP registrations over one typed operation dispatcher. The\n[server integration example](examples/arena-host.ts) returns `{ api, registerMcp }`.\nMount the six handlers at host-owned routes, for example:\n\n| Handler | Method and example route | Parameters |\n|---|---|---|\n| `api.list` | `GET /api/prompt-arena/list` | none |\n| `api.execute` | `POST /api/prompt-arena/execute` | JSON `{ key, draft, inputs }` |\n| `api.read` | `GET /api/prompt-arena/read?id=...` | query `id` |\n| `api.judge` | `POST /api/prompt-arena/judge` | JSON `{ id, pairId, decision: 'A' \\| 'B' \\| 'tie' }` |\n| `api.results` | `GET /api/prompt-arena/results?id=...` | query `id` |\n| `api.promote` | `POST /api/prompt-arena/promote` | JSON `{ id, scopeType: 'app' \\| 'tenant' }` |\n\nAt host MCP startup call `registerMcp(mcpServer)` with core's `SmrtMCPServer`\n(or an adapter implementing its existing `addTool(tool, handler)` interface).\nIt registers `prompt_arena_list`, `prompt_arena_execute`, `prompt_arena_read`,\n`prompt_arena_judge`, `prompt_arena_results` and `prompt_arena_promote`, with the\nsame parameter schemas and the same service instance as REST. For a SvelteKit\nroute, exporting `const POST = ({ request }) => host.api.execute(request)`\nmounts the execute adapter; GET handlers mount the same way. Neither surface\nopens generated CRUD access to prompt-override authorization state.\n\nThe dispatcher obtains actor and tenant from `currentCaller()`, then invokes\nits mandatory host-bound `assertOperationPermission()` before calling the arena\nservice. UI actions call the REST adapters; they share the exact same host\npermission gate as MCP. For a host using `smrt-users`, bind its real operation\nguard to the request-local authenticated session and permission catalog:\n\n```typescript\nimport { assertOperationPermission } from '@happyvertical/smrt-users';\n\n// Inside createArenaHost options. The host registers the prompt_arena actions\n// in its permission catalog; smrt-users normalizes list/read to the read slug.\nassertOperationPermission: ({ operation, caller }) =>\n assertOperationPermission({\n db,\n collection: 'prompt_arena',\n action: operation,\n userId: caller.actorId,\n tenantId: caller.tenantId,\n catalog: hostPermissionCatalog,\n permissionSet: currentSession().permissions,\n allowSystemContextBypass: false,\n allowSuperAdminBypass: false,\n }),\n```\n\nThe host owns authentication, tenant context, route URLs, CSRF protection and\nMCP session setup. Operation parameters cannot supply actor/tenant/provider\nconfiguration: unknown properties, invalid enums and malformed input fail\nclosed. Request bodies are bounded; REST responses use `Cache-Control: no-store`.\nThe original arena authorizer and the independent override-write authorizer\nremain mandatory. The judgement operation returns only the updated experiment;\nfetching its scoreboard invokes the separate results permission.\n\nThe optional `PromptArenaPanel` from `@happyvertical/smrt-prompts/svelte` stays\npresentational. The [browser integration example](examples/arena-ui.svelte)\nshows callbacks using `fetch()` against the six REST adapters: execute posts an\nexperiment, judge posts the decision then gets results, and promote posts the\nwinning scope. `runners` comes from the list API via an authenticated host load.\nPass a stable user/tenant `contextKey` so the panel clears old drafts and results\nand ignores responses from the previous context. The host chooses promotion\nbuttons; server authorization applies independently to every surface.\nThe panel reads `prompts.arena.*` messages from the host's i18n context\nand falls back to its registered English defaults. Use\n`@happyvertical/smrt-prompts/i18n/catalog` to include these messages in the\nhost's application catalog.\n"
|
|
404
|
+
}
|
|
405
|
+
],
|
|
395
406
|
"browser": {
|
|
396
407
|
"status": "server-only",
|
|
397
408
|
"issues": [
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Browser-only presentation shapes. Structurally match the server service. */
|
|
2
|
+
export type PromptArenaJsonInput = null | boolean | number | string | PromptArenaJsonInput[] | {
|
|
3
|
+
[key: string]: PromptArenaJsonInput;
|
|
4
|
+
};
|
|
5
|
+
export interface PromptArenaRunnerView {
|
|
6
|
+
key: string;
|
|
7
|
+
template: string;
|
|
8
|
+
fixtures: Array<{
|
|
9
|
+
id: string;
|
|
10
|
+
label: string;
|
|
11
|
+
}>;
|
|
12
|
+
}
|
|
13
|
+
export interface PromptArenaView {
|
|
14
|
+
id: string;
|
|
15
|
+
key: string;
|
|
16
|
+
pairs: Array<{
|
|
17
|
+
id: string;
|
|
18
|
+
input: PromptArenaJsonInput;
|
|
19
|
+
status: 'complete' | 'failed';
|
|
20
|
+
outputs: Array<{
|
|
21
|
+
side: 'A' | 'B';
|
|
22
|
+
text?: string;
|
|
23
|
+
failed: boolean;
|
|
24
|
+
}>;
|
|
25
|
+
decision?: 'A' | 'B' | 'tie';
|
|
26
|
+
variants?: Array<{
|
|
27
|
+
side: 'A' | 'B';
|
|
28
|
+
variant: 'current' | 'draft';
|
|
29
|
+
runId: string;
|
|
30
|
+
usageIds: string[];
|
|
31
|
+
}>;
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export interface PromptArenaScoreView {
|
|
35
|
+
variant: 'current' | 'draft';
|
|
36
|
+
wins: number;
|
|
37
|
+
judgedPairs: number;
|
|
38
|
+
winRate: number | null;
|
|
39
|
+
tokens: number;
|
|
40
|
+
cost: number;
|
|
41
|
+
uncostedCalls: number;
|
|
42
|
+
latencyMs: number;
|
|
43
|
+
}
|
|
44
|
+
export interface PromptArenaRunRequest {
|
|
45
|
+
key: string;
|
|
46
|
+
draft: string;
|
|
47
|
+
inputs: Array<{
|
|
48
|
+
fixtureId: string;
|
|
49
|
+
} | {
|
|
50
|
+
input: PromptArenaJsonInput;
|
|
51
|
+
}>;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=arena-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"arena-types.d.ts","sourceRoot":"","sources":["../../src/svelte/arena-types.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,MAAM,MAAM,oBAAoB,GAC5B,IAAI,GACJ,OAAO,GACP,MAAM,GACN,MAAM,GACN,oBAAoB,EAAE,GACtB;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CAAA;CAAE,CAAC;AAC5C,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAChD;AACD,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,KAAK,CAAC;QACX,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,EAAE,oBAAoB,CAAC;QAC5B,MAAM,EAAE,UAAU,GAAG,QAAQ,CAAC;QAC9B,OAAO,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,GAAG,GAAG,GAAG,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,MAAM,EAAE,OAAO,CAAA;SAAE,CAAC,CAAC;QACpE,QAAQ,CAAC,EAAE,GAAG,GAAG,GAAG,GAAG,KAAK,CAAC;QAC7B,QAAQ,CAAC,EAAE,KAAK,CAAC;YACf,IAAI,EAAE,GAAG,GAAG,GAAG,CAAC;YAChB,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC;YAC7B,KAAK,EAAE,MAAM,CAAC;YACd,QAAQ,EAAE,MAAM,EAAE,CAAC;SACpB,CAAC,CAAC;KACJ,CAAC,CAAC;CACJ;AACD,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;CACnB;AACD,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,KAAK,EAAE,oBAAoB,CAAA;KAAE,CAAC,CAAC;CACxE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export declare const M: {
|
|
2
|
+
readonly 'prompts.arena.heading': "prompts.arena.heading";
|
|
3
|
+
readonly 'prompts.arena.empty': "prompts.arena.empty";
|
|
4
|
+
readonly 'prompts.arena.prompt': "prompts.arena.prompt";
|
|
5
|
+
readonly 'prompts.arena.choose_prompt': "prompts.arena.choose_prompt";
|
|
6
|
+
readonly 'prompts.arena.alternative_template': "prompts.arena.alternative_template";
|
|
7
|
+
readonly 'prompts.arena.input': "prompts.arena.input";
|
|
8
|
+
readonly 'prompts.arena.ad_hoc_json': "prompts.arena.ad_hoc_json";
|
|
9
|
+
readonly 'prompts.arena.application_input_json': "prompts.arena.application_input_json";
|
|
10
|
+
readonly 'prompts.arena.application_input': "prompts.arena.application_input";
|
|
11
|
+
readonly 'prompts.arena.run': "prompts.arena.run";
|
|
12
|
+
readonly 'prompts.arena.working': "prompts.arena.working";
|
|
13
|
+
readonly 'prompts.arena.request_failed': "prompts.arena.request_failed";
|
|
14
|
+
readonly 'prompts.arena.output_comparison': "prompts.arena.output_comparison";
|
|
15
|
+
readonly 'prompts.arena.output': "prompts.arena.output";
|
|
16
|
+
readonly 'prompts.arena.execution_failed': "prompts.arena.execution_failed";
|
|
17
|
+
readonly 'prompts.arena.judgement': "prompts.arena.judgement";
|
|
18
|
+
readonly 'prompts.arena.judge_outputs': "prompts.arena.judge_outputs";
|
|
19
|
+
readonly 'prompts.arena.prefer': "prompts.arena.prefer";
|
|
20
|
+
readonly 'prompts.arena.tie': "prompts.arena.tie";
|
|
21
|
+
readonly 'prompts.arena.tie_result': "prompts.arena.tie_result";
|
|
22
|
+
readonly 'prompts.arena.scoreboard': "prompts.arena.scoreboard";
|
|
23
|
+
readonly 'prompts.arena.variant': "prompts.arena.variant";
|
|
24
|
+
readonly 'prompts.arena.current_variant': "prompts.arena.current_variant";
|
|
25
|
+
readonly 'prompts.arena.draft_variant': "prompts.arena.draft_variant";
|
|
26
|
+
readonly 'prompts.arena.wins_judged': "prompts.arena.wins_judged";
|
|
27
|
+
readonly 'prompts.arena.win_rate': "prompts.arena.win_rate";
|
|
28
|
+
readonly 'prompts.arena.cost': "prompts.arena.cost";
|
|
29
|
+
readonly 'prompts.arena.latency': "prompts.arena.latency";
|
|
30
|
+
readonly 'prompts.arena.tokens': "prompts.arena.tokens";
|
|
31
|
+
readonly 'prompts.arena.uncosted': "prompts.arena.uncosted";
|
|
32
|
+
readonly 'prompts.arena.promote_app': "prompts.arena.promote_app";
|
|
33
|
+
readonly 'prompts.arena.promote_tenant': "prompts.arena.promote_tenant";
|
|
34
|
+
readonly 'prompts.arena.promoted_app': "prompts.arena.promoted_app";
|
|
35
|
+
readonly 'prompts.arena.promoted_tenant': "prompts.arena.promoted_tenant";
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=arena.messages.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"arena.messages.d.ts","sourceRoot":"","sources":["../../src/svelte/arena.messages.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCZ,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { defineMessages } from '@happyvertical/smrt-ui/i18n';
|
|
2
|
+
export const M = defineMessages({
|
|
3
|
+
'prompts.arena.heading': 'Prompt arena',
|
|
4
|
+
'prompts.arena.empty': 'No runnable prompts are available.',
|
|
5
|
+
'prompts.arena.prompt': 'Prompt',
|
|
6
|
+
'prompts.arena.choose_prompt': 'Choose a prompt',
|
|
7
|
+
'prompts.arena.alternative_template': 'Alternative template',
|
|
8
|
+
'prompts.arena.input': 'Input',
|
|
9
|
+
'prompts.arena.ad_hoc_json': 'Ad hoc JSON',
|
|
10
|
+
'prompts.arena.application_input_json': 'Application input (JSON)',
|
|
11
|
+
'prompts.arena.application_input': 'Application input',
|
|
12
|
+
'prompts.arena.run': 'Run comparison',
|
|
13
|
+
'prompts.arena.working': 'Working…',
|
|
14
|
+
'prompts.arena.request_failed': 'Arena request failed',
|
|
15
|
+
'prompts.arena.output_comparison': 'Output comparison',
|
|
16
|
+
'prompts.arena.output': 'Output {side}',
|
|
17
|
+
'prompts.arena.execution_failed': 'Execution failed. This pair cannot be judged.',
|
|
18
|
+
'prompts.arena.judgement': 'Judgement: {decision}',
|
|
19
|
+
'prompts.arena.judge_outputs': 'Judge outputs',
|
|
20
|
+
'prompts.arena.prefer': 'Prefer {side}',
|
|
21
|
+
'prompts.arena.tie': 'Tie',
|
|
22
|
+
'prompts.arena.tie_result': 'tie',
|
|
23
|
+
'prompts.arena.scoreboard': 'Experiment scoreboard',
|
|
24
|
+
'prompts.arena.variant': 'Variant',
|
|
25
|
+
'prompts.arena.current_variant': 'current',
|
|
26
|
+
'prompts.arena.draft_variant': 'draft',
|
|
27
|
+
'prompts.arena.wins_judged': 'Wins / judged',
|
|
28
|
+
'prompts.arena.win_rate': 'Win rate',
|
|
29
|
+
'prompts.arena.cost': 'Cost (USD)',
|
|
30
|
+
'prompts.arena.latency': 'Latency (ms)',
|
|
31
|
+
'prompts.arena.tokens': 'Tokens',
|
|
32
|
+
'prompts.arena.uncosted': ' ({calls} uncosted)',
|
|
33
|
+
'prompts.arena.promote_app': 'Promote winner to app',
|
|
34
|
+
'prompts.arena.promote_tenant': 'Promote winner to tenant',
|
|
35
|
+
'prompts.arena.promoted_app': 'Winning template promoted to app scope.',
|
|
36
|
+
'prompts.arena.promoted_tenant': 'Winning template promoted to tenant scope.',
|
|
37
|
+
});
|