@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/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { APP_PROMPT_SCOPE_ID } from "./types.js";
2
- import { INFERENCE_TIERS, ObjectRegistry, REASONING_EFFORTS, RuntimeError, SmrtCollection, SmrtObject, createAsyncContext, field, isInferenceTier, isInferenceTierRequest, isReasoningEffort, smrt } from "@happyvertical/smrt-core";
2
+ import { INFERENCE_TIERS, ObjectRegistry, REASONING_EFFORTS, RuntimeError, SmrtClass, SmrtCollection, SmrtObject, createAsyncContext, createTrackedAiClient, field, finishAiRun, isDatabaseTransactionActive, isInferenceTier, isInferenceTierRequest, isReasoningEffort, recordAiEvaluation, smrt, withAiRunTransaction } from "@happyvertical/smrt-core";
3
3
  import { getPackageConfig } from "@happyvertical/smrt-config";
4
4
  import { getTenantId } from "@happyvertical/smrt-tenancy";
5
+ import { parseJsonRequestBody } from "@happyvertical/smrt-core/http";
5
6
  //#region \0rolldown/runtime.js
6
7
  var __defProp$1 = Object.defineProperty;
7
8
  var __exportAll = (all, no_symbols) => {
@@ -15,7 +16,7 @@ var __exportAll = (all, no_symbols) => {
15
16
  };
16
17
  //#endregion
17
18
  //#region src/__smrt-register__.ts
18
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-prompts","packageVersion":"0.76.0","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
+ ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-prompts","packageVersion":"0.76.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}`));
19
20
  //#endregion
20
21
  //#region src/cache.ts
21
22
  var PROMPT_CACHE_TTL_MS = 3e4;
@@ -737,71 +738,6 @@ var PromptOverrideCollection = class extends SmrtCollection {
737
738
  }
738
739
  };
739
740
  //#endregion
740
- //#region src/prompt-override-service.ts
741
- var PromptOverrideAuthorizationError = class extends Error {
742
- constructor(request) {
743
- super(`Prompt override ${request.operation} denied for ${request.scopeType} scope`);
744
- this.request = request;
745
- this.name = "PromptOverrideAuthorizationError";
746
- }
747
- request;
748
- status = 403;
749
- };
750
- var InvalidPromptScopeError = class extends Error {
751
- constructor(scopeType, scopeId, reason) {
752
- super(`Invalid prompt override scope (${scopeType}): ${reason}`);
753
- this.scopeType = scopeType;
754
- this.scopeId = scopeId;
755
- this.name = "InvalidPromptScopeError";
756
- }
757
- scopeType;
758
- scopeId;
759
- status = 400;
760
- };
761
- function assertValidPromptScope(scopeType, scopeId) {
762
- if (scopeType !== "app" && scopeType !== "tenant") throw new InvalidPromptScopeError(String(scopeType), String(scopeId), "scope type must be \"app\" or \"tenant\"");
763
- if (typeof scopeId !== "string") throw new InvalidPromptScopeError(scopeType, String(scopeId), "scope id must be a string");
764
- if (scopeType === "app" && scopeId !== "__app__") throw new InvalidPromptScopeError(scopeType, scopeId, `the app scope is only ever "${APP_PROMPT_SCOPE_ID}"`);
765
- if (scopeType === "tenant" && (!scopeId.trim() || scopeId !== scopeId.trim() || scopeId === "__app__")) throw new InvalidPromptScopeError(scopeType, scopeId, "a tenant scope id must be non-blank, already trimmed, and not the app scope id");
766
- }
767
- var PromptOverrideService = class {
768
- constructor(overrides, authorize) {
769
- this.overrides = overrides;
770
- this.authorize = authorize;
771
- }
772
- overrides;
773
- authorize;
774
- async setTemplateOverride(key, scopeType, scopeId, template) {
775
- await this.require({
776
- operation: "set",
777
- key,
778
- scopeType,
779
- scopeId,
780
- template
781
- });
782
- return this.overrides.setTemplateOverride(key, scopeType, scopeId, template);
783
- }
784
- async removeOverride(key, scopeType, scopeId) {
785
- await this.require({
786
- operation: "remove",
787
- key,
788
- scopeType,
789
- scopeId
790
- });
791
- return this.overrides.removeOverride(key, scopeType, scopeId);
792
- }
793
- async require(request) {
794
- assertValidPromptScope(request.scopeType, request.scopeId);
795
- let allowed = false;
796
- try {
797
- allowed = await this.authorize(request) === true;
798
- } catch {
799
- allowed = false;
800
- }
801
- if (!allowed) throw new PromptOverrideAuthorizationError(request);
802
- }
803
- };
804
- //#endregion
805
741
  //#region src/scoped-overrides.ts
806
742
  var STORAGE = /* @__PURE__ */ Symbol.for("smrt.prompts.scopedOverrides");
807
743
  var shared = globalThis;
@@ -933,6 +869,71 @@ function withPromptOverrides(overrides, fn) {
933
869
  return runWithScopedOverrides(overrides, fn);
934
870
  }
935
871
  //#endregion
872
+ //#region src/prompt-override-service.ts
873
+ var PromptOverrideAuthorizationError = class extends Error {
874
+ constructor(request) {
875
+ super(`Prompt override ${request.operation} denied for ${request.scopeType} scope`);
876
+ this.request = request;
877
+ this.name = "PromptOverrideAuthorizationError";
878
+ }
879
+ request;
880
+ status = 403;
881
+ };
882
+ var InvalidPromptScopeError = class extends Error {
883
+ constructor(scopeType, scopeId, reason) {
884
+ super(`Invalid prompt override scope (${scopeType}): ${reason}`);
885
+ this.scopeType = scopeType;
886
+ this.scopeId = scopeId;
887
+ this.name = "InvalidPromptScopeError";
888
+ }
889
+ scopeType;
890
+ scopeId;
891
+ status = 400;
892
+ };
893
+ function assertValidPromptScope(scopeType, scopeId) {
894
+ if (scopeType !== "app" && scopeType !== "tenant") throw new InvalidPromptScopeError(String(scopeType), String(scopeId), "scope type must be \"app\" or \"tenant\"");
895
+ if (typeof scopeId !== "string") throw new InvalidPromptScopeError(scopeType, String(scopeId), "scope id must be a string");
896
+ if (scopeType === "app" && scopeId !== "__app__") throw new InvalidPromptScopeError(scopeType, scopeId, `the app scope is only ever "${APP_PROMPT_SCOPE_ID}"`);
897
+ if (scopeType === "tenant" && (!scopeId.trim() || scopeId !== scopeId.trim() || scopeId === "__app__")) throw new InvalidPromptScopeError(scopeType, scopeId, "a tenant scope id must be non-blank, already trimmed, and not the app scope id");
898
+ }
899
+ var PromptOverrideService = class {
900
+ constructor(overrides, authorize) {
901
+ this.overrides = overrides;
902
+ this.authorize = authorize;
903
+ }
904
+ overrides;
905
+ authorize;
906
+ async setTemplateOverride(key, scopeType, scopeId, template) {
907
+ await this.require({
908
+ operation: "set",
909
+ key,
910
+ scopeType,
911
+ scopeId,
912
+ template
913
+ });
914
+ return this.overrides.setTemplateOverride(key, scopeType, scopeId, template);
915
+ }
916
+ async removeOverride(key, scopeType, scopeId) {
917
+ await this.require({
918
+ operation: "remove",
919
+ key,
920
+ scopeType,
921
+ scopeId
922
+ });
923
+ return this.overrides.removeOverride(key, scopeType, scopeId);
924
+ }
925
+ async require(request) {
926
+ assertValidPromptScope(request.scopeType, request.scopeId);
927
+ let allowed = false;
928
+ try {
929
+ allowed = await this.authorize(request) === true;
930
+ } catch {
931
+ allowed = false;
932
+ }
933
+ if (!allowed) throw new PromptOverrideAuthorizationError(request);
934
+ }
935
+ };
936
+ //#endregion
936
937
  //#region src/prompt-settings.ts
937
938
  function getPromptConfig() {
938
939
  return getPackageConfig("prompts", {
@@ -1098,9 +1099,557 @@ var PromptSettingsService = class PromptSettingsService {
1098
1099
  }
1099
1100
  };
1100
1101
  //#endregion
1102
+ //#region src/prompt-arena.ts
1103
+ var PromptArenaError = class extends Error {
1104
+ constructor(message, status = 400) {
1105
+ super(message);
1106
+ this.status = status;
1107
+ this.name = "PromptArenaError";
1108
+ }
1109
+ status;
1110
+ };
1111
+ var UsageReader = class extends SmrtClass {
1112
+ ready() {
1113
+ return this.initialize();
1114
+ }
1115
+ };
1116
+ function copyInput(value) {
1117
+ const visit = (item, depth) => {
1118
+ if (depth > 30) throw new PromptArenaError("Input is too deeply nested");
1119
+ if (item === null || typeof item === "string" || typeof item === "boolean") return;
1120
+ if (typeof item === "number" && Number.isFinite(item)) return;
1121
+ if (Array.isArray(item)) {
1122
+ for (const child of item) visit(child, depth + 1);
1123
+ return;
1124
+ }
1125
+ if (typeof item === "object" && item && Object.getPrototypeOf(item) === Object.prototype) {
1126
+ for (const child of Object.values(item)) visit(child, depth + 1);
1127
+ return;
1128
+ }
1129
+ throw new PromptArenaError("Input must be finite JSON data");
1130
+ };
1131
+ visit(value, 0);
1132
+ const json = JSON.stringify(value);
1133
+ if (json.length > 1e5) throw new PromptArenaError("Input exceeds 100 KB");
1134
+ return JSON.parse(json);
1135
+ }
1136
+ var PromptArenaService = class {
1137
+ runners = /* @__PURE__ */ new Map();
1138
+ experiments = /* @__PURE__ */ new Map();
1139
+ options;
1140
+ constructor(options) {
1141
+ if (isDatabaseTransactionActive(options.db)) throw new PromptArenaError("Arena requires a root database outside a transaction");
1142
+ this.options = { ...options };
1143
+ }
1144
+ register(runner) {
1145
+ if (!PromptRegistry.get(runner.key) || this.runners.has(runner.key)) throw new PromptArenaError("Runner key must be registered exactly once");
1146
+ this.runners.set(runner.key, {
1147
+ ...runner,
1148
+ fixtures: runner.fixtures?.map((fixture) => ({
1149
+ ...fixture,
1150
+ input: copyInput(fixture.input)
1151
+ }))
1152
+ });
1153
+ }
1154
+ async list(caller) {
1155
+ caller = { ...caller };
1156
+ await this.require(caller, "list");
1157
+ const entries = [];
1158
+ for (const { key, fixtures } of this.runners.values()) {
1159
+ if (!PromptRegistry.get(key)?.editable.template) continue;
1160
+ try {
1161
+ await this.require(caller, "list", key);
1162
+ } catch {
1163
+ continue;
1164
+ }
1165
+ const prompt = await resolvePrompt(key, {
1166
+ db: this.options.db,
1167
+ tenantId: caller.tenantId
1168
+ });
1169
+ entries.push({
1170
+ key,
1171
+ template: prompt.template,
1172
+ fixtures: (fixtures ?? []).map(({ id, label }) => ({
1173
+ id,
1174
+ label
1175
+ }))
1176
+ });
1177
+ }
1178
+ return entries;
1179
+ }
1180
+ async execute(caller, request) {
1181
+ const scope = { ...caller };
1182
+ request = copyInput(request);
1183
+ await this.require(scope, "execute", request?.key);
1184
+ const runner = this.runners.get(request?.key);
1185
+ if (!runner || !PromptRegistry.get(request.key)) throw new PromptArenaError("Unknown runner");
1186
+ if (typeof request.draft !== "string" || !request.draft.trim() || request.draft.length > 1e5) throw new PromptArenaError("A draft template of at most 100 KB is required");
1187
+ if (!PromptRegistry.get(request.key)?.editable.template) throw new PromptFieldNotEditableError(request.key, "template");
1188
+ if (!Array.isArray(request.inputs) || request.inputs.length < 1 || request.inputs.length > 20) throw new PromptArenaError("Supply between one and twenty inputs");
1189
+ const inputs = await Promise.all(request.inputs.map(async (selection) => {
1190
+ if (!selection || typeof selection !== "object") throw new PromptArenaError("Invalid input selection");
1191
+ let value;
1192
+ if ("fixtureId" in selection && !("input" in selection)) {
1193
+ const fixture = runner.fixtures?.find(({ id }) => id === selection.fixtureId);
1194
+ if (!fixture) throw new PromptArenaError("Unknown fixture");
1195
+ value = fixture.input;
1196
+ } else if ("input" in selection && !("fixtureId" in selection)) value = selection.input;
1197
+ else throw new PromptArenaError("Choose a fixture or ad hoc input");
1198
+ const input = copyInput(value);
1199
+ await runner.validate(copyInput(input));
1200
+ return input;
1201
+ }));
1202
+ const baseline = await resolvePrompt(request.key, {
1203
+ db: this.options.db,
1204
+ tenantId: scope.tenantId
1205
+ });
1206
+ const experiment = {
1207
+ id: crypto.randomUUID(),
1208
+ key: request.key,
1209
+ tenantId: scope.tenantId,
1210
+ templates: [baseline.template, request.draft],
1211
+ pairs: []
1212
+ };
1213
+ const fixed = {
1214
+ model: baseline.ai.model ?? null,
1215
+ effort: baseline.ai.effort ?? null,
1216
+ params: structuredClone(baseline.ai.params)
1217
+ };
1218
+ const fixedOptions = promptMessageOptions(baseline.ai, { routeTier: false });
1219
+ const tracked = createTrackedAiClient({
1220
+ db: this.options.db,
1221
+ tenantId: scope.tenantId,
1222
+ ai: this.options.ai,
1223
+ label: this.options.label
1224
+ });
1225
+ const reader = new UsageReader({ db: this.options.db });
1226
+ await reader.ready();
1227
+ for (const input of inputs) {
1228
+ const pair = {
1229
+ id: crypto.randomUUID(),
1230
+ input: copyInput(input),
1231
+ executions: []
1232
+ };
1233
+ const reversed = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(1))[0] % 2 === 1;
1234
+ for (const index of [0, 1]) {
1235
+ const execution = {
1236
+ variant: index === 0 ? "current" : "draft",
1237
+ side: index === 0 !== reversed ? "A" : "B",
1238
+ runId: "",
1239
+ usage: [],
1240
+ failed: true
1241
+ };
1242
+ pair.executions.push(execution);
1243
+ await withPromptOverrides({ [experiment.key]: {
1244
+ ...fixed,
1245
+ template: experiment.templates[index]
1246
+ } }, async () => {
1247
+ const prompt = await resolvePrompt(experiment.key, {
1248
+ db: this.options.db,
1249
+ tenantId: scope.tenantId
1250
+ });
1251
+ const run = await tracked.openRun({
1252
+ type: "@happyvertical/smrt-prompts:arena",
1253
+ promptKey: experiment.key,
1254
+ templateHash: prompt.ai.usageTags.templateHash
1255
+ });
1256
+ execution.runId = run.run.id;
1257
+ try {
1258
+ const inner = await tracked.client({
1259
+ ...trackedPromptCall(prompt),
1260
+ tier: void 0
1261
+ }, { runContext: run.context });
1262
+ const settings = {
1263
+ ...fixedOptions,
1264
+ usageTags: prompt.ai.usageTags
1265
+ };
1266
+ const client = new Proxy(inner, { get(target, property, receiver) {
1267
+ const fn = Reflect.get(target, property, receiver);
1268
+ if (typeof fn !== "function") return fn;
1269
+ if (![
1270
+ "message",
1271
+ "chat",
1272
+ "complete",
1273
+ "stream"
1274
+ ].includes(String(property))) return fn.bind(target);
1275
+ return (value, options) => fn.call(target, value, {
1276
+ ...structuredClone(settings),
1277
+ ...options?.signal ? { signal: options.signal } : {}
1278
+ });
1279
+ } });
1280
+ const text = await runner.run(copyInput(input), {
1281
+ client,
1282
+ db: this.options.db,
1283
+ tenantId: scope.tenantId
1284
+ });
1285
+ if (typeof text !== "string") throw new PromptArenaError("Runner must return text");
1286
+ execution.usage = await reader.listAiUsage({
1287
+ runId: run.run.id,
1288
+ tenantId: scope.tenantId
1289
+ });
1290
+ if (!execution.usage.length) throw new PromptArenaError("Runner produced no tracked usage");
1291
+ execution.text = text;
1292
+ await finishAiRun(this.options.db, run.run.id, { status: "done" });
1293
+ execution.failed = false;
1294
+ } catch {
1295
+ execution.usage = await reader.listAiUsage({
1296
+ runId: run.run.id,
1297
+ tenantId: scope.tenantId
1298
+ });
1299
+ await finishAiRun(this.options.db, run.run.id, { status: "failed" });
1300
+ }
1301
+ });
1302
+ }
1303
+ experiment.pairs.push(pair);
1304
+ }
1305
+ this.experiments.set(experiment.id, experiment);
1306
+ return this.view(experiment);
1307
+ }
1308
+ async read(caller, id) {
1309
+ return this.view(await this.owned(caller, id, "read"));
1310
+ }
1311
+ async judge(caller, id, pairId, decision) {
1312
+ caller = { ...caller };
1313
+ const experiment = await this.owned(caller, id, "judge");
1314
+ if (![
1315
+ "A",
1316
+ "B",
1317
+ "tie"
1318
+ ].includes(decision)) throw new PromptArenaError("Unknown decision");
1319
+ const pair = experiment.pairs.find((item) => item.id === pairId);
1320
+ if (!pair || pair.executions.some((item) => item.failed)) throw new PromptArenaError("A completed pair is required");
1321
+ if (pair.pending) await pair.pending;
1322
+ if (pair.decision) {
1323
+ if (pair.decision !== decision) throw new PromptArenaError("Pair has already been judged", 409);
1324
+ return this.view(experiment);
1325
+ }
1326
+ const pending = (async () => {
1327
+ await withAiRunTransaction(this.options.db, async ({ db }) => {
1328
+ for (const execution of pair.executions) await recordAiEvaluation(db, {
1329
+ runId: execution.runId,
1330
+ tenantId: experiment.tenantId,
1331
+ metric: "prompt-arena.preference",
1332
+ evaluator: "human",
1333
+ value: decision === "tie" ? .5 : decision === execution.side ? 1 : 0,
1334
+ label: decision === "tie" ? "tie" : decision === execution.side ? "winner" : "loser",
1335
+ evidence: {
1336
+ experimentId: id,
1337
+ pairId,
1338
+ actorId: caller.actorId
1339
+ }
1340
+ });
1341
+ });
1342
+ pair.decision = decision;
1343
+ })();
1344
+ pair.pending = pending;
1345
+ try {
1346
+ await pending;
1347
+ } finally {
1348
+ if (pair.pending === pending) pair.pending = void 0;
1349
+ }
1350
+ return this.view(experiment);
1351
+ }
1352
+ async results(caller, id) {
1353
+ const experiment = await this.owned(caller, id, "results");
1354
+ if (experiment.pairs.some((pair) => !pair.decision && pair.executions.every((execution) => !execution.failed))) return [];
1355
+ return this.metrics(experiment);
1356
+ }
1357
+ async promote(caller, id, scopeType) {
1358
+ const experiment = await this.owned(caller, id, "promote");
1359
+ if (scopeType !== "app" && scopeType !== "tenant") throw new PromptArenaError("Unknown promotion scope");
1360
+ const [current, draft] = this.metrics(experiment);
1361
+ if (current.wins === draft.wins) throw new PromptArenaError("A winning variant is required");
1362
+ const template = experiment.templates[draft.wins > current.wins ? 1 : 0];
1363
+ if (scopeType === "tenant" && experiment.tenantId === null) throw new PromptArenaError("Tenant promotion requires a tenant");
1364
+ return this.options.settings.setPromptOverride({
1365
+ key: experiment.key,
1366
+ scopeType,
1367
+ scopeId: scopeType === "app" ? "__app__" : experiment.tenantId,
1368
+ template
1369
+ });
1370
+ }
1371
+ async require(caller, operation, key, experimentId) {
1372
+ if (isDatabaseTransactionActive(this.options.db)) throw new PromptArenaError("Arena cannot participate in an external transaction");
1373
+ if (this.options.enabled !== true || typeof caller?.actorId !== "string" || !caller.actorId.trim() || !(caller.tenantId === null || typeof caller.tenantId === "string" && caller.tenantId.trim() === caller.tenantId && !!caller.tenantId) || (getTenantId() ?? null) !== caller.tenantId) throw new PromptArenaError("Arena access denied", 403);
1374
+ let allowed = false;
1375
+ try {
1376
+ allowed = await this.options.authorize?.({
1377
+ ...caller,
1378
+ operation,
1379
+ key,
1380
+ experimentId
1381
+ }) === true;
1382
+ } catch {}
1383
+ if (!allowed) throw new PromptArenaError("Arena access denied", 403);
1384
+ }
1385
+ async owned(caller, id, operation) {
1386
+ const scope = { ...caller };
1387
+ const experiment = this.experiments.get(id);
1388
+ await this.require(scope, operation, experiment?.tenantId === scope.tenantId ? experiment.key : void 0, id);
1389
+ if (!experiment || experiment.tenantId !== scope.tenantId) throw new PromptArenaError("Experiment not found", 404);
1390
+ return experiment;
1391
+ }
1392
+ view(experiment) {
1393
+ return {
1394
+ id: experiment.id,
1395
+ key: experiment.key,
1396
+ pairs: experiment.pairs.map((pair) => ({
1397
+ id: pair.id,
1398
+ input: copyInput(pair.input),
1399
+ status: pair.executions.some((item) => item.failed) ? "failed" : "complete",
1400
+ outputs: [...pair.executions].sort((a, b) => a.side.localeCompare(b.side)).map(({ side, text, failed }) => ({
1401
+ side,
1402
+ text,
1403
+ failed
1404
+ })),
1405
+ ...pair.decision ? {
1406
+ decision: pair.decision,
1407
+ variants: pair.executions.map(({ side, variant, runId, usage }) => ({
1408
+ side,
1409
+ variant,
1410
+ runId,
1411
+ usageIds: usage.map(({ id }) => id)
1412
+ }))
1413
+ } : {}
1414
+ }))
1415
+ };
1416
+ }
1417
+ metrics(experiment) {
1418
+ return ["current", "draft"].map((variant) => {
1419
+ const executions = experiment.pairs.flatMap((pair) => pair.executions.filter((execution) => execution.variant === variant).map((execution) => ({
1420
+ pair,
1421
+ execution
1422
+ })));
1423
+ const judgedPairs = executions.filter(({ pair }) => !!pair.decision).length;
1424
+ const wins = executions.filter(({ pair, execution }) => pair.decision === execution.side).length;
1425
+ const usage = executions.flatMap(({ execution }) => execution.usage);
1426
+ return {
1427
+ variant,
1428
+ wins,
1429
+ judgedPairs,
1430
+ winRate: judgedPairs ? wins / judgedPairs : null,
1431
+ tokens: usage.reduce((sum, row) => sum + (row.usage?.totalTokens ?? 0), 0),
1432
+ cost: usage.reduce((sum, row) => sum + (row.estimatedCost ?? 0), 0),
1433
+ uncostedCalls: usage.filter((row) => row.estimatedCost === void 0).length,
1434
+ latencyMs: usage.reduce((sum, row) => sum + row.duration, 0)
1435
+ };
1436
+ });
1437
+ }
1438
+ };
1439
+ //#endregion
1440
+ //#region src/prompt-arena-transports.ts
1441
+ var MAX_ARGUMENT_BYTES = 11e4;
1442
+ var text = {
1443
+ type: "string",
1444
+ minLength: 1
1445
+ };
1446
+ var id = {
1447
+ type: "string",
1448
+ minLength: 1,
1449
+ maxLength: 1e3
1450
+ };
1451
+ var schema = (properties, required = Object.keys(properties)) => ({
1452
+ type: "object",
1453
+ properties,
1454
+ required,
1455
+ additionalProperties: false
1456
+ });
1457
+ var schemas = {
1458
+ list: schema({}),
1459
+ execute: schema({
1460
+ key: id,
1461
+ draft: {
1462
+ ...text,
1463
+ maxLength: 1e5
1464
+ },
1465
+ inputs: {
1466
+ type: "array",
1467
+ minItems: 1,
1468
+ maxItems: 20,
1469
+ items: { oneOf: [schema({ fixtureId: id }), schema({ input: {} })] }
1470
+ }
1471
+ }),
1472
+ read: schema({ id }),
1473
+ judge: schema({
1474
+ id,
1475
+ pairId: id,
1476
+ decision: {
1477
+ type: "string",
1478
+ enum: [
1479
+ "A",
1480
+ "B",
1481
+ "tie"
1482
+ ]
1483
+ }
1484
+ }),
1485
+ results: schema({ id }),
1486
+ promote: schema({
1487
+ id,
1488
+ scopeType: {
1489
+ type: "string",
1490
+ enum: ["app", "tenant"]
1491
+ }
1492
+ })
1493
+ };
1494
+ var operations = Object.keys(schemas);
1495
+ var readOperations = /* @__PURE__ */ new Set([
1496
+ "list",
1497
+ "read",
1498
+ "results"
1499
+ ]);
1500
+ function record(value) {
1501
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) throw new PromptArenaError("Expected an object");
1502
+ return value;
1503
+ }
1504
+ function exact(value, keys) {
1505
+ const data = record(value);
1506
+ if (Object.keys(data).some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(data, key))) throw new PromptArenaError("Missing or unknown operation parameters");
1507
+ return data;
1508
+ }
1509
+ function identifier(value) {
1510
+ if (typeof value !== "string" || !value.trim() || value !== value.trim() || value.length > 1e3) throw new PromptArenaError("A non-blank identifier of at most 1000 characters is required");
1511
+ return value;
1512
+ }
1513
+ function decode(operation, raw) {
1514
+ const encoded = JSON.stringify(raw);
1515
+ if (encoded && new TextEncoder().encode(encoded).byteLength > MAX_ARGUMENT_BYTES) throw new PromptArenaError("Arena request is too large", 413);
1516
+ const keys = Object.keys(schemas[operation]?.properties ?? {});
1517
+ if (!operations.includes(operation)) throw new PromptArenaError("Unknown arena operation");
1518
+ const data = exact(raw, keys);
1519
+ if (operation === "list") return {};
1520
+ if (operation === "execute") {
1521
+ const key = identifier(data.key);
1522
+ if (typeof data.draft !== "string" || !data.draft.trim() || data.draft.length > 1e5 || !Array.isArray(data.inputs) || data.inputs.length < 1 || data.inputs.length > 20) throw new PromptArenaError("Invalid arena draft or inputs");
1523
+ const inputs = data.inputs.map((selection) => {
1524
+ const selected = record(selection);
1525
+ if (Object.keys(selected).length !== 1) throw new PromptArenaError("Choose one input source");
1526
+ if (Object.hasOwn(selected, "fixtureId")) return { fixtureId: identifier(selected.fixtureId) };
1527
+ if (!Object.hasOwn(selected, "input")) throw new PromptArenaError("Unknown input source");
1528
+ return { input: selected.input };
1529
+ });
1530
+ try {
1531
+ return structuredClone({
1532
+ key,
1533
+ draft: data.draft,
1534
+ inputs
1535
+ });
1536
+ } catch {
1537
+ throw new PromptArenaError("Input must be JSON data");
1538
+ }
1539
+ }
1540
+ const experimentId = identifier(data.id);
1541
+ if (operation === "read" || operation === "results") return { id: experimentId };
1542
+ if (operation === "judge") {
1543
+ if (![
1544
+ "A",
1545
+ "B",
1546
+ "tie"
1547
+ ].includes(data.decision)) throw new PromptArenaError("Unknown decision");
1548
+ return {
1549
+ id: experimentId,
1550
+ pairId: identifier(data.pairId),
1551
+ decision: data.decision
1552
+ };
1553
+ }
1554
+ if (data.scopeType !== "app" && data.scopeType !== "tenant") throw new PromptArenaError("Unknown promotion scope");
1555
+ return {
1556
+ id: experimentId,
1557
+ scopeType: data.scopeType
1558
+ };
1559
+ }
1560
+ function publicError(error) {
1561
+ if (error instanceof PromptArenaError) return error;
1562
+ const status = error && typeof error === "object" && "status" in error ? error.status : void 0;
1563
+ if (status === 403) return new PromptArenaError("Arena access denied", 403);
1564
+ if (status === 413) return new PromptArenaError("Arena request is too large", 413);
1565
+ if (status === 400 || error instanceof TypeError) return new PromptArenaError("Invalid arena request");
1566
+ return new PromptArenaError("Arena operation failed", 500);
1567
+ }
1568
+ function json(value, status = 200) {
1569
+ return Response.json(value, {
1570
+ status,
1571
+ headers: {
1572
+ "cache-control": "no-store",
1573
+ "x-content-type-options": "nosniff"
1574
+ }
1575
+ });
1576
+ }
1577
+ function createPromptArenaTransports(options) {
1578
+ async function dispatch(operation, raw) {
1579
+ try {
1580
+ const caller = { ...await options.currentCaller() };
1581
+ const params = decode(operation, raw);
1582
+ if (typeof options.assertOperationPermission !== "function") throw new PromptArenaError("Arena access denied", 403);
1583
+ const decision = await options.assertOperationPermission(structuredClone({
1584
+ operation,
1585
+ caller,
1586
+ params
1587
+ }));
1588
+ if (decision !== void 0 && decision !== true && !(decision && typeof decision === "object" && decision.allowed === true)) throw new PromptArenaError("Arena access denied", 403);
1589
+ const arena = options.arena;
1590
+ switch (operation) {
1591
+ case "list": return await arena.list(caller);
1592
+ case "execute": return await arena.execute(caller, params);
1593
+ case "read": return await arena.read(caller, params.id);
1594
+ case "judge": {
1595
+ const { id: id2, pairId, decision: decision2 } = params;
1596
+ return await arena.judge(caller, id2, pairId, decision2);
1597
+ }
1598
+ case "results": return await arena.results(caller, params.id);
1599
+ case "promote": {
1600
+ const { id: id2, scopeType } = params;
1601
+ return await arena.promote(caller, id2, scopeType);
1602
+ }
1603
+ }
1604
+ } catch (error) {
1605
+ throw publicError(error);
1606
+ }
1607
+ }
1608
+ return {
1609
+ api: Object.fromEntries(operations.map((operation) => [operation, async (request) => {
1610
+ const method = readOperations.has(operation) ? "GET" : "POST";
1611
+ if (request.method !== method) {
1612
+ const response = json({ error: `Use ${method}` }, 405);
1613
+ response.headers.set("allow", method);
1614
+ return response;
1615
+ }
1616
+ try {
1617
+ const query = new URL(request.url).searchParams;
1618
+ let params;
1619
+ if (method === "GET") {
1620
+ const values = {};
1621
+ for (const [key, value] of query) {
1622
+ if (Object.hasOwn(values, key)) throw new PromptArenaError("Repeated query parameter");
1623
+ Object.defineProperty(values, key, {
1624
+ value,
1625
+ enumerable: true
1626
+ });
1627
+ }
1628
+ params = values;
1629
+ } else {
1630
+ if (query.size) throw new PromptArenaError("POST parameters belong in the JSON body");
1631
+ params = await parseJsonRequestBody(request, MAX_ARGUMENT_BYTES);
1632
+ }
1633
+ return json(await dispatch(operation, params));
1634
+ } catch (error) {
1635
+ const failure = publicError(error);
1636
+ return json({ error: failure.message }, failure.status);
1637
+ }
1638
+ }])),
1639
+ /** Call once at host MCP startup, using core's existing server addTool API. */
1640
+ registerMcp(server) {
1641
+ for (const operation of operations) server.addTool({
1642
+ name: `prompt_arena_${operation}`,
1643
+ description: `${operation} a developer prompt arena experiment (host authorization required)`,
1644
+ inputSchema: structuredClone(schemas[operation])
1645
+ }, (params) => dispatch(operation, params));
1646
+ }
1647
+ };
1648
+ }
1649
+ //#endregion
1101
1650
  //#region src/index.ts
1102
1651
  var PACKAGE_VERSION_INITIALIZED = true;
1103
1652
  //#endregion
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 };
1653
+ export { APP_PROMPT_SCOPE_ID, InvalidPromptScopeError, PACKAGE_VERSION_INITIALIZED, PromptArenaError, PromptArenaService, PromptFieldNotEditableError, PromptOverride, PromptOverrideAuthorizationError, PromptOverrideCollection, PromptOverrideService, PromptRegistry, PromptSettingsService, UnknownPromptKeyError, clearPromptCache, createPromptArenaTransports, definePrompt, getPromptCacheTtlMs, promptMessageOptions, promptTemplateHash, resolvePrompt, trackedPromptCall, withPromptOverrides };
1105
1654
 
1106
1655
  //# sourceMappingURL=index.js.map