@case-framework/survey-assistant 0.2.3 → 0.4.0

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.
Files changed (87) hide show
  1. package/README.md +12 -4
  2. package/dist/{authoring-references-ChDTVnms.mjs → authoring-references-yyYC4Ydi.mjs} +2 -2
  3. package/dist/{authoring-references-ChDTVnms.mjs.map → authoring-references-yyYC4Ydi.mjs.map} +1 -1
  4. package/dist/capabilities-default.d.mts +1 -1
  5. package/dist/capabilities-default.mjs +1 -1
  6. package/dist/{constants-BK1-g6pR.d.mts → constants-k1b_evIb.d.mts} +7 -4
  7. package/dist/constants-k1b_evIb.d.mts.map +1 -0
  8. package/dist/{controller-proxy-DY36XFV3.mjs → controller-proxy-jWIPOZAv.mjs} +18 -8
  9. package/dist/controller-proxy-jWIPOZAv.mjs.map +1 -0
  10. package/dist/{controller-proxy-CIDRd8Wu.d.mts → controller-proxy-quQjtA7j.d.mts} +5 -2
  11. package/dist/controller-proxy-quQjtA7j.d.mts.map +1 -0
  12. package/dist/{engine-CWTuN3o2.mjs → engine-BvfUx_Jx.mjs} +85 -12
  13. package/dist/engine-BvfUx_Jx.mjs.map +1 -0
  14. package/dist/engine.d.mts +2 -2
  15. package/dist/engine.mjs +3 -3
  16. package/dist/{form-authoring-DCd9XfXf.mjs → form-authoring-BQh40yDb.mjs} +2 -2
  17. package/dist/{form-authoring-DCd9XfXf.mjs.map → form-authoring-BQh40yDb.mjs.map} +1 -1
  18. package/dist/index-8x1Eqlnz.d.mts +741 -0
  19. package/dist/index-8x1Eqlnz.d.mts.map +1 -0
  20. package/dist/{index-SPHf3OoJ.d.mts → index-BDp6S7r9.d.mts} +14 -5
  21. package/dist/index-BDp6S7r9.d.mts.map +1 -0
  22. package/dist/{index-Bp5W_oPa.d.mts → index-biZnRl-h.d.mts} +26 -24
  23. package/dist/index-biZnRl-h.d.mts.map +1 -0
  24. package/dist/{index-CPOQgkTN.d.mts → index-r8HVcn5b.d.mts} +9 -4
  25. package/dist/index-r8HVcn5b.d.mts.map +1 -0
  26. package/dist/lifecycle-DWv5CiSu.d.mts +523 -0
  27. package/dist/lifecycle-DWv5CiSu.d.mts.map +1 -0
  28. package/dist/{memory-thread-repository-acbz6HZJ.mjs → memory-thread-repository-xBZOog_q.mjs} +49 -21
  29. package/dist/memory-thread-repository-xBZOog_q.mjs.map +1 -0
  30. package/dist/{protocol-DATvkr1S.mjs → protocol-DJUP4gc0.mjs} +10 -4
  31. package/dist/protocol-DJUP4gc0.mjs.map +1 -0
  32. package/dist/protocol.d.mts +2 -1
  33. package/dist/protocol.mjs +1 -1
  34. package/dist/{react-3kSE6WtS.mjs → react-CY6N7lVi.mjs} +30 -8
  35. package/dist/react-CY6N7lVi.mjs.map +1 -0
  36. package/dist/react-integration.d.mts +1 -1
  37. package/dist/react-integration.mjs +1 -1
  38. package/dist/react.d.mts +2 -2
  39. package/dist/react.mjs +2 -2
  40. package/dist/{request-context-BEjnaaFr.mjs → request-context-DixY5DYu.mjs} +3 -3
  41. package/dist/request-context-DixY5DYu.mjs.map +1 -0
  42. package/dist/server-agent.d.mts +26 -24
  43. package/dist/server-agent.d.mts.map +1 -1
  44. package/dist/server-agent.mjs +7 -6
  45. package/dist/server-agent.mjs.map +1 -1
  46. package/dist/server-runtime.d.mts +341 -8
  47. package/dist/server-runtime.d.mts.map +1 -1
  48. package/dist/server-runtime.mjs +321 -23
  49. package/dist/server-runtime.mjs.map +1 -1
  50. package/dist/server-tasks.d.mts +1 -1
  51. package/dist/server-tasks.mjs +8 -6
  52. package/dist/server-tasks.mjs.map +1 -1
  53. package/dist/server-tools.d.mts +1 -1
  54. package/dist/server-tools.mjs +1 -1
  55. package/dist/server.d.mts +8 -8
  56. package/dist/server.d.mts.map +1 -1
  57. package/dist/server.mjs +3 -3
  58. package/dist/storage-postgres.d.mts +1 -1
  59. package/dist/{tasks-DIZgr4nD.d.mts → tasks-BWmTMXoK.d.mts} +3 -3
  60. package/dist/{tasks-DIZgr4nD.d.mts.map → tasks-BWmTMXoK.d.mts.map} +1 -1
  61. package/dist/{thread-documents-C3kf0Vds.d.mts → thread-documents-Dvo6XS7o.d.mts} +1 -1
  62. package/dist/{thread-documents-C3kf0Vds.d.mts.map → thread-documents-Dvo6XS7o.d.mts.map} +1 -1
  63. package/dist/{thread-handlers-DZ1WsorO.d.mts → thread-handlers-D8gkLfU6.d.mts} +15 -7
  64. package/dist/{thread-handlers-DZ1WsorO.d.mts.map → thread-handlers-D8gkLfU6.d.mts.map} +1 -1
  65. package/dist/{tools-GDd5_GUh.mjs → tools-TXI8bfzZ.mjs} +28 -9
  66. package/dist/tools-TXI8bfzZ.mjs.map +1 -0
  67. package/dist/ui.css +2 -2
  68. package/dist/ui.d.mts +94 -10
  69. package/dist/ui.d.mts.map +1 -1
  70. package/dist/ui.mjs +561 -203
  71. package/dist/ui.mjs.map +1 -1
  72. package/docs/integration.md +84 -63
  73. package/package.json +25 -19
  74. package/dist/constants-BK1-g6pR.d.mts.map +0 -1
  75. package/dist/controller-proxy-CIDRd8Wu.d.mts.map +0 -1
  76. package/dist/controller-proxy-DY36XFV3.mjs.map +0 -1
  77. package/dist/engine-CWTuN3o2.mjs.map +0 -1
  78. package/dist/index-Bp5W_oPa.d.mts.map +0 -1
  79. package/dist/index-CPOQgkTN.d.mts.map +0 -1
  80. package/dist/index-EDL1V168.d.mts +0 -1257
  81. package/dist/index-EDL1V168.d.mts.map +0 -1
  82. package/dist/index-SPHf3OoJ.d.mts.map +0 -1
  83. package/dist/memory-thread-repository-acbz6HZJ.mjs.map +0 -1
  84. package/dist/protocol-DATvkr1S.mjs.map +0 -1
  85. package/dist/react-3kSE6WtS.mjs.map +0 -1
  86. package/dist/request-context-BEjnaaFr.mjs.map +0 -1
  87. package/dist/tools-GDd5_GUh.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"server-runtime.mjs","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"sourcesContent":["import type { AgentExecutionOptions } from \"@mastra/core/agent\";\nimport type { AzureOpenAIGatewayConfig } from \"@mastra/core/llm\";\nimport {\n createSurveyAssistantObservationalMemoryOptions,\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS,\n type SurveyAssistantObservationalMemoryOptions,\n} from \"./agent\";\nimport {\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS,\n type SurveyAssistantRequestLimits,\n} from \"./request-guardrails\";\n\nexport type SurveyAssistantProvider = \"azure-openai\" | \"lmstudio\" | \"mistral\" | \"openai\";\nexport type SurveyAssistantProviderOptionsKey = \"azure\" | \"lmstudio\" | \"mistral\" | \"openai\";\n\nexport interface SurveyAssistantAzureConfig {\n apiKey?: string;\n apiVersion: string;\n discoverModels: boolean;\n management?: AzureOpenAIGatewayConfig[\"management\"];\n resourceName?: string;\n}\n\nexport interface SurveyAssistantLmStudioConfig {\n apiKey?: string;\n baseUrl: string;\n}\n\nexport interface SurveyAssistantExecutionConfig {\n firstResponseTimeoutMs: number;\n idleTimeoutMs: number;\n maxConcurrentRequests: number;\n /** Absolute execution ceiling. Active streams still stop when this duration is reached. */\n maxDurationMs: number;\n maxSteps: number;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n sendReasoning: boolean;\n}\n\nexport interface SurveyAssistantRuntimeConfig {\n azure?: SurveyAssistantAzureConfig;\n lmstudio?: SurveyAssistantLmStudioConfig;\n /** Default chat model and fallback for chat requests without a selection. */\n defaultModelId: string;\n enabled: boolean;\n /** Fixed same-provider model shared by memory observation and reflection. */\n memoryModelId: string;\n modelCatalogTtlMs: number;\n modelIds: string[];\n observationalMemory: SurveyAssistantObservationalMemoryOptions | false;\n provider: SurveyAssistantProvider;\n requestLimits: Pick<\n SurveyAssistantRequestLimits,\n | \"maxAttachmentBytes\"\n | \"maxAttachments\"\n | \"maxRequestBytes\"\n | \"maxTextPartChars\"\n | \"maxTotalAttachmentBytes\"\n >;\n readinessError: string | null;\n /**\n * Fixed model for one-shot tasks. When omitted, tasks follow the\n * server-authorized chat model selection.\n */\n taskModelId?: string;\n execution: SurveyAssistantExecutionConfig;\n}\n\nexport interface ParseSurveyAssistantEnvironmentOptions {\n defaultLmStudioModel?: string;\n defaultMistralModel?: string;\n defaultOpenAIModel?: string;\n defaultProvider?: SurveyAssistantProvider;\n requireExperimentalIdentityOptIn?: boolean;\n requireStorage?: boolean;\n}\n\ntype Environment = Record<string, string | undefined>;\n\nconst DEFAULT_MAX_STEPS = 48;\nconst HARD_MAX_STEPS = 64;\nconst DEFAULT_FIRST_RESPONSE_TIMEOUT_MS = 15 * 60 * 1_000;\nconst DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1_000;\nconst DEFAULT_MAX_DURATION_MS = 60 * 60 * 1_000;\nconst DEFAULT_CATALOG_TTL_MS = 5 * 60 * 1_000;\n\nconst getValue = (env: Environment, name: string) => {\n const value = env[name]?.trim();\n return value || undefined;\n};\n\nconst getBoolean = (env: Environment, name: string, fallback: boolean) => {\n const value = getValue(env, name)?.toLowerCase();\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (value !== undefined) {\n throw new Error(`${name} must be \"true\" or \"false\".`);\n }\n return fallback;\n};\n\nconst getPositiveNumber = (env: Environment, name: string, fallback: number) => {\n const configured = getValue(env, name);\n if (configured === undefined) return fallback;\n const value = Number(configured);\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return value;\n};\n\nconst getEnum = <TValue extends string>(\n env: Environment,\n name: string,\n values: readonly TValue[],\n) => {\n const value = getValue(env, name);\n if (!value) return undefined;\n if (!(values as readonly string[]).includes(value)) {\n throw new Error(`${name} must be one of: ${values.join(\", \")}.`);\n }\n return value as TValue;\n};\n\nconst getCommaSeparatedValues = (env: Environment, name: string) => [\n ...new Set(\n (getValue(env, name) ?? \"\")\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean),\n ),\n];\n\nconst getSameProviderModelId = (\n value: string,\n name: string,\n { allowNestedId = false }: { allowNestedId?: boolean } = {},\n) => {\n if (!allowNestedId && value.includes(\"/\")) {\n throw new Error(\n `${name} must be a model or deployment id without a provider prefix. ` +\n \"All survey assistant models use SURVEY_ASSISTANT_PROVIDER.\",\n );\n }\n return value;\n};\n\nconst getOptionalSameProviderModelId = (\n env: Environment,\n name: string,\n options?: { allowNestedId?: boolean },\n) => {\n const value = getValue(env, name);\n return value ? getSameProviderModelId(value, name, options) : undefined;\n};\n\nexport const resolveSurveyAssistantProviderOptionsKey = (\n provider: SurveyAssistantProvider,\n): SurveyAssistantProviderOptionsKey => (provider === \"azure-openai\" ? \"azure\" : provider);\n\nconst parseProvider = (\n env: Environment,\n fallback: SurveyAssistantProvider,\n): SurveyAssistantProvider => {\n const value = getValue(env, \"SURVEY_ASSISTANT_PROVIDER\")?.toLowerCase();\n if (value === \"azure\" || value === \"azure-openai\") return \"azure-openai\";\n if (value === \"lmstudio\" || value === \"openai\" || value === \"mistral\") return value;\n if (value) {\n throw new Error(\n \"SURVEY_ASSISTANT_PROVIDER must be one of: openai, mistral, lmstudio, azure-openai.\",\n );\n }\n return fallback;\n};\n\nconst parseAzureManagement = (\n env: Environment,\n): AzureOpenAIGatewayConfig[\"management\"] | undefined => {\n if (!getBoolean(env, \"SURVEY_ASSISTANT_AZURE_DISCOVER_MODELS\", false)) return undefined;\n const management = {\n tenantId: getValue(env, \"AZURE_TENANT_ID\"),\n clientId: getValue(env, \"AZURE_CLIENT_ID\"),\n clientSecret: getValue(env, \"AZURE_CLIENT_SECRET\"),\n subscriptionId: getValue(env, \"AZURE_SUBSCRIPTION_ID\"),\n resourceGroup: getValue(env, \"AZURE_RESOURCE_GROUP\"),\n };\n return Object.values(management).every(Boolean)\n ? (management as AzureOpenAIGatewayConfig[\"management\"])\n : undefined;\n};\n\nconst getReadinessError = ({\n azure,\n env,\n modelWasConfigured,\n provider,\n requireStorage,\n}: {\n azure?: SurveyAssistantAzureConfig;\n env: Environment;\n modelWasConfigured: boolean;\n provider: SurveyAssistantProvider;\n requireStorage: boolean;\n}) => {\n if (\n requireStorage &&\n !getValue(env, \"SURVEY_ASSISTANT_DATABASE_URL\") &&\n !getValue(env, \"DATABASE_URL\")\n ) {\n return \"Survey assistant storage is not configured.\";\n }\n if (provider === \"openai\" && !getValue(env, \"OPENAI_API_KEY\")) {\n return \"The OpenAI API key is not configured for the survey assistant.\";\n }\n if (provider === \"mistral\" && !getValue(env, \"MISTRAL_API_KEY\")) {\n return \"The Mistral API key is not configured for the survey assistant.\";\n }\n if (provider === \"azure-openai\") {\n if (!azure?.resourceName) {\n return \"The Azure OpenAI resource name is not configured for the survey assistant.\";\n }\n if (!azure.apiKey) {\n return \"The Azure OpenAI API key is not configured for the survey assistant.\";\n }\n if (!modelWasConfigured) {\n return \"The Azure OpenAI deployment name is not configured for the survey assistant.\";\n }\n if (azure.discoverModels && !azure.management) {\n return \"Azure deployment discovery requires complete tenant, client, subscription, and resource-group settings.\";\n }\n }\n return null;\n};\n\nexport const parseSurveyAssistantEnvironment = (\n env: Environment,\n {\n defaultLmStudioModel,\n defaultMistralModel = \"mistral-medium-latest\",\n defaultOpenAIModel = \"gpt-5.4-nano\",\n defaultProvider = \"openai\",\n requireExperimentalIdentityOptIn = false,\n requireStorage = true,\n }: ParseSurveyAssistantEnvironmentOptions = {},\n): SurveyAssistantRuntimeConfig => {\n const provider = parseProvider(env, defaultProvider);\n const modelIdOptions = { allowNestedId: provider === \"lmstudio\" };\n const configuredModelId = getOptionalSameProviderModelId(\n env,\n \"SURVEY_ASSISTANT_MODEL\",\n modelIdOptions,\n );\n if (provider === \"lmstudio\" && !configuredModelId && !defaultLmStudioModel) {\n throw new Error(\n \"SURVEY_ASSISTANT_MODEL must be configured when SURVEY_ASSISTANT_PROVIDER is lmstudio.\",\n );\n }\n const defaultModelId =\n configuredModelId ??\n getSameProviderModelId(\n provider === \"lmstudio\"\n ? defaultLmStudioModel!\n : provider === \"mistral\"\n ? defaultMistralModel\n : defaultOpenAIModel,\n provider === \"lmstudio\"\n ? \"defaultLmStudioModel\"\n : provider === \"mistral\"\n ? \"defaultMistralModel\"\n : \"defaultOpenAIModel\",\n modelIdOptions,\n );\n const configuredModelIds = getCommaSeparatedValues(env, \"SURVEY_ASSISTANT_MODELS\").map(\n (modelId) => getSameProviderModelId(modelId, \"SURVEY_ASSISTANT_MODELS\", modelIdOptions),\n );\n const modelIds = [\n ...new Set(\n configuredModelIds.includes(defaultModelId)\n ? configuredModelIds\n : [defaultModelId, ...configuredModelIds],\n ),\n ];\n const taskModelId = getOptionalSameProviderModelId(\n env,\n \"SURVEY_ASSISTANT_TASK_MODEL\",\n modelIdOptions,\n );\n const sendReasoning = getBoolean(env, \"SURVEY_ASSISTANT_SEND_REASONING\", true);\n const providerOptionsKey = resolveSurveyAssistantProviderOptionsKey(provider);\n const providerReasoningEffort = getValue(\n env,\n `SURVEY_ASSISTANT_${providerOptionsKey.toUpperCase()}_REASONING_EFFORT`,\n );\n const reasoningEffort =\n providerReasoningEffort ??\n getValue(env, \"SURVEY_ASSISTANT_REASONING_EFFORT\") ??\n (provider === \"openai\" || provider === \"azure-openai\" ? \"low\" : \"none\");\n const promptCacheRetention = getEnum(\n env,\n provider === \"azure-openai\"\n ? \"SURVEY_ASSISTANT_AZURE_PROMPT_CACHE_RETENTION\"\n : \"SURVEY_ASSISTANT_PROMPT_CACHE_RETENTION\",\n [\"in_memory\", \"24h\"] as const,\n );\n const serviceTier = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_SERVICE_TIER\", [\n \"auto\",\n \"flex\",\n \"priority\",\n \"default\",\n ] as const);\n const textVerbosity = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_TEXT_VERBOSITY\", [\n \"low\",\n \"medium\",\n \"high\",\n ] as const);\n const reasoningSummaryValue = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_REASONING_SUMMARY\", [\n \"auto\",\n \"concise\",\n \"detailed\",\n \"off\",\n \"none\",\n ] as const);\n const reasoningSummary =\n reasoningSummaryValue === \"off\" || reasoningSummaryValue === \"none\"\n ? undefined\n : (reasoningSummaryValue ?? \"detailed\");\n const resolvedReasoningEffort =\n reasoningEffort === \"default\" || reasoningEffort === \"provider-default\"\n ? undefined\n : reasoningEffort;\n const providerOptions: AgentExecutionOptions[\"providerOptions\"] =\n provider === \"lmstudio\"\n ? undefined\n : {\n [providerOptionsKey]: {\n parallelToolCalls: false,\n ...(resolvedReasoningEffort ? { reasoningEffort: resolvedReasoningEffort } : {}),\n ...(provider === \"openai\" || provider === \"azure-openai\"\n ? {\n promptCacheKey:\n getValue(env, \"SURVEY_ASSISTANT_PROMPT_CACHE_KEY\") ??\n \"survey-assistant-chat-v21\",\n ...(promptCacheRetention ? { promptCacheRetention } : {}),\n ...(sendReasoning && reasoningSummary ? { reasoningSummary } : {}),\n ...(provider === \"openai\" && serviceTier ? { serviceTier } : {}),\n ...(textVerbosity ? { textVerbosity } : {}),\n }\n : {}),\n },\n };\n const azure: SurveyAssistantAzureConfig | undefined =\n provider === \"azure-openai\"\n ? {\n resourceName: getValue(env, \"AZURE_RESOURCE_NAME\"),\n apiKey: getValue(env, \"AZURE_API_KEY\"),\n apiVersion: getValue(env, \"SURVEY_ASSISTANT_AZURE_API_VERSION\") ?? \"v1\",\n discoverModels: getBoolean(env, \"SURVEY_ASSISTANT_AZURE_DISCOVER_MODELS\", false),\n management: parseAzureManagement(env),\n }\n : undefined;\n const lmstudio: SurveyAssistantLmStudioConfig | undefined =\n provider === \"lmstudio\"\n ? {\n baseUrl:\n getValue(env, \"SURVEY_ASSISTANT_LMSTUDIO_BASE_URL\") ?? \"http://127.0.0.1:1234/v1\",\n apiKey: getValue(env, \"SURVEY_ASSISTANT_LMSTUDIO_API_KEY\"),\n }\n : undefined;\n const memoryModelId =\n getOptionalSameProviderModelId(env, \"SURVEY_ASSISTANT_MEMORY_MODEL\", modelIdOptions) ??\n defaultModelId;\n const memoryModel = `${provider}/${memoryModelId}`;\n const observationalMemory = getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_ENABLED\", true)\n ? createSurveyAssistantObservationalMemoryOptions({\n model: memoryModel,\n temporalMarkers: getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_TEMPORAL_MARKERS\", false),\n observation: {\n messageTokens: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MEMORY_MESSAGE_TOKENS\",\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n ),\n bufferOnIdle: getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_BUFFER_ON_IDLE\", false),\n observeAttachments: false,\n },\n reflection: {\n observationTokens: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MEMORY_OBSERVATION_TOKENS\",\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n ),\n },\n })\n : false;\n const configuredMaxSteps = getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_STEPS\",\n DEFAULT_MAX_STEPS,\n );\n const enabledSetting = getValue(env, \"SURVEY_ASSISTANT_ENABLED\")?.toLowerCase();\n if (enabledSetting !== undefined && enabledSetting !== \"true\" && enabledSetting !== \"false\") {\n throw new Error('SURVEY_ASSISTANT_ENABLED must be \"true\" or \"false\".');\n }\n const enabled =\n enabledSetting === \"false\"\n ? false\n : enabledSetting === \"true\"\n ? !requireExperimentalIdentityOptIn ||\n env.NODE_ENV === \"development\" ||\n getBoolean(env, \"SURVEY_ASSISTANT_ALLOW_EXPERIMENTAL_IDENTITY\", false)\n : env.NODE_ENV === \"development\";\n\n return {\n provider,\n defaultModelId,\n memoryModelId,\n modelIds,\n modelCatalogTtlMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MODEL_CATALOG_TTL_MS\",\n DEFAULT_CATALOG_TTL_MS,\n ),\n azure,\n lmstudio,\n enabled,\n readinessError: getReadinessError({\n azure,\n env,\n modelWasConfigured: Boolean(configuredModelId),\n provider,\n requireStorage,\n }),\n requestLimits: {\n maxAttachmentBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachmentBytes,\n ),\n maxAttachments: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_ATTACHMENTS\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachments,\n ),\n maxRequestBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_REQUEST_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxRequestBytes,\n ),\n maxTextPartChars: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTextPartChars,\n ),\n maxTotalAttachmentBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTotalAttachmentBytes,\n ),\n },\n execution: {\n firstResponseTimeoutMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_FIRST_RESPONSE_TIMEOUT_MS\",\n DEFAULT_FIRST_RESPONSE_TIMEOUT_MS,\n ),\n idleTimeoutMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_IDLE_TIMEOUT_MS\",\n DEFAULT_IDLE_TIMEOUT_MS,\n ),\n maxConcurrentRequests: getPositiveNumber(env, \"SURVEY_ASSISTANT_MAX_CONCURRENT_REQUESTS\", 4),\n maxDurationMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_DURATION_MS\",\n DEFAULT_MAX_DURATION_MS,\n ),\n maxSteps: Math.min(configuredMaxSteps, HARD_MAX_STEPS),\n providerOptions,\n sendReasoning,\n },\n observationalMemory,\n taskModelId,\n };\n};\n","import type { AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { AzureOpenAIGateway, type MastraModelGatewayInterface } from \"@mastra/core/llm\";\nimport type { Mastra } from \"@mastra/core/mastra\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport type { SurveyAssistantModelCatalog } from \"../protocol\";\nimport { createSurveyAssistantAgent, type CreateSurveyAssistantAgentOptions } from \"./agent\";\nimport { SURVEY_ASSISTANT_AGENT_ID, SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\nimport {\n createSurveyAssistantChatHandler,\n SurveyAssistantAuthorizationError,\n type SurveyAssistantAuthorize,\n type SurveyAssistantChatHandlerOptions,\n type SurveyAssistantResolveModel,\n} from \"./handler\";\nimport { createMastraMemoryThreadRepository } from \"./memory-thread-repository\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport type { SurveyAssistantCapabilitySet } from \"../engine\";\nimport type { SurveyAssistantRuntimeConfig } from \"./runtime-config\";\nimport {\n createSurveyAssistantTaskAgent,\n createSurveyAssistantTaskHandler,\n type CreateSurveyAssistantTaskHandlerOptions,\n type SurveyAssistantTaskModelResolutionInput,\n} from \"./tasks\";\nimport type { SurveyAssistantThreadDocumentRepository } from \"./thread-documents\";\nimport {\n createSurveyAssistantThreadHandlers,\n type CreateSurveyAssistantThreadHandlersOptions,\n} from \"./thread-handlers\";\nimport { SURVEY_ASSISTANT_TOOL_IDS } from \"./tools\";\n\nexport {\n parseSurveyAssistantEnvironment,\n resolveSurveyAssistantProviderOptionsKey,\n type ParseSurveyAssistantEnvironmentOptions,\n type SurveyAssistantAzureConfig,\n type SurveyAssistantExecutionConfig,\n type SurveyAssistantLmStudioConfig,\n type SurveyAssistantProvider,\n type SurveyAssistantProviderOptionsKey,\n type SurveyAssistantRuntimeConfig,\n} from \"./runtime-config\";\n\nexport interface SurveyAssistantModelRouter {\n defaultModel: SurveyAssistantModelSelection[\"model\"];\n gateways?: Record<string, MastraModelGatewayInterface>;\n getCatalog(options?: { refresh?: boolean }): Promise<SurveyAssistantModelCatalog>;\n memoryModel: SurveyAssistantModelSelection[\"model\"];\n providerName: string;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel: SurveyAssistantResolveModel;\n resolveTaskModel(\n input: SurveyAssistantTaskModelResolutionInput,\n ): ReturnType<SurveyAssistantResolveModel>;\n taskModel?: SurveyAssistantModelSelection[\"model\"];\n}\n\nexport const createSurveyAssistantModelRouter = (\n config: SurveyAssistantRuntimeConfig,\n): SurveyAssistantModelRouter => {\n const toProviderModel = (\n modelId: string,\n configName: string,\n ): SurveyAssistantModelSelection[\"model\"] => {\n if (config.provider === \"lmstudio\") {\n if (!config.lmstudio) {\n throw new Error(\"LM Studio configuration is missing for the lmstudio provider.\");\n }\n return {\n providerId: \"lmstudio\",\n modelId,\n url: config.lmstudio.baseUrl,\n ...(config.lmstudio.apiKey ? { apiKey: config.lmstudio.apiKey } : {}),\n };\n }\n if (modelId.includes(\"/\")) {\n throw new Error(\n `${configName} must be a model or deployment id without a provider prefix. ` +\n \"All survey assistant models use the configured provider.\",\n );\n }\n return `${config.provider}/${modelId}`;\n };\n const defaultModel = toProviderModel(config.defaultModelId, \"defaultModelId\");\n const chatModelIds = config.modelIds.map((modelId) => {\n toProviderModel(modelId, \"modelIds\");\n return modelId;\n });\n if (!chatModelIds.includes(config.defaultModelId)) {\n throw new Error(\"modelIds must include defaultModelId.\");\n }\n const taskModel = config.taskModelId\n ? toProviderModel(config.taskModelId, \"taskModelId\")\n : undefined;\n const memoryModel = toProviderModel(config.memoryModelId, \"memoryModelId\");\n if (config.observationalMemory !== false) {\n const configuredMemoryModel = `${config.provider}/${config.memoryModelId}`;\n if (\n typeof config.observationalMemory.model !== \"string\" ||\n config.observationalMemory.model !== configuredMemoryModel ||\n config.observationalMemory.observation?.model !== undefined ||\n config.observationalMemory.reflection?.model !== undefined\n ) {\n throw new Error(\n \"The standard runtime requires observationalMemory to use memoryModelId \" +\n \"for both observation and reflection. Use the low-level Agent factory \" +\n \"for custom memory model routing.\",\n );\n }\n }\n const deploymentIds = [\n ...new Set([\n ...chatModelIds,\n ...(config.taskModelId ? [config.taskModelId] : []),\n config.memoryModelId,\n ]),\n ];\n const azureGateway = config.azure\n ? new AzureOpenAIGateway({\n resourceName: config.azure.resourceName ?? \"\",\n apiKey: config.azure.apiKey,\n apiVersion: config.azure.apiVersion,\n useResponsesAPI: true,\n ...(config.azure.management\n ? { management: config.azure.management }\n : { deployments: deploymentIds }),\n })\n : undefined;\n let cachedCatalog: { expiresAt: number; value: SurveyAssistantModelCatalog } | undefined;\n\n const getCatalog = async ({ refresh = false }: { refresh?: boolean } = {}) => {\n if (!refresh && cachedCatalog && cachedCatalog.expiresAt > Date.now()) {\n return cachedCatalog.value;\n }\n let ids = chatModelIds;\n if (azureGateway && config.azure?.discoverModels) {\n try {\n const providers = await azureGateway.fetchProviders();\n ids = [...new Set([...chatModelIds, ...(providers[\"azure-openai\"]?.models ?? [])])];\n } catch {\n // Keep the explicit catalog available when Azure management discovery is temporarily down.\n }\n }\n const value = {\n defaultModelId: config.defaultModelId,\n models: ids.map((id) => ({ id, label: id })),\n } satisfies SurveyAssistantModelCatalog;\n cachedCatalog = { expiresAt: Date.now() + config.modelCatalogTtlMs, value };\n return value;\n };\n const resolveRequestedModel = async (requestedModelId?: string) => {\n const catalog = await getCatalog();\n const id = requestedModelId ?? catalog.defaultModelId;\n return catalog.models.some((model) => model.id === id)\n ? { id, model: toProviderModel(id, \"requestedModelId\") }\n : null;\n };\n\n return {\n defaultModel,\n gateways: azureGateway\n ? {\n // Mastra 1.47 narrows one method's environment type in the concrete class.\n \"azure-openai\": azureGateway as unknown as MastraModelGatewayInterface,\n }\n : undefined,\n getCatalog,\n memoryModel,\n providerName: config.provider,\n providerOptions: config.execution.providerOptions,\n resolveModel: async ({ requestedModelId }) => resolveRequestedModel(requestedModelId),\n resolveTaskModel: async ({ requestedModelId }) =>\n config.taskModelId\n ? { id: config.taskModelId, model: taskModel! }\n : resolveRequestedModel(requestedModelId),\n taskModel,\n };\n};\n\nexport interface SurveyAssistantRuntimeComponents {\n agents: Record<\n string,\n | ReturnType<typeof createSurveyAssistantAgent>\n | ReturnType<typeof createSurveyAssistantTaskAgent>\n >;\n gateways?: Record<string, MastraModelGatewayInterface>;\n modelRouter: SurveyAssistantModelRouter;\n}\n\nexport const createSurveyAssistantRuntimeComponents = (\n config: SurveyAssistantRuntimeConfig,\n): SurveyAssistantRuntimeComponents => {\n const modelRouter = createSurveyAssistantModelRouter(config);\n const chatModel: CreateSurveyAssistantAgentOptions[\"model\"] = ({\n requestContext,\n }: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n }) => requestContext.get(\"modelSelection\")?.model ?? modelRouter.defaultModel;\n const taskModel = modelRouter.taskModel ?? chatModel;\n const observationalMemory =\n config.provider === \"lmstudio\" && config.observationalMemory !== false\n ? { ...config.observationalMemory, model: modelRouter.memoryModel }\n : config.observationalMemory;\n return {\n agents: {\n [SURVEY_ASSISTANT_AGENT_ID]: createSurveyAssistantAgent({\n model: chatModel,\n observationalMemory,\n }),\n [SURVEY_ASSISTANT_TASK_AGENT_ID]: createSurveyAssistantTaskAgent({ model: taskModel }),\n },\n gateways: modelRouter.gateways,\n modelRouter,\n };\n};\n\ntype ChatHandlerOverrides = Partial<\n Omit<\n SurveyAssistantChatHandlerOptions,\n \"authorize\" | \"mastra\" | \"providerName\" | \"providerOptions\" | \"resolveModel\"\n >\n>;\ntype TaskHandlerOverrides = Partial<\n Omit<\n CreateSurveyAssistantTaskHandlerOptions,\n \"agent\" | \"authorize\" | \"providerOptions\" | \"resolveModel\"\n >\n>;\n\nexport interface CreateSurveyAssistantRuntimeHandlersOptions {\n authorize: {\n chat: SurveyAssistantAuthorize;\n model?: (request: Request) => unknown | Promise<unknown>;\n task: CreateSurveyAssistantTaskHandlerOptions[\"authorize\"];\n thread: CreateSurveyAssistantThreadHandlersOptions[\"authorize\"];\n };\n chat?: ChatHandlerOverrides;\n config: SurveyAssistantRuntimeConfig;\n mastra: Mastra | (() => Mastra | Promise<Mastra>);\n modelRouter: SurveyAssistantModelRouter;\n task?: TaskHandlerOverrides;\n threadDocuments?: SurveyAssistantThreadDocumentRepository;\n}\n\nexport type CreateConfiguredSurveyAssistantRuntimeHandlersOptions = Omit<\n CreateSurveyAssistantRuntimeHandlersOptions,\n \"config\" | \"modelRouter\"\n>;\n\nconst resolveMastra = async (mastra: Mastra | (() => Mastra | Promise<Mastra>)) =>\n typeof mastra === \"function\" ? mastra() : mastra;\n\nexport const createSurveyAssistantRuntimeHandlers = ({\n authorize,\n chat = {},\n config,\n mastra,\n modelRouter,\n task = {},\n threadDocuments,\n}: CreateSurveyAssistantRuntimeHandlersOptions) => {\n const isEnabled = chat.isEnabled ?? (() => config.enabled);\n const getReadinessError = chat.getReadinessError ?? (() => config.readinessError);\n const chatHandler = createSurveyAssistantChatHandler({\n ...chat,\n mastra,\n agentId: SURVEY_ASSISTANT_AGENT_ID,\n activeTools:\n chat.activeTools ??\n (config.observationalMemory === false\n ? SURVEY_ASSISTANT_TOOL_IDS\n : [...SURVEY_ASSISTANT_TOOL_IDS, \"recall\"]),\n authorize: authorize.chat,\n firstResponseTimeoutMs: chat.firstResponseTimeoutMs ?? config.execution.firstResponseTimeoutMs,\n getReadinessError,\n isEnabled,\n idleTimeoutMs: chat.idleTimeoutMs ?? config.execution.idleTimeoutMs,\n maxConcurrentRequests: chat.maxConcurrentRequests ?? config.execution.maxConcurrentRequests,\n maxDurationMs: chat.maxDurationMs ?? config.execution.maxDurationMs,\n maxSteps: chat.maxSteps ?? config.execution.maxSteps,\n providerName: modelRouter.providerName,\n providerOptions: modelRouter.providerOptions,\n requestLimits: { ...config.requestLimits, ...chat.requestLimits },\n resolveModel: modelRouter.resolveModel,\n sendReasoning: chat.sendReasoning ?? config.execution.sendReasoning,\n threadDocuments,\n });\n const taskHandler = createSurveyAssistantTaskHandler({\n ...task,\n agent: async () => (await resolveMastra(mastra)).getAgent(SURVEY_ASSISTANT_TASK_AGENT_ID),\n authorize: authorize.task,\n getReadinessError: task.getReadinessError ?? getReadinessError,\n isEnabled: task.isEnabled ?? isEnabled,\n maxConcurrentRequests: task.maxConcurrentRequests ?? config.execution.maxConcurrentRequests,\n maxDurationMs: task.maxDurationMs ?? config.execution.maxDurationMs,\n providerOptions: modelRouter.providerOptions,\n resolveModel: modelRouter.resolveTaskModel,\n });\n const getMemory = async () => {\n const memory = await (\n await resolveMastra(mastra)\n )\n .getAgent(SURVEY_ASSISTANT_AGENT_ID)\n .getMemory();\n if (!memory) throw new Error(\"Survey assistant memory is not configured.\");\n return memory;\n };\n const threads = createSurveyAssistantThreadHandlers({\n authorize: async (request) => {\n if (!config.enabled) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant is disabled.\", 404);\n }\n return authorize.thread(request);\n },\n repository: createMastraMemoryThreadRepository({ getMemory, threadDocuments }),\n });\n const models = async (request: Request) => {\n if (!config.enabled) {\n return Response.json(\n { code: \"authorization_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n try {\n if (authorize.model) {\n await authorize.model(request);\n } else {\n await authorize.task({ request });\n }\n return Response.json(await modelRouter.getCatalog());\n } catch (error) {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : 403;\n return Response.json(\n {\n code: \"authorization_failed\",\n error: \"The survey assistant request is not authorized.\",\n },\n { status },\n );\n }\n };\n\n return {\n chat: chatHandler,\n models,\n task: taskHandler,\n threads,\n };\n};\n\nexport interface SurveyAssistantRuntime extends SurveyAssistantRuntimeComponents {\n config: SurveyAssistantRuntimeConfig;\n createHandlers(\n options: CreateConfiguredSurveyAssistantRuntimeHandlersOptions,\n ): ReturnType<typeof createSurveyAssistantRuntimeHandlers>;\n}\n\nexport interface CreateSurveyAssistantRuntimeOptions {\n /** Trusted server-side capabilities for custom registry item types. */\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n}\n\n/**\n * Creates the reusable assistant runtime without hiding Mastra from the host.\n * Register `agents` and `gateways` in the host's standard Mastra instance, then\n * call `createHandlers` with that instance and host authorization policy.\n */\nexport const createSurveyAssistantRuntime = (\n config: SurveyAssistantRuntimeConfig,\n runtimeOptions: CreateSurveyAssistantRuntimeOptions = {},\n): SurveyAssistantRuntime => {\n const components = createSurveyAssistantRuntimeComponents(config);\n return {\n ...components,\n config,\n createHandlers: (handlerOptions) =>\n createSurveyAssistantRuntimeHandlers({\n ...handlerOptions,\n chat: {\n ...handlerOptions.chat,\n trustedCapabilities:\n handlerOptions.chat?.trustedCapabilities ?? runtimeOptions.trustedCapabilities,\n },\n config,\n modelRouter: components.modelRouter,\n }),\n };\n};\n"],"mappings":";;;;;;;;AA+EA,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AACvB,MAAM,oCAAoC,MAAU;AACpD,MAAM,0BAA0B,MAAS;AACzC,MAAM,0BAA0B,OAAU;AAC1C,MAAM,yBAAyB,MAAS;AAExC,MAAM,YAAY,KAAkB,SAAiB;AAEnD,QADc,IAAI,OAAO,MAAM,IACf,KAAA;;AAGlB,MAAM,cAAc,KAAkB,MAAc,aAAsB;CACxE,MAAM,QAAQ,SAAS,KAAK,KAAK,EAAE,aAAa;AAChD,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,QAAS,QAAO;AAC9B,KAAI,UAAU,KAAA,EACZ,OAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;AAEvD,QAAO;;AAGT,MAAM,qBAAqB,KAAkB,MAAc,aAAqB;CAC9E,MAAM,aAAa,SAAS,KAAK,KAAK;AACtC,KAAI,eAAe,KAAA,EAAW,QAAO;CACrC,MAAM,QAAQ,OAAO,WAAW;AAChC,KAAI,CAAC,OAAO,cAAc,MAAM,IAAI,SAAS,EAC3C,OAAM,IAAI,MAAM,GAAG,KAAK,8BAA8B;AAExD,QAAO;;AAGT,MAAM,WACJ,KACA,MACA,WACG;CACH,MAAM,QAAQ,SAAS,KAAK,KAAK;AACjC,KAAI,CAAC,MAAO,QAAO,KAAA;AACnB,KAAI,CAAE,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N;EACD;;;;;;;AAoBH,MAAa,gCACX,QACA,iBAAsD,EAAE,KAC7B;CAC3B,MAAM,aAAa,uCAAuC,OAAO;AACjE,QAAO;EACL,GAAG;EACH;EACA,iBAAiB,mBACf,qCAAqC;GACnC,GAAG;GACH,MAAM;IACJ,GAAG,eAAe;IAClB,qBACE,eAAe,MAAM,uBAAuB,eAAe;IAC9D;GACD;GACA,aAAa,WAAW;GACzB,CAAC;EACL"}
1
+ {"version":3,"file":"server-runtime.mjs","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"sourcesContent":["import type { AgentExecutionOptions } from \"@mastra/core/agent\";\nimport type { AzureOpenAIGatewayConfig } from \"@mastra/core/llm\";\nimport { z } from \"zod\";\nimport {\n createSurveyAssistantObservationalMemoryOptions,\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS,\n type SurveyAssistantObservationalMemoryOptions,\n} from \"./agent\";\nimport {\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS,\n type SurveyAssistantRequestLimits,\n} from \"./request-guardrails\";\n\nexport type SurveyAssistantProvider = \"azure-openai\" | \"lmstudio\" | \"mistral\" | \"openai\";\nexport type SurveyAssistantProviderOptionsKey = \"azure\" | \"lmstudio\" | \"mistral\" | \"openai\";\n\nexport type SurveyAssistantModelRole = \"chat-default\" | \"chat-picker\" | \"memory\" | \"task-default\";\n\nexport interface SurveyAssistantConfiguredModel {\n id: string;\n label: string;\n upstreamModelId: string;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n}\n\nexport interface SurveyAssistantAzureConfig {\n apiKey?: string;\n apiVersion: \"preview\" | \"v1\";\n discoverModels: boolean;\n management?: AzureOpenAIGatewayConfig[\"management\"];\n resourceName?: string;\n}\n\nexport interface SurveyAssistantLmStudioConfig {\n apiKey?: string;\n baseUrl: string;\n}\n\nexport interface SurveyAssistantExecutionConfig {\n firstResponseTimeoutMs: number;\n idleTimeoutMs: number;\n maxConcurrentRequests: number;\n /** Absolute execution ceiling. Active streams still stop when this duration is reached. */\n maxDurationMs: number;\n maxSteps: number;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n sendReasoning: boolean;\n}\n\nexport interface SurveyAssistantRuntimeConfig {\n azure?: SurveyAssistantAzureConfig;\n lmstudio?: SurveyAssistantLmStudioConfig;\n /** Default chat model and fallback for chat requests without a selection. */\n defaultModelId: string;\n enabled: boolean;\n /** Fixed same-provider model shared by memory observation and reflection. */\n memoryModelId: string;\n modelCatalogTtlMs: number;\n /** Every configured model for the active provider, including internal-only roles. */\n models?: SurveyAssistantConfiguredModel[];\n modelIds: string[];\n observationalMemory: SurveyAssistantObservationalMemoryOptions | false;\n provider: SurveyAssistantProvider;\n /** Resolved server-only provider credential. Never expose it through the model catalog. */\n providerApiKey?: string;\n requestLimits: Pick<\n SurveyAssistantRequestLimits,\n | \"maxAttachmentBytes\"\n | \"maxAttachments\"\n | \"maxRequestBytes\"\n | \"maxTextPartChars\"\n | \"maxTotalAttachmentBytes\"\n >;\n readinessError: string | null;\n /**\n * Fixed model for one-shot tasks. When omitted, tasks follow the\n * server-authorized chat model selection.\n */\n taskModelId?: string;\n execution: SurveyAssistantExecutionConfig;\n}\n\nexport interface ParseSurveyAssistantEnvironmentOptions {\n defaultLmStudioModel?: string;\n defaultMistralModel?: string;\n defaultOpenAIModel?: string;\n defaultProvider?: SurveyAssistantProvider;\n requireExperimentalIdentityOptIn?: boolean;\n requireStorage?: boolean;\n}\n\ntype Environment = Record<string, string | undefined>;\n\nconst ENVIRONMENT_VARIABLE_NAME = /^[A-Z_][A-Z0-9_]*$/;\n\nconst modelRoleSchema = z.enum([\"chat-default\", \"chat-picker\", \"memory\", \"task-default\"]);\n\nconst providerModelOptionsSchema = z\n .object({\n parallelToolCalls: z.boolean().optional(),\n promptCacheKey: z.string().trim().min(1).optional(),\n promptCacheRetention: z.enum([\"in_memory\", \"24h\"]).optional(),\n reasoningEffort: z.string().trim().min(1).optional(),\n reasoningSummary: z.enum([\"auto\", \"concise\", \"detailed\", \"off\", \"none\"]).optional(),\n serviceTier: z.enum([\"auto\", \"flex\", \"priority\", \"default\"]).optional(),\n textVerbosity: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n })\n .strict();\n\nconst configuredModelSchema = z\n .object({\n id: z.string().trim().min(1).max(240),\n label: z.string().trim().min(1).max(240).optional(),\n upstreamModel: z.string().trim().min(1).max(240).optional(),\n roles: z.array(modelRoleSchema).min(1),\n options: providerModelOptionsSchema.optional(),\n })\n .strict()\n .superRefine(({ roles }, context) => {\n if (new Set(roles).size !== roles.length) {\n context.addIssue({ code: \"custom\", message: \"Model roles must be unique.\" });\n }\n });\n\nconst providerBaseShape = {\n apiKeyEnv: z.string().regex(ENVIRONMENT_VARIABLE_NAME).optional(),\n models: z.array(configuredModelSchema).min(1),\n options: providerModelOptionsSchema.optional(),\n};\n\nconst providerSchema = z.discriminatedUnion(\"type\", [\n z\n .object({\n ...providerBaseShape,\n type: z.literal(\"openai\"),\n apiKeyEnv: z.string().regex(ENVIRONMENT_VARIABLE_NAME),\n })\n .strict(),\n z\n .object({\n ...providerBaseShape,\n type: z.literal(\"mistral\"),\n apiKeyEnv: z.string().regex(ENVIRONMENT_VARIABLE_NAME),\n })\n .strict(),\n z\n .object({\n ...providerBaseShape,\n type: z.literal(\"lmstudio\"),\n baseUrl: z.string().url().default(\"http://127.0.0.1:1234/v1\"),\n apiKeyOptional: z.boolean().default(true),\n })\n .strict(),\n z\n .object({\n ...providerBaseShape,\n type: z.literal(\"azure-openai\"),\n apiKeyEnv: z.string().regex(ENVIRONMENT_VARIABLE_NAME),\n apiVersion: z.enum([\"v1\", \"preview\"]).default(\"v1\"),\n discoverModels: z.boolean().default(false),\n resourceName: z.string().trim().min(1),\n management: z\n .object({\n tenantId: z.string().trim().min(1),\n clientId: z.string().trim().min(1),\n clientSecretEnv: z.string().regex(ENVIRONMENT_VARIABLE_NAME),\n subscriptionId: z.string().trim().min(1),\n resourceGroup: z.string().trim().min(1),\n })\n .strict()\n .optional(),\n })\n .strict(),\n]);\n\nexport const surveyAssistantConfigurationDocumentSchema = z\n .object({\n version: z.literal(1),\n activeProvider: z.string().trim().min(1),\n enabled: z.boolean().optional(),\n providers: z.record(z.string().trim().min(1), providerSchema),\n execution: z\n .object({\n firstResponseTimeoutMs: z.number().int().positive().optional(),\n idleTimeoutMs: z.number().int().positive().optional(),\n maxConcurrentRequests: z.number().int().positive().optional(),\n maxDurationMs: z.number().int().positive().optional(),\n maxSteps: z.number().int().positive().optional(),\n sendReasoning: z.boolean().optional(),\n })\n .strict()\n .optional(),\n memory: z\n .object({\n enabled: z.boolean().optional(),\n bufferOnIdle: z.boolean().optional(),\n messageTokens: z.number().int().positive().optional(),\n observationTokens: z.number().int().positive().optional(),\n temporalMarkers: z.boolean().optional(),\n })\n .strict()\n .optional(),\n modelCatalogTtlMs: z.number().int().positive().optional(),\n requestLimits: z\n .object({\n maxAttachmentBytes: z.number().int().positive().optional(),\n maxAttachments: z.number().int().positive().optional(),\n maxRequestBytes: z.number().int().positive().optional(),\n maxTextPartChars: z.number().int().positive().optional(),\n maxTotalAttachmentBytes: z.number().int().positive().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type SurveyAssistantConfigurationDocument = z.infer<\n typeof surveyAssistantConfigurationDocumentSchema\n>;\n\nconst DEFAULT_MAX_STEPS = 48;\nconst HARD_MAX_STEPS = 64;\nconst DEFAULT_FIRST_RESPONSE_TIMEOUT_MS = 15 * 60 * 1_000;\nconst DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1_000;\nconst DEFAULT_MAX_DURATION_MS = 60 * 60 * 1_000;\nconst DEFAULT_CATALOG_TTL_MS = 5 * 60 * 1_000;\n\ntype ProviderModelOptions = z.infer<typeof providerModelOptionsSchema>;\n\nconst getValue = (env: Environment, name: string) => {\n const value = env[name]?.trim();\n return value || undefined;\n};\n\nconst getBoolean = (env: Environment, name: string, fallback: boolean) => {\n const value = getValue(env, name)?.toLowerCase();\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (value !== undefined) {\n throw new Error(`${name} must be \"true\" or \"false\".`);\n }\n return fallback;\n};\n\nconst getPositiveNumber = (env: Environment, name: string, fallback: number) => {\n const configured = getValue(env, name);\n if (configured === undefined) return fallback;\n const value = Number(configured);\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return value;\n};\n\nconst getEnum = <TValue extends string>(\n env: Environment,\n name: string,\n values: readonly TValue[],\n) => {\n const value = getValue(env, name);\n if (!value) return undefined;\n if (!(values as readonly string[]).includes(value)) {\n throw new Error(`${name} must be one of: ${values.join(\", \")}.`);\n }\n return value as TValue;\n};\n\nconst getCommaSeparatedValues = (env: Environment, name: string) => [\n ...new Set(\n (getValue(env, name) ?? \"\")\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean),\n ),\n];\n\nconst getSameProviderModelId = (\n value: string,\n name: string,\n { allowNestedId = false }: { allowNestedId?: boolean } = {},\n) => {\n if (!allowNestedId && value.includes(\"/\")) {\n throw new Error(\n `${name} must be a model or deployment id without a provider prefix. ` +\n \"All survey assistant models use SURVEY_ASSISTANT_PROVIDER.\",\n );\n }\n return value;\n};\n\nconst getOptionalSameProviderModelId = (\n env: Environment,\n name: string,\n options?: { allowNestedId?: boolean },\n) => {\n const value = getValue(env, name);\n return value ? getSameProviderModelId(value, name, options) : undefined;\n};\n\nexport const resolveSurveyAssistantProviderOptionsKey = (\n provider: SurveyAssistantProvider,\n): SurveyAssistantProviderOptionsKey => (provider === \"azure-openai\" ? \"azure\" : provider);\n\nconst createProviderOptions = (\n provider: SurveyAssistantProvider,\n options: ProviderModelOptions | undefined,\n sendReasoning: boolean,\n): AgentExecutionOptions[\"providerOptions\"] => {\n const providerOptionsKey = resolveSurveyAssistantProviderOptionsKey(provider);\n const reasoningSummary =\n options?.reasoningSummary === \"off\" || options?.reasoningSummary === \"none\"\n ? undefined\n : options?.reasoningSummary;\n const reasoningEffort =\n options?.reasoningEffort === \"default\" || options?.reasoningEffort === \"provider-default\"\n ? undefined\n : options?.reasoningEffort;\n const resolved = {\n parallelToolCalls: options?.parallelToolCalls ?? false,\n ...(reasoningEffort ? { reasoningEffort } : {}),\n ...(options?.promptCacheKey ? { promptCacheKey: options.promptCacheKey } : {}),\n ...(options?.promptCacheRetention\n ? { promptCacheRetention: options.promptCacheRetention }\n : {}),\n ...(sendReasoning && reasoningSummary ? { reasoningSummary } : {}),\n ...(options?.serviceTier ? { serviceTier: options.serviceTier } : {}),\n ...(options?.textVerbosity ? { textVerbosity: options.textVerbosity } : {}),\n };\n return { [providerOptionsKey]: resolved } as AgentExecutionOptions[\"providerOptions\"];\n};\n\nconst resolveConfiguredEnabled = (\n env: Environment,\n configured: boolean | undefined,\n requireExperimentalIdentityOptIn: boolean,\n) => {\n const environmentOverride = getValue(env, \"SURVEY_ASSISTANT_ENABLED\");\n if (\n environmentOverride !== undefined &&\n environmentOverride !== \"true\" &&\n environmentOverride !== \"false\"\n ) {\n throw new Error('SURVEY_ASSISTANT_ENABLED must be \"true\" or \"false\".');\n }\n const requested =\n environmentOverride === \"true\"\n ? true\n : environmentOverride === \"false\"\n ? false\n : (configured ?? env.NODE_ENV === \"development\");\n return (\n requested &&\n (!requireExperimentalIdentityOptIn ||\n env.NODE_ENV === \"development\" ||\n getBoolean(env, \"SURVEY_ASSISTANT_ALLOW_EXPERIMENTAL_IDENTITY\", false))\n );\n};\n\nconst parseProvider = (\n env: Environment,\n fallback: SurveyAssistantProvider,\n): SurveyAssistantProvider => {\n const value = getValue(env, \"SURVEY_ASSISTANT_PROVIDER\")?.toLowerCase();\n if (value === \"azure\" || value === \"azure-openai\") return \"azure-openai\";\n if (value === \"lmstudio\" || value === \"openai\" || value === \"mistral\") return value;\n if (value) {\n throw new Error(\n \"SURVEY_ASSISTANT_PROVIDER must be one of: openai, mistral, lmstudio, azure-openai.\",\n );\n }\n return fallback;\n};\n\nconst parseAzureManagement = (\n env: Environment,\n): AzureOpenAIGatewayConfig[\"management\"] | undefined => {\n if (!getBoolean(env, \"SURVEY_ASSISTANT_AZURE_DISCOVER_MODELS\", false)) return undefined;\n const management = {\n tenantId: getValue(env, \"AZURE_TENANT_ID\"),\n clientId: getValue(env, \"AZURE_CLIENT_ID\"),\n clientSecret: getValue(env, \"AZURE_CLIENT_SECRET\"),\n subscriptionId: getValue(env, \"AZURE_SUBSCRIPTION_ID\"),\n resourceGroup: getValue(env, \"AZURE_RESOURCE_GROUP\"),\n };\n return Object.values(management).every(Boolean)\n ? (management as AzureOpenAIGatewayConfig[\"management\"])\n : undefined;\n};\n\nconst getReadinessError = ({\n azure,\n env,\n modelWasConfigured,\n provider,\n requireStorage,\n}: {\n azure?: SurveyAssistantAzureConfig;\n env: Environment;\n modelWasConfigured: boolean;\n provider: SurveyAssistantProvider;\n requireStorage: boolean;\n}) => {\n if (\n requireStorage &&\n !getValue(env, \"SURVEY_ASSISTANT_DATABASE_URL\") &&\n !getValue(env, \"DATABASE_URL\")\n ) {\n return \"Survey assistant storage is not configured.\";\n }\n if (provider === \"openai\" && !getValue(env, \"OPENAI_API_KEY\")) {\n return \"The OpenAI API key is not configured for the survey assistant.\";\n }\n if (provider === \"mistral\" && !getValue(env, \"MISTRAL_API_KEY\")) {\n return \"The Mistral API key is not configured for the survey assistant.\";\n }\n if (provider === \"azure-openai\") {\n if (!azure?.resourceName) {\n return \"The Azure OpenAI resource name is not configured for the survey assistant.\";\n }\n if (!azure.apiKey) {\n return \"The Azure OpenAI API key is not configured for the survey assistant.\";\n }\n if (!modelWasConfigured) {\n return \"The Azure OpenAI deployment name is not configured for the survey assistant.\";\n }\n if (azure.discoverModels && !azure.management) {\n return \"Azure deployment discovery requires complete tenant, client, subscription, and resource-group settings.\";\n }\n }\n return null;\n};\n\nexport const parseSurveyAssistantConfigurationDocument = (\n input: unknown,\n env: Environment,\n {\n requireExperimentalIdentityOptIn = false,\n requireStorage = true,\n }: Pick<\n ParseSurveyAssistantEnvironmentOptions,\n \"requireExperimentalIdentityOptIn\" | \"requireStorage\"\n > = {},\n): SurveyAssistantRuntimeConfig => {\n const document = surveyAssistantConfigurationDocumentSchema.parse(input);\n const activeProvider = document.providers[document.activeProvider];\n if (!activeProvider) {\n throw new Error(`activeProvider references unknown provider \"${document.activeProvider}\".`);\n }\n\n const memoryEnabled = document.memory?.enabled ?? true;\n for (const [providerName, configuredProvider] of Object.entries(document.providers)) {\n const duplicateModelId = configuredProvider.models.find(\n (model, index, models) =>\n models.findIndex((candidate) => candidate.id === model.id) !== index,\n )?.id;\n if (duplicateModelId) {\n throw new Error(\n `Provider \"${providerName}\" contains duplicate model id \"${duplicateModelId}\".`,\n );\n }\n const modelsForProviderRole = (role: SurveyAssistantModelRole) =>\n configuredProvider.models.filter((model) => model.roles.includes(role));\n const providerChatDefaults = modelsForProviderRole(\"chat-default\");\n const providerChatModels = modelsForProviderRole(\"chat-picker\");\n const providerTaskDefaults = modelsForProviderRole(\"task-default\");\n const providerMemoryModels = modelsForProviderRole(\"memory\");\n if (providerChatDefaults.length !== 1) {\n throw new Error(`Provider \"${providerName}\" must configure exactly one chat-default model.`);\n }\n if (!providerChatDefaults[0].roles.includes(\"chat-picker\")) {\n throw new Error(\n `The chat-default model for provider \"${providerName}\" must also have the chat-picker role.`,\n );\n }\n if (providerChatModels.length === 0) {\n throw new Error(`Provider \"${providerName}\" must configure a chat-picker model.`);\n }\n if (providerTaskDefaults.length > 1) {\n throw new Error(`Provider \"${providerName}\" may configure at most one task-default model.`);\n }\n if (providerMemoryModels.length > 1 || (memoryEnabled && providerMemoryModels.length !== 1)) {\n throw new Error(\n memoryEnabled\n ? `Provider \"${providerName}\" must configure exactly one memory model when memory is enabled.`\n : `Provider \"${providerName}\" may configure at most one memory model.`,\n );\n }\n if (\n configuredProvider.type === \"lmstudio\" &&\n !configuredProvider.apiKeyOptional &&\n !configuredProvider.apiKeyEnv\n ) {\n throw new Error(\n `Provider \"${providerName}\" must configure apiKeyEnv when apiKeyOptional is false.`,\n );\n }\n const validateOptions = (options: ProviderModelOptions | undefined, location: string) => {\n if (!options) return;\n if (\n configuredProvider.type !== \"openai\" &&\n configuredProvider.type !== \"azure-openai\" &&\n (options.promptCacheKey ||\n options.promptCacheRetention ||\n options.reasoningSummary ||\n options.textVerbosity)\n ) {\n throw new Error(`${location} contains options unsupported by ${configuredProvider.type}.`);\n }\n if (configuredProvider.type !== \"openai\" && options.serviceTier) {\n throw new Error(`${location} contains serviceTier, which is only supported by openai.`);\n }\n };\n validateOptions(configuredProvider.options, `Provider \"${providerName}\"`);\n for (const model of configuredProvider.models) {\n const upstreamModelId = model.upstreamModel ?? model.id;\n if (configuredProvider.type !== \"lmstudio\" && upstreamModelId.includes(\"/\")) {\n throw new Error(\n `Model \"${model.id}\" must use an upstreamModel without a provider prefix for ${configuredProvider.type}.`,\n );\n }\n validateOptions(model.options, `Model \"${model.id}\" in provider \"${providerName}\"`);\n }\n }\n\n const modelsForRole = (role: SurveyAssistantModelRole) =>\n activeProvider.models.filter((model) => model.roles.includes(role));\n const chatDefaults = modelsForRole(\"chat-default\");\n const chatModels = modelsForRole(\"chat-picker\");\n const taskDefaults = modelsForRole(\"task-default\");\n const memoryModels = modelsForRole(\"memory\");\n\n const provider = activeProvider.type;\n\n const sendReasoning = document.execution?.sendReasoning ?? true;\n const providerDefaults: ProviderModelOptions = {\n parallelToolCalls: false,\n ...(provider === \"openai\" || provider === \"azure-openai\"\n ? {\n reasoningEffort: \"low\",\n reasoningSummary: \"detailed\" as const,\n promptCacheKey: \"survey-assistant-chat-v21\",\n }\n : provider === \"mistral\"\n ? { reasoningEffort: \"none\" }\n : {}),\n ...activeProvider.options,\n };\n const models: SurveyAssistantConfiguredModel[] = activeProvider.models.map((model) => ({\n id: model.id,\n label: model.label ?? model.id,\n upstreamModelId: model.upstreamModel ?? model.id,\n providerOptions: createProviderOptions(\n provider,\n { ...providerDefaults, ...model.options },\n sendReasoning,\n ),\n }));\n const configuredModel = (id: string) => models.find((model) => model.id === id)!;\n const defaultModelId = chatDefaults[0].id;\n const memoryModelId = (memoryModels[0] ?? chatDefaults[0]).id;\n const taskModelId = taskDefaults[0]?.id;\n const providerApiKey = activeProvider.apiKeyEnv\n ? getValue(env, activeProvider.apiKeyEnv)\n : undefined;\n const memoryModel = configuredModel(memoryModelId);\n const memoryModelConfig:\n | string\n | { id: `${string}/${string}`; apiKey?: string }\n | {\n providerId: string;\n modelId: string;\n url: string;\n apiKey?: string;\n } =\n provider === \"lmstudio\"\n ? {\n providerId: \"lmstudio\",\n modelId: memoryModel.upstreamModelId,\n url: activeProvider.baseUrl,\n ...(providerApiKey ? { apiKey: providerApiKey } : {}),\n }\n : provider === \"azure-openai\"\n ? `${provider}/${memoryModel.upstreamModelId}`\n : {\n id: `${provider}/${memoryModel.upstreamModelId}`,\n ...(providerApiKey ? { apiKey: providerApiKey } : {}),\n };\n const azure: SurveyAssistantAzureConfig | undefined =\n provider === \"azure-openai\"\n ? {\n resourceName: activeProvider.resourceName,\n apiKey: providerApiKey,\n apiVersion: activeProvider.apiVersion,\n discoverModels: activeProvider.discoverModels,\n management: activeProvider.management\n ? {\n tenantId: activeProvider.management.tenantId,\n clientId: activeProvider.management.clientId,\n clientSecret: getValue(env, activeProvider.management.clientSecretEnv) ?? \"\",\n subscriptionId: activeProvider.management.subscriptionId,\n resourceGroup: activeProvider.management.resourceGroup,\n }\n : undefined,\n }\n : undefined;\n const lmstudio: SurveyAssistantLmStudioConfig | undefined =\n provider === \"lmstudio\"\n ? { baseUrl: activeProvider.baseUrl, ...(providerApiKey ? { apiKey: providerApiKey } : {}) }\n : undefined;\n const missingProviderSecret =\n activeProvider.apiKeyEnv &&\n !providerApiKey &&\n !(provider === \"lmstudio\" && activeProvider.apiKeyOptional);\n const missingManagementSecret =\n provider === \"azure-openai\" &&\n activeProvider.discoverModels &&\n (!activeProvider.management || !azure?.management?.clientSecret);\n const missingStorage =\n requireStorage &&\n !getValue(env, \"SURVEY_ASSISTANT_DATABASE_URL\") &&\n !getValue(env, \"DATABASE_URL\");\n const readinessError = missingStorage\n ? \"Survey assistant storage is not configured.\"\n : missingProviderSecret\n ? `The provider credential ${activeProvider.apiKeyEnv} is not configured for the survey assistant.`\n : missingManagementSecret\n ? \"Azure deployment discovery requires complete management configuration and credentials.\"\n : null;\n const configuredMaxSteps = document.execution?.maxSteps ?? DEFAULT_MAX_STEPS;\n\n return {\n provider,\n providerApiKey,\n defaultModelId,\n memoryModelId,\n taskModelId,\n modelIds: chatModels.map((model) => model.id),\n models,\n modelCatalogTtlMs: document.modelCatalogTtlMs ?? DEFAULT_CATALOG_TTL_MS,\n azure,\n lmstudio,\n enabled: resolveConfiguredEnabled(env, document.enabled, requireExperimentalIdentityOptIn),\n readinessError,\n requestLimits: {\n maxAttachmentBytes:\n document.requestLimits?.maxAttachmentBytes ??\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachmentBytes,\n maxAttachments:\n document.requestLimits?.maxAttachments ??\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachments,\n maxRequestBytes:\n document.requestLimits?.maxRequestBytes ??\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxRequestBytes,\n maxTextPartChars:\n document.requestLimits?.maxTextPartChars ??\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTextPartChars,\n maxTotalAttachmentBytes:\n document.requestLimits?.maxTotalAttachmentBytes ??\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTotalAttachmentBytes,\n },\n execution: {\n firstResponseTimeoutMs:\n document.execution?.firstResponseTimeoutMs ?? DEFAULT_FIRST_RESPONSE_TIMEOUT_MS,\n idleTimeoutMs: document.execution?.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\n maxConcurrentRequests: document.execution?.maxConcurrentRequests ?? 4,\n maxDurationMs: document.execution?.maxDurationMs ?? DEFAULT_MAX_DURATION_MS,\n maxSteps: Math.min(configuredMaxSteps, HARD_MAX_STEPS),\n providerOptions: configuredModel(defaultModelId).providerOptions,\n sendReasoning,\n },\n observationalMemory: memoryEnabled\n ? createSurveyAssistantObservationalMemoryOptions({\n model: memoryModelConfig,\n temporalMarkers: document.memory?.temporalMarkers ?? false,\n observation: {\n messageTokens:\n document.memory?.messageTokens ??\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferOnIdle: document.memory?.bufferOnIdle ?? false,\n observeAttachments: false,\n },\n reflection: {\n observationTokens:\n document.memory?.observationTokens ??\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n },\n })\n : false,\n };\n};\n\nexport const parseSurveyAssistantEnvironment = (\n env: Environment,\n {\n defaultLmStudioModel,\n defaultMistralModel = \"mistral-medium-latest\",\n defaultOpenAIModel = \"gpt-5.4-nano\",\n defaultProvider = \"openai\",\n requireExperimentalIdentityOptIn = false,\n requireStorage = true,\n }: ParseSurveyAssistantEnvironmentOptions = {},\n): SurveyAssistantRuntimeConfig => {\n const provider = parseProvider(env, defaultProvider);\n const modelIdOptions = { allowNestedId: provider === \"lmstudio\" };\n const configuredModelId = getOptionalSameProviderModelId(\n env,\n \"SURVEY_ASSISTANT_MODEL\",\n modelIdOptions,\n );\n if (provider === \"lmstudio\" && !configuredModelId && !defaultLmStudioModel) {\n throw new Error(\n \"SURVEY_ASSISTANT_MODEL must be configured when SURVEY_ASSISTANT_PROVIDER is lmstudio.\",\n );\n }\n const defaultModelId =\n configuredModelId ??\n getSameProviderModelId(\n provider === \"lmstudio\"\n ? defaultLmStudioModel!\n : provider === \"mistral\"\n ? defaultMistralModel\n : defaultOpenAIModel,\n provider === \"lmstudio\"\n ? \"defaultLmStudioModel\"\n : provider === \"mistral\"\n ? \"defaultMistralModel\"\n : \"defaultOpenAIModel\",\n modelIdOptions,\n );\n const configuredModelIds = getCommaSeparatedValues(env, \"SURVEY_ASSISTANT_MODELS\").map(\n (modelId) => getSameProviderModelId(modelId, \"SURVEY_ASSISTANT_MODELS\", modelIdOptions),\n );\n const modelIds = [\n ...new Set(\n configuredModelIds.includes(defaultModelId)\n ? configuredModelIds\n : [defaultModelId, ...configuredModelIds],\n ),\n ];\n const taskModelId = getOptionalSameProviderModelId(\n env,\n \"SURVEY_ASSISTANT_TASK_MODEL\",\n modelIdOptions,\n );\n const sendReasoning = getBoolean(env, \"SURVEY_ASSISTANT_SEND_REASONING\", true);\n const providerOptionsKey = resolveSurveyAssistantProviderOptionsKey(provider);\n const providerReasoningEffort = getValue(\n env,\n `SURVEY_ASSISTANT_${providerOptionsKey.toUpperCase()}_REASONING_EFFORT`,\n );\n const reasoningEffort =\n providerReasoningEffort ??\n getValue(env, \"SURVEY_ASSISTANT_REASONING_EFFORT\") ??\n (provider === \"openai\" || provider === \"azure-openai\" ? \"low\" : \"none\");\n const promptCacheRetention = getEnum(\n env,\n provider === \"azure-openai\"\n ? \"SURVEY_ASSISTANT_AZURE_PROMPT_CACHE_RETENTION\"\n : \"SURVEY_ASSISTANT_PROMPT_CACHE_RETENTION\",\n [\"in_memory\", \"24h\"] as const,\n );\n const serviceTier = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_SERVICE_TIER\", [\n \"auto\",\n \"flex\",\n \"priority\",\n \"default\",\n ] as const);\n const textVerbosity = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_TEXT_VERBOSITY\", [\n \"low\",\n \"medium\",\n \"high\",\n ] as const);\n const reasoningSummaryValue = getEnum(env, \"SURVEY_ASSISTANT_OPENAI_REASONING_SUMMARY\", [\n \"auto\",\n \"concise\",\n \"detailed\",\n \"off\",\n \"none\",\n ] as const);\n const reasoningSummary =\n reasoningSummaryValue === \"off\" || reasoningSummaryValue === \"none\"\n ? undefined\n : (reasoningSummaryValue ?? \"detailed\");\n const resolvedReasoningEffort =\n reasoningEffort === \"default\" || reasoningEffort === \"provider-default\"\n ? undefined\n : reasoningEffort;\n const providerOptions: AgentExecutionOptions[\"providerOptions\"] =\n provider === \"lmstudio\"\n ? undefined\n : {\n [providerOptionsKey]: {\n parallelToolCalls: false,\n ...(resolvedReasoningEffort ? { reasoningEffort: resolvedReasoningEffort } : {}),\n ...(provider === \"openai\" || provider === \"azure-openai\"\n ? {\n promptCacheKey:\n getValue(env, \"SURVEY_ASSISTANT_PROMPT_CACHE_KEY\") ??\n \"survey-assistant-chat-v21\",\n ...(promptCacheRetention ? { promptCacheRetention } : {}),\n ...(sendReasoning && reasoningSummary ? { reasoningSummary } : {}),\n ...(provider === \"openai\" && serviceTier ? { serviceTier } : {}),\n ...(textVerbosity ? { textVerbosity } : {}),\n }\n : {}),\n },\n };\n const azure: SurveyAssistantAzureConfig | undefined =\n provider === \"azure-openai\"\n ? {\n resourceName: getValue(env, \"AZURE_RESOURCE_NAME\"),\n apiKey: getValue(env, \"AZURE_API_KEY\"),\n apiVersion: getEnum(env, \"SURVEY_ASSISTANT_AZURE_API_VERSION\", [\"v1\", \"preview\"]) ?? \"v1\",\n discoverModels: getBoolean(env, \"SURVEY_ASSISTANT_AZURE_DISCOVER_MODELS\", false),\n management: parseAzureManagement(env),\n }\n : undefined;\n const lmstudio: SurveyAssistantLmStudioConfig | undefined =\n provider === \"lmstudio\"\n ? {\n baseUrl:\n getValue(env, \"SURVEY_ASSISTANT_LMSTUDIO_BASE_URL\") ?? \"http://127.0.0.1:1234/v1\",\n apiKey: getValue(env, \"SURVEY_ASSISTANT_LMSTUDIO_API_KEY\"),\n }\n : undefined;\n const providerApiKey =\n provider === \"openai\"\n ? getValue(env, \"OPENAI_API_KEY\")\n : provider === \"mistral\"\n ? getValue(env, \"MISTRAL_API_KEY\")\n : provider === \"lmstudio\"\n ? getValue(env, \"SURVEY_ASSISTANT_LMSTUDIO_API_KEY\")\n : getValue(env, \"AZURE_API_KEY\");\n const memoryModelId =\n getOptionalSameProviderModelId(env, \"SURVEY_ASSISTANT_MEMORY_MODEL\", modelIdOptions) ??\n defaultModelId;\n const memoryModel =\n provider === \"lmstudio\"\n ? {\n providerId: \"lmstudio\",\n modelId: memoryModelId,\n url: lmstudio!.baseUrl,\n ...(providerApiKey ? { apiKey: providerApiKey } : {}),\n }\n : provider === \"azure-openai\"\n ? `${provider}/${memoryModelId}`\n : `${provider}/${memoryModelId}`;\n const observationalMemory = getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_ENABLED\", true)\n ? createSurveyAssistantObservationalMemoryOptions({\n model: memoryModel,\n temporalMarkers: getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_TEMPORAL_MARKERS\", false),\n observation: {\n messageTokens: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MEMORY_MESSAGE_TOKENS\",\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n ),\n bufferOnIdle: getBoolean(env, \"SURVEY_ASSISTANT_MEMORY_BUFFER_ON_IDLE\", false),\n observeAttachments: false,\n },\n reflection: {\n observationTokens: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MEMORY_OBSERVATION_TOKENS\",\n SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n ),\n },\n })\n : false;\n const configuredMaxSteps = getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_STEPS\",\n DEFAULT_MAX_STEPS,\n );\n const enabled = resolveConfiguredEnabled(env, undefined, requireExperimentalIdentityOptIn);\n const allModelIds = [\n ...new Set([...modelIds, ...(taskModelId ? [taskModelId] : []), memoryModelId]),\n ];\n\n return {\n provider,\n defaultModelId,\n memoryModelId,\n modelIds,\n models: allModelIds.map((id) => ({\n id,\n label: id,\n upstreamModelId: id,\n providerOptions,\n })),\n modelCatalogTtlMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MODEL_CATALOG_TTL_MS\",\n DEFAULT_CATALOG_TTL_MS,\n ),\n azure,\n lmstudio,\n enabled,\n readinessError: getReadinessError({\n azure,\n env,\n modelWasConfigured: Boolean(configuredModelId),\n provider,\n requireStorage,\n }),\n requestLimits: {\n maxAttachmentBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachmentBytes,\n ),\n maxAttachments: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_ATTACHMENTS\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxAttachments,\n ),\n maxRequestBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_REQUEST_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxRequestBytes,\n ),\n maxTextPartChars: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTextPartChars,\n ),\n maxTotalAttachmentBytes: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES\",\n SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS.maxTotalAttachmentBytes,\n ),\n },\n execution: {\n firstResponseTimeoutMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_FIRST_RESPONSE_TIMEOUT_MS\",\n DEFAULT_FIRST_RESPONSE_TIMEOUT_MS,\n ),\n idleTimeoutMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_IDLE_TIMEOUT_MS\",\n DEFAULT_IDLE_TIMEOUT_MS,\n ),\n maxConcurrentRequests: getPositiveNumber(env, \"SURVEY_ASSISTANT_MAX_CONCURRENT_REQUESTS\", 4),\n maxDurationMs: getPositiveNumber(\n env,\n \"SURVEY_ASSISTANT_MAX_DURATION_MS\",\n DEFAULT_MAX_DURATION_MS,\n ),\n maxSteps: Math.min(configuredMaxSteps, HARD_MAX_STEPS),\n providerOptions,\n sendReasoning,\n },\n observationalMemory,\n taskModelId,\n };\n};\n","import type { AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { AzureOpenAIGateway, type MastraModelGatewayInterface } from \"@mastra/core/llm\";\nimport type { Mastra } from \"@mastra/core/mastra\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport type { SurveyAssistantModelCatalog } from \"../protocol\";\nimport { createSurveyAssistantAgent, type CreateSurveyAssistantAgentOptions } from \"./agent\";\nimport { SURVEY_ASSISTANT_AGENT_ID, SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\nimport {\n createSurveyAssistantChatHandler,\n SurveyAssistantAuthorizationError,\n type SurveyAssistantAuthorize,\n type SurveyAssistantChatHandlerOptions,\n type SurveyAssistantResolveModel,\n} from \"./handler\";\nimport { createMastraMemoryThreadRepository } from \"./memory-thread-repository\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport type { SurveyAssistantCapabilitySet } from \"../engine\";\nimport type { SurveyAssistantRuntimeConfig } from \"./runtime-config\";\nimport {\n createSurveyAssistantTaskAgent,\n createSurveyAssistantTaskHandler,\n type CreateSurveyAssistantTaskHandlerOptions,\n type SurveyAssistantTaskModelResolutionInput,\n} from \"./tasks\";\nimport type { SurveyAssistantThreadDocumentRepository } from \"./thread-documents\";\nimport {\n createSurveyAssistantThreadHandlers,\n type CreateSurveyAssistantThreadHandlersOptions,\n} from \"./thread-handlers\";\nimport { SURVEY_ASSISTANT_TOOL_IDS } from \"./tools\";\n\nexport {\n parseSurveyAssistantEnvironment,\n parseSurveyAssistantConfigurationDocument,\n resolveSurveyAssistantProviderOptionsKey,\n surveyAssistantConfigurationDocumentSchema,\n type ParseSurveyAssistantEnvironmentOptions,\n type SurveyAssistantAzureConfig,\n type SurveyAssistantConfigurationDocument,\n type SurveyAssistantConfiguredModel,\n type SurveyAssistantExecutionConfig,\n type SurveyAssistantLmStudioConfig,\n type SurveyAssistantModelRole,\n type SurveyAssistantProvider,\n type SurveyAssistantProviderOptionsKey,\n type SurveyAssistantRuntimeConfig,\n} from \"./runtime-config\";\n\nexport interface SurveyAssistantModelRouter {\n defaultModel: SurveyAssistantModelSelection[\"model\"];\n gateways?: Record<string, MastraModelGatewayInterface>;\n getCatalog(options?: { refresh?: boolean }): Promise<SurveyAssistantModelCatalog>;\n memoryModel: SurveyAssistantModelSelection[\"model\"];\n providerName: string;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel: SurveyAssistantResolveModel;\n resolveTaskModel(\n input: SurveyAssistantTaskModelResolutionInput,\n ): ReturnType<SurveyAssistantResolveModel>;\n taskModel?: SurveyAssistantModelSelection[\"model\"];\n}\n\nexport const createSurveyAssistantModelRouter = (\n config: SurveyAssistantRuntimeConfig,\n): SurveyAssistantModelRouter => {\n const configuredModels = new Map(config.models?.map((model) => [model.id, model]));\n const getConfiguredModel = (modelId: string) =>\n configuredModels.get(modelId) ?? {\n id: modelId,\n label: modelId,\n upstreamModelId: modelId,\n providerOptions: config.execution.providerOptions,\n };\n const toProviderModel = (\n modelId: string,\n configName: string,\n ): SurveyAssistantModelSelection[\"model\"] => {\n const configuredModel = getConfiguredModel(modelId);\n const upstreamModelId = configuredModel.upstreamModelId;\n if (config.provider === \"lmstudio\") {\n if (!config.lmstudio) {\n throw new Error(\"LM Studio configuration is missing for the lmstudio provider.\");\n }\n return {\n providerId: \"lmstudio\",\n modelId: upstreamModelId,\n url: config.lmstudio.baseUrl,\n ...(config.lmstudio.apiKey ? { apiKey: config.lmstudio.apiKey } : {}),\n };\n }\n if (upstreamModelId.includes(\"/\")) {\n throw new Error(\n `${configName} must be a model or deployment id without a provider prefix. ` +\n \"All survey assistant models use the configured provider.\",\n );\n }\n const id = `${config.provider}/${upstreamModelId}` as `${string}/${string}`;\n return config.providerApiKey && config.provider !== \"azure-openai\"\n ? { id, apiKey: config.providerApiKey }\n : id;\n };\n const defaultModel = toProviderModel(config.defaultModelId, \"defaultModelId\");\n const chatModelIds = config.modelIds.map((modelId) => {\n toProviderModel(modelId, \"modelIds\");\n return modelId;\n });\n if (!chatModelIds.includes(config.defaultModelId)) {\n throw new Error(\"modelIds must include defaultModelId.\");\n }\n const taskModel = config.taskModelId\n ? toProviderModel(config.taskModelId, \"taskModelId\")\n : undefined;\n const memoryModel = toProviderModel(config.memoryModelId, \"memoryModelId\");\n if (config.observationalMemory !== false) {\n const configuredMemoryModel = toProviderModel(config.memoryModelId, \"memoryModelId\");\n if (\n JSON.stringify(config.observationalMemory.model) !== JSON.stringify(configuredMemoryModel) ||\n config.observationalMemory.observation?.model !== undefined ||\n config.observationalMemory.reflection?.model !== undefined\n ) {\n throw new Error(\n \"The standard runtime requires observationalMemory to use memoryModelId \" +\n \"for both observation and reflection. Use the low-level Agent factory \" +\n \"for custom memory model routing.\",\n );\n }\n }\n const deploymentIds = [\n ...new Set([\n ...chatModelIds.map((id) => getConfiguredModel(id).upstreamModelId),\n ...(config.taskModelId ? [getConfiguredModel(config.taskModelId).upstreamModelId] : []),\n getConfiguredModel(config.memoryModelId).upstreamModelId,\n ]),\n ];\n const azureGateway = config.azure\n ? new AzureOpenAIGateway({\n resourceName: config.azure.resourceName ?? \"\",\n apiKey: config.azure.apiKey,\n apiVersion: config.azure.apiVersion,\n useResponsesAPI: true,\n ...(config.azure.management\n ? { management: config.azure.management }\n : { deployments: deploymentIds }),\n })\n : undefined;\n let cachedCatalog: { expiresAt: number; value: SurveyAssistantModelCatalog } | undefined;\n\n const getCatalog = async ({ refresh = false }: { refresh?: boolean } = {}) => {\n if (!refresh && cachedCatalog && cachedCatalog.expiresAt > Date.now()) {\n return cachedCatalog.value;\n }\n let ids = chatModelIds;\n if (azureGateway && config.azure?.discoverModels) {\n try {\n const providers = await azureGateway.fetchProviders();\n const configuredUpstreamIds = new Set(\n chatModelIds.map((id) => getConfiguredModel(id).upstreamModelId),\n );\n const discoveredIds = (providers[\"azure-openai\"]?.models ?? []).filter(\n (id) => !configuredUpstreamIds.has(id),\n );\n ids = [...new Set([...chatModelIds, ...discoveredIds])];\n } catch {\n // Keep the explicit catalog available when Azure management discovery is temporarily down.\n }\n }\n const value = {\n defaultModelId: config.defaultModelId,\n models: ids.map((id) => {\n const configuredModel = getConfiguredModel(id);\n return { id, label: configuredModel.label };\n }),\n } satisfies SurveyAssistantModelCatalog;\n cachedCatalog = { expiresAt: Date.now() + config.modelCatalogTtlMs, value };\n return value;\n };\n const resolveRequestedModel = async (requestedModelId?: string) => {\n const catalog = await getCatalog();\n const id = requestedModelId ?? catalog.defaultModelId;\n return catalog.models.some((model) => model.id === id)\n ? {\n id,\n model: toProviderModel(id, \"requestedModelId\"),\n providerName: config.provider,\n ...(getConfiguredModel(id).providerOptions\n ? { providerOptions: getConfiguredModel(id).providerOptions }\n : {}),\n }\n : null;\n };\n\n return {\n defaultModel,\n gateways: azureGateway\n ? {\n // Mastra 1.47 narrows one method's environment type in the concrete class.\n \"azure-openai\": azureGateway as unknown as MastraModelGatewayInterface,\n }\n : undefined,\n getCatalog,\n memoryModel,\n providerName: config.provider,\n providerOptions: config.execution.providerOptions,\n resolveModel: async ({ requestedModelId }) => resolveRequestedModel(requestedModelId),\n resolveTaskModel: async ({ requestedModelId }) =>\n config.taskModelId\n ? {\n id: config.taskModelId,\n model: taskModel!,\n providerName: config.provider,\n ...(getConfiguredModel(config.taskModelId).providerOptions\n ? { providerOptions: getConfiguredModel(config.taskModelId).providerOptions }\n : {}),\n }\n : resolveRequestedModel(requestedModelId),\n taskModel,\n };\n};\n\nexport interface SurveyAssistantRuntimeComponents {\n agents: Record<\n string,\n | ReturnType<typeof createSurveyAssistantAgent>\n | ReturnType<typeof createSurveyAssistantTaskAgent>\n >;\n gateways?: Record<string, MastraModelGatewayInterface>;\n modelRouter: SurveyAssistantModelRouter;\n}\n\nexport const createSurveyAssistantRuntimeComponents = (\n config: SurveyAssistantRuntimeConfig,\n): SurveyAssistantRuntimeComponents => {\n const modelRouter = createSurveyAssistantModelRouter(config);\n const chatModel: CreateSurveyAssistantAgentOptions[\"model\"] = ({\n requestContext,\n }: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n }) => requestContext.get(\"modelSelection\")?.model ?? modelRouter.defaultModel;\n const taskModel = modelRouter.taskModel ?? chatModel;\n const observationalMemory =\n config.provider === \"lmstudio\" && config.observationalMemory !== false\n ? { ...config.observationalMemory, model: modelRouter.memoryModel }\n : config.observationalMemory;\n return {\n agents: {\n [SURVEY_ASSISTANT_AGENT_ID]: createSurveyAssistantAgent({\n model: chatModel,\n observationalMemory,\n }),\n [SURVEY_ASSISTANT_TASK_AGENT_ID]: createSurveyAssistantTaskAgent({ model: taskModel }),\n },\n gateways: modelRouter.gateways,\n modelRouter,\n };\n};\n\ntype ChatHandlerOverrides = Partial<\n Omit<\n SurveyAssistantChatHandlerOptions,\n \"authorize\" | \"mastra\" | \"providerName\" | \"providerOptions\" | \"resolveModel\"\n >\n>;\ntype TaskHandlerOverrides = Partial<\n Omit<\n CreateSurveyAssistantTaskHandlerOptions,\n \"agent\" | \"authorize\" | \"providerOptions\" | \"resolveModel\"\n >\n>;\n\nexport interface CreateSurveyAssistantRuntimeHandlersOptions {\n authorize: {\n chat: SurveyAssistantAuthorize;\n model?: (request: Request) => unknown | Promise<unknown>;\n task: CreateSurveyAssistantTaskHandlerOptions[\"authorize\"];\n thread: CreateSurveyAssistantThreadHandlersOptions[\"authorize\"];\n };\n chat?: ChatHandlerOverrides;\n config: SurveyAssistantRuntimeConfig;\n mastra: Mastra | (() => Mastra | Promise<Mastra>);\n modelRouter: SurveyAssistantModelRouter;\n task?: TaskHandlerOverrides;\n threadDocuments?: SurveyAssistantThreadDocumentRepository;\n}\n\nexport type CreateConfiguredSurveyAssistantRuntimeHandlersOptions = Omit<\n CreateSurveyAssistantRuntimeHandlersOptions,\n \"config\" | \"modelRouter\"\n>;\n\nconst resolveMastra = async (mastra: Mastra | (() => Mastra | Promise<Mastra>)) =>\n typeof mastra === \"function\" ? mastra() : mastra;\n\nexport const createSurveyAssistantRuntimeHandlers = ({\n authorize,\n chat = {},\n config,\n mastra,\n modelRouter,\n task = {},\n threadDocuments,\n}: CreateSurveyAssistantRuntimeHandlersOptions) => {\n const isEnabled = chat.isEnabled ?? (() => config.enabled);\n const getReadinessError = chat.getReadinessError ?? (() => config.readinessError);\n const chatHandler = createSurveyAssistantChatHandler({\n ...chat,\n mastra,\n agentId: SURVEY_ASSISTANT_AGENT_ID,\n activeTools:\n chat.activeTools ??\n (config.observationalMemory === false\n ? SURVEY_ASSISTANT_TOOL_IDS\n : [...SURVEY_ASSISTANT_TOOL_IDS, \"recall\"]),\n authorize: authorize.chat,\n firstResponseTimeoutMs: chat.firstResponseTimeoutMs ?? config.execution.firstResponseTimeoutMs,\n getReadinessError,\n isEnabled,\n idleTimeoutMs: chat.idleTimeoutMs ?? config.execution.idleTimeoutMs,\n maxConcurrentRequests: chat.maxConcurrentRequests ?? config.execution.maxConcurrentRequests,\n maxDurationMs: chat.maxDurationMs ?? config.execution.maxDurationMs,\n maxSteps: chat.maxSteps ?? config.execution.maxSteps,\n providerName: modelRouter.providerName,\n providerOptions: modelRouter.providerOptions,\n requestLimits: { ...config.requestLimits, ...chat.requestLimits },\n resolveModel: modelRouter.resolveModel,\n sendReasoning: chat.sendReasoning ?? config.execution.sendReasoning,\n threadDocuments,\n });\n const taskHandler = createSurveyAssistantTaskHandler({\n ...task,\n agent: async () => (await resolveMastra(mastra)).getAgent(SURVEY_ASSISTANT_TASK_AGENT_ID),\n authorize: authorize.task,\n getReadinessError: task.getReadinessError ?? getReadinessError,\n isEnabled: task.isEnabled ?? isEnabled,\n maxConcurrentRequests: task.maxConcurrentRequests ?? config.execution.maxConcurrentRequests,\n maxDurationMs: task.maxDurationMs ?? config.execution.maxDurationMs,\n providerOptions: modelRouter.providerOptions,\n resolveModel: modelRouter.resolveTaskModel,\n });\n const getMemory = async () => {\n const memory = await (\n await resolveMastra(mastra)\n )\n .getAgent(SURVEY_ASSISTANT_AGENT_ID)\n .getMemory();\n if (!memory) throw new Error(\"Survey assistant memory is not configured.\");\n return memory;\n };\n const threads = createSurveyAssistantThreadHandlers({\n authorize: async (request) => {\n if (!config.enabled) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant is disabled.\", 404);\n }\n return authorize.thread(request);\n },\n repository: createMastraMemoryThreadRepository({ getMemory, threadDocuments }),\n });\n const models = async (request: Request) => {\n if (!config.enabled) {\n return Response.json(\n { code: \"authorization_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n try {\n if (authorize.model) {\n await authorize.model(request);\n } else {\n await authorize.task({ request });\n }\n return Response.json(await modelRouter.getCatalog());\n } catch (error) {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : 403;\n return Response.json(\n {\n code: \"authorization_failed\",\n error: \"The survey assistant request is not authorized.\",\n },\n { status },\n );\n }\n };\n\n return {\n chat: chatHandler,\n models,\n task: taskHandler,\n threads,\n };\n};\n\nexport interface SurveyAssistantRuntime extends SurveyAssistantRuntimeComponents {\n config: SurveyAssistantRuntimeConfig;\n createHandlers(\n options: CreateConfiguredSurveyAssistantRuntimeHandlersOptions,\n ): ReturnType<typeof createSurveyAssistantRuntimeHandlers>;\n}\n\nexport interface CreateSurveyAssistantRuntimeOptions {\n /** Trusted server-side capabilities for custom registry item types. */\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n}\n\n/**\n * Creates the reusable assistant runtime without hiding Mastra from the host.\n * Register `agents` and `gateways` in the host's standard Mastra instance, then\n * call `createHandlers` with that instance and host authorization policy.\n */\nexport const createSurveyAssistantRuntime = (\n config: SurveyAssistantRuntimeConfig,\n runtimeOptions: CreateSurveyAssistantRuntimeOptions = {},\n): SurveyAssistantRuntime => {\n const components = createSurveyAssistantRuntimeComponents(config);\n return {\n ...components,\n config,\n createHandlers: (handlerOptions) =>\n createSurveyAssistantRuntimeHandlers({\n ...handlerOptions,\n chat: {\n ...handlerOptions.chat,\n trustedCapabilities:\n handlerOptions.chat?.trustedCapabilities ?? runtimeOptions.trustedCapabilities,\n },\n config,\n modelRouter: components.modelRouter,\n }),\n };\n};\n"],"mappings":";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CAAC;CACF,MAAM,SAAS,OAAO,YAAqB;AACzC,MAAI,CAAC,OAAO,QACV,QAAO,SAAS,KACd;GAAE,MAAM;GAAwB,OAAO;GAAiC,EACxE,EAAE,QAAQ,KAAK,CAChB;AAEH,MAAI;AACF,OAAI,UAAU,MACZ,OAAM,UAAU,MAAM,QAAQ;OAE9B,OAAM,UAAU,KAAK,EAAE,SAAS,CAAC;AAEnC,UAAO,SAAS,KAAK,MAAM,YAAY,YAAY,CAAC;WAC7C,OAAO;GACd,MAAM,SACJ,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,OAAO,MAAM,WAAW,WACpB,MAAM,SACN;AACN,UAAO,SAAS,KACd;IACE,MAAM;IACN,OAAO;IACR,EACD,EAAE,QAAQ,CACX;;;AAIL,QAAO;EACL,MAAM;EACN;EACA,MAAM;EACN;EACD;;;;;;;AAoBH,MAAa,gCACX,QACA,iBAAsD,EAAE,KAC7B;CAC3B,MAAM,aAAa,uCAAuC,OAAO;AACjE,QAAO;EACL,GAAG;EACH;EACA,iBAAiB,mBACf,qCAAqC;GACnC,GAAG;GACH,MAAM;IACJ,GAAG,eAAe;IAClB,qBACE,eAAe,MAAM,uBAAuB,eAAe;IAC9D;GACD;GACA,aAAa,WAAW;GACzB,CAAC;EACL"}
@@ -1,2 +1,2 @@
1
- import { a as SurveyAssistantTaskAuthorizationInput, c as createSurveyAssistantTaskAgent, d as runSurveyAssistantSuggestItemLabelTask, f as runSurveyAssistantTask, i as RunSurveyAssistantTaskOptions, l as createSurveyAssistantTaskHandler, n as CreateSurveyAssistantTaskHandlerOptions, o as SurveyAssistantTaskAuthorizedIdentity, p as runSurveyAssistantTranslateContentTask, r as RunSurveyAssistantBuiltInTaskOptions, s as SurveyAssistantTaskModelResolutionInput, t as CreateSurveyAssistantTaskAgentOptions, u as runSurveyAssistantSuggestItemKeyTask } from "./tasks-DIZgr4nD.mjs";
1
+ import { a as SurveyAssistantTaskAuthorizationInput, c as createSurveyAssistantTaskAgent, d as runSurveyAssistantSuggestItemLabelTask, f as runSurveyAssistantTask, i as RunSurveyAssistantTaskOptions, l as createSurveyAssistantTaskHandler, n as CreateSurveyAssistantTaskHandlerOptions, o as SurveyAssistantTaskAuthorizedIdentity, p as runSurveyAssistantTranslateContentTask, r as RunSurveyAssistantBuiltInTaskOptions, s as SurveyAssistantTaskModelResolutionInput, t as CreateSurveyAssistantTaskAgentOptions, u as runSurveyAssistantSuggestItemKeyTask } from "./tasks-BWmTMXoK.mjs";
2
2
  export { CreateSurveyAssistantTaskAgentOptions, CreateSurveyAssistantTaskHandlerOptions, RunSurveyAssistantBuiltInTaskOptions, RunSurveyAssistantTaskOptions, SurveyAssistantTaskAuthorizationInput, SurveyAssistantTaskAuthorizedIdentity, SurveyAssistantTaskModelResolutionInput, createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemKeyTask, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
@@ -1,7 +1,7 @@
1
- import { T as surveyAssistantTaskRequestSchema } from "./protocol-DATvkr1S.mjs";
1
+ import { T as surveyAssistantTaskRequestSchema } from "./protocol-DJUP4gc0.mjs";
2
2
  import { n as SURVEY_ASSISTANT_TASK_AGENT_ID } from "./constants-CFUWrRtl.mjs";
3
3
  import { d as readSurveyAssistantRequestJson, u as SurveyAssistantRequestError } from "./request-guardrails-h4t6u8mP.mjs";
4
- import { i as surveyAuthoringReferences } from "./authoring-references-ChDTVnms.mjs";
4
+ import { i as surveyAuthoringReferences } from "./authoring-references-yyYC4Ydi.mjs";
5
5
  import { n as FAIR_ITEM_KEY_RULES_TEXT } from "./fair-guidance-CEdJYccK.mjs";
6
6
  import { z } from "zod";
7
7
  import { RequestContext } from "@mastra/core/request-context";
@@ -17,7 +17,8 @@ const BASE_TASK_INSTRUCTIONS = [
17
17
  "You perform one bounded CASE Survey Editor AI task and return only the requested structured result.",
18
18
  "The supplied task context was derived from the current canonical survey document snapshot. Use it as current survey context, but do not mutate it and do not claim that any editor change was applied.",
19
19
  "Follow the supplied CASE authoring references where relevant. Do not invent item types, locales, ids, or capabilities that are absent from the task input and context.",
20
- "Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content."
20
+ "Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.",
21
+ "Be fast, don't think."
21
22
  ];
22
23
  const runSurveyAssistantTask = async ({ agent, taskId, input, context, schema, instructions, referenceTopics = [], requestContext, providerOptions, abortSignal }) => {
23
24
  const references = referenceTopics.map((topic) => ({
@@ -266,12 +267,13 @@ const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError,
266
267
  error: readinessError
267
268
  }, { status: 503 });
268
269
  const requestContext = new RequestContext();
270
+ let modelSelection;
269
271
  if (resolveModel) {
270
- const modelSelection = await resolveModel({
272
+ modelSelection = await resolveModel({
271
273
  identity: metricsIdentity,
272
274
  request,
273
275
  requestedModelId: task.modelId
274
- });
276
+ }) ?? void 0;
275
277
  if (!modelSelection) return Response.json({
276
278
  code: "request_failed",
277
279
  error: "The selected survey assistant model is unavailable."
@@ -285,7 +287,7 @@ const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError,
285
287
  context: task.context,
286
288
  mode: task.mode,
287
289
  requestContext,
288
- providerOptions
290
+ providerOptions: modelSelection?.providerOptions ?? providerOptions
289
291
  };
290
292
  const result = task.taskId === "suggest-item-key" ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime) : task.taskId === "suggest-item-label" ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime) : await runSurveyAssistantTranslateContentTask(task.input, runtime);
291
293
  completed = true;
@@ -1 +1 @@
1
- {"version":3,"file":"server-tasks.mjs","names":[],"sources":["../src/server/tasks.ts"],"sourcesContent":["import { Agent, type AgentConfig, type AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport { surveyAssistantTaskRequestSchema } from \"../protocol\";\nimport type {\n SurveyAssistantSuggestItemKeyInput,\n SurveyAssistantSuggestItemKeyResult,\n SurveyAssistantKeySuggestionCategory,\n SurveyAssistantSuggestItemLabelInput,\n SurveyAssistantSuggestItemLabelResult,\n SurveyAssistantTaskInvocationMode,\n SurveyAssistantTaskContext,\n SurveyAssistantTranslateContentInput,\n SurveyAssistantTranslateContentResult,\n} from \"../protocol\";\nimport {\n surveyAuthoringReferences,\n type SurveyAuthoringReferenceTopic,\n} from \"./authoring-references\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport { SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\nimport { FAIR_ITEM_KEY_RULES_TEXT } from \"./fair-guidance\";\nimport { readSurveyAssistantRequestJson, SurveyAssistantRequestError } from \"./request-guardrails\";\n\ntype SurveyAssistantTaskAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n>;\n\nexport interface CreateSurveyAssistantTaskAgentOptions {\n model: SurveyAssistantTaskAgentConfig[\"model\"];\n}\n\nexport const createSurveyAssistantTaskAgent = ({ model }: CreateSurveyAssistantTaskAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_TASK_AGENT_ID,\n name: \"Survey Assistant Tasks\",\n instructions:\n \"Perform the supplied bounded survey-authoring task and return only its requested structured output.\",\n model,\n });\n\nexport interface RunSurveyAssistantTaskOptions<TSchema extends z.ZodType> {\n agent: Pick<Agent, \"generate\">;\n taskId: string;\n input: unknown;\n context: SurveyAssistantTaskContext;\n schema: TSchema;\n instructions: readonly string[];\n referenceTopics?: readonly SurveyAuthoringReferenceTopic[];\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst BASE_TASK_INSTRUCTIONS = [\n \"You perform one bounded CASE Survey Editor AI task and return only the requested structured result.\",\n \"The supplied task context was derived from the current canonical survey document snapshot. Use it as current survey context, but do not mutate it and do not claim that any editor change was applied.\",\n \"Follow the supplied CASE authoring references where relevant. Do not invent item types, locales, ids, or capabilities that are absent from the task input and context.\",\n \"Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.\",\n] as const;\n\nexport const runSurveyAssistantTask = async <TSchema extends z.ZodType>({\n agent,\n taskId,\n input,\n context,\n schema,\n instructions,\n referenceTopics = [],\n requestContext,\n providerOptions,\n abortSignal,\n}: RunSurveyAssistantTaskOptions<TSchema>): Promise<z.output<TSchema>> => {\n const references = referenceTopics.map((topic) => ({\n topic,\n title: surveyAuthoringReferences[topic].title,\n content: surveyAuthoringReferences[topic].content,\n }));\n const response = await agent.generate(\n JSON.stringify({ taskId, input, currentSurveyContext: context }),\n {\n instructions: [\n ...BASE_TASK_INSTRUCTIONS,\n ...instructions,\n ...references.map((entry) => `Reference: ${entry.title}\\n${entry.content}`),\n ],\n activeTools: [],\n inputProcessors: [],\n maxSteps: 1,\n structuredOutput: {\n schema,\n errorStrategy: \"strict\",\n },\n ...(requestContext ? { requestContext } : {}),\n ...(providerOptions ? { providerOptions } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n },\n );\n\n return schema.parse(response.object);\n};\n\nconst keySuggestionValueSchema = z.object({\n text: z.string().min(1),\n rationale: z.string().optional(),\n});\n\nconst keySuggestionCategorySchema = z.enum([\"survey-pattern\", \"compact\", \"preferred\", \"fair\"]);\n\nconst keySuggestionSchema = z.object({\n surveyPattern: keySuggestionValueSchema.describe(\n \"A key that follows the strongest naming and numbering pattern in the current survey.\",\n ),\n compact: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(2)\n .max(5)\n .regex(/^[A-Z][A-Z0-9]{1,4}$/)\n .describe(\"A recognizable 2-5 character uppercase abbreviation.\"),\n }),\n preferred: keySuggestionValueSchema.describe(\n \"The key the model considers clearest without a category-specific naming constraint.\",\n ),\n fair: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(1)\n .max(32)\n .regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/)\n .describe(\"A FAIR-by-design lowercase snake_case variable name.\"),\n }),\n alternatives: z\n .array(\n keySuggestionValueSchema.extend({\n category: keySuggestionCategorySchema,\n }),\n )\n .max(2),\n});\n\nconst labelSuggestionSchema = z.object({\n suggestions: z.array(\n z.object({\n text: z.string().min(1),\n }),\n ),\n});\n\nconst translationsSchema = z.object({\n translations: z.record(z.string(), z.record(z.string(), z.string())),\n});\n\nexport interface RunSurveyAssistantBuiltInTaskOptions {\n agent: Pick<Agent, \"generate\">;\n context: SurveyAssistantTaskContext;\n mode?: SurveyAssistantTaskInvocationMode;\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst clampLimit = (value: number | undefined, fallback: number, maximum: number) =>\n Math.min(Math.max(1, value ?? fallback), maximum);\n\nconst sanitizeCodingKey = (value: string) =>\n value\n .trim()\n .replace(/[.\\s-]+/g, \"_\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst getCodingKeyIdentity = (value: string) => sanitizeCodingKey(value).toLocaleLowerCase();\n\nconst getNumberedKeyParts = (value: string) => {\n const match = /^(.+?)_(\\d+)$/.exec(getCodingKeyIdentity(value));\n return match ? { stem: match[1], number: Number(match[2]) } : undefined;\n};\n\nconst isUnsupportedFocusedItemSequence = (\n candidate: string,\n input: SurveyAssistantSuggestItemKeyInput,\n context: SurveyAssistantTaskContext,\n) => {\n const candidateParts = getNumberedKeyParts(candidate);\n const focusItem = context.focus?.item;\n if (!candidateParts || !focusItem) return false;\n\n const focusedKeyParts = [input.currentKey, input.draftKey, focusItem.key]\n .map(getNumberedKeyParts)\n .find((parts) => parts?.stem === candidateParts.stem && parts.number < candidateParts.number);\n if (!focusedKeyParts) return false;\n\n return !context.naming?.keyExamples.some((example) => {\n const exampleParts = getNumberedKeyParts(example.key);\n return example.itemType === focusItem.itemType && exampleParts?.stem === candidateParts.stem;\n });\n};\n\nconst invocationInstruction = (mode: SurveyAssistantTaskInvocationMode | undefined) =>\n mode === \"background\"\n ? \"This is a background invocation. Be efficient, but do not relax task conventions, completeness, or output quality.\"\n : \"This is an explicit user invocation. Prioritize quality and useful variation.\";\n\nexport const runSurveyAssistantSuggestItemKeyTask = async (\n input: SurveyAssistantSuggestItemKeyInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemKeyResult> => {\n const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-key\",\n input,\n schema: keySuggestionSchema,\n instructions: [\n \"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.\",\n \"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.\",\n \"For a group or other container, treat its own descendants as the primary evidence for what the container represents. Derive a descriptive group key from those children before considering generic default container names.\",\n \"The input currentKey and draftKey, plus the focused item's key and fullKey in currentSurveyContext, identify the value being replaced. They may provide topic hints, but they are not evidence of an established naming or numbering pattern.\",\n \"Use only currentSurveyContext.naming.keyExamples and sibling keys from other items to infer the survey's established naming pattern. Pay particular attention to prefixes, casing, separators, numeric sequences, and zero padding.\",\n \"Treat a numeric pattern as established only when at least one other survey item supports it. For example, another item Q1_APPLES can support a topic-appropriate Q2_... key, while Q1_APPLES and Q2_ORANGES support Q3_.... The focused item's current key choice_1 by itself does not support choice_2 or a numeric suffix in other suggestions.\",\n \"In particular, a focused group named group_1 is a default placeholder, not a group-numbering pattern. Do not propose group_2 (or another group_N key) from it unless another group/container in currentSurveyContext.naming.keyExamples independently uses the same group_N pattern. The group's children provide semantic context, not evidence of a group-numbering pattern.\",\n \"Return one surveyPattern key that follows the strongest detected local pattern. Preserve that pattern's casing and increment a clear sequence rather than copying an existing number. If no meaningful pattern exists, use a consistent descriptive key.\",\n \"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.\",\n \"Return one preferred key: the key you consider clearest and most useful without category-specific naming constraints, while still using only letters, digits, and underscores.\",\n `Return one fair key following these FAIR-by-design rules: ${FAIR_ITEM_KEY_RULES_TEXT}. Meaning belongs in metadata, so do not turn it into a sentence.`,\n `You may return up to ${Math.max(0, maxSuggestions - 4)} genuinely useful alternatives when another category has more than one strong candidate. Tag each alternative with its category.`,\n \"Never repeat the same suggestion, including case-only or punctuation-only variations.\",\n \"Do not return the current key, a sibling key, or a semantically unrelated abbreviation.\",\n `Return between 4 and ${maxSuggestions} distinct suggestions in total.`,\n invocationInstruction(options.mode),\n ],\n });\n\n const excluded = new Set(\n [input.currentKey, ...input.siblingKeys].map(getCodingKeyIdentity).filter(Boolean),\n );\n const seen = new Set<string>();\n const categorizedSuggestions: Array<{\n text: string;\n rationale?: string;\n category: SurveyAssistantKeySuggestionCategory;\n }> = [\n { ...result.surveyPattern, category: \"survey-pattern\" },\n { ...result.compact, category: \"compact\" },\n { ...result.preferred, category: \"preferred\" },\n { ...result.fair, category: \"fair\" },\n ...result.alternatives,\n ];\n const suggestions = categorizedSuggestions\n .flatMap((suggestion) => {\n const text = sanitizeCodingKey(suggestion.text);\n const identity = getCodingKeyIdentity(text);\n if (\n !text ||\n excluded.has(identity) ||\n seen.has(identity) ||\n isUnsupportedFocusedItemSequence(text, input, options.context)\n ) {\n return [];\n }\n seen.add(identity);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions);\n return { suggestions };\n};\n\nexport const runSurveyAssistantSuggestItemLabelTask = async (\n input: SurveyAssistantSuggestItemLabelInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemLabelResult> => {\n const maxSuggestions = clampLimit(input.maxSuggestions, 3, 10);\n const locale = input.locale ?? options.context.survey.selectedLocale;\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-label\",\n input,\n schema: labelSuggestionSchema,\n instructions: [\n \"Suggest concise editor-only item labels, not coding keys and not respondent-facing question text.\",\n \"Infer the item's purpose from its type, draft label, visible content, hierarchy, siblings, and descendants.\",\n \"Use currentSurveyContext.naming.labelExamples to infer established capitalization, prefixes, abbreviations, delimiters, and typical length.\",\n \"If existing label examples are available, the first suggestion must follow their dominant pattern while still describing the focused item accurately. Other suggestions may offer useful concise alternatives.\",\n \"Do not copy the subject matter of an unrelated example merely to imitate its style, and do not return an existing unrelated label verbatim.\",\n `Write labels in locale ${locale}.`,\n `Return at most ${maxSuggestions} distinct, specific, human-readable suggestions.`,\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"core-rules\"],\n });\n\n const normalizeLabel = (value: string) => value.trim().toLocaleLowerCase();\n const excludedLabels = new Set([\n normalizeLabel(input.draftLabel),\n ...(options.context.naming?.labelExamples ?? []).map((example) =>\n normalizeLabel(example.label),\n ),\n ]);\n const seen = new Set<string>();\n return {\n suggestions: result.suggestions\n .flatMap((suggestion) => {\n const text = suggestion.text.trim();\n const normalizedText = normalizeLabel(text);\n if (!text || excludedLabels.has(normalizedText) || seen.has(normalizedText)) return [];\n seen.add(normalizedText);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions),\n };\n};\n\nconst getProtectedTokens = (value: string) =>\n value.match(/\\{\\{[^{}]+\\}\\}|\\{[^{}]+\\}|\\$\\{[^{}]+\\}|%\\d*\\$?[a-z]/gi) ?? [];\n\nexport const runSurveyAssistantTranslateContentTask = async (\n input: SurveyAssistantTranslateContentInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantTranslateContentResult> => {\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"translate-content\",\n input,\n schema: translationsSchema,\n instructions: [\n \"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.\",\n `Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(\", \")}.`,\n \"Use currentSurveyContext.translation.examples as a terminology and style reference when relevant. The supplied source entries remain authoritative.\",\n \"Preserve meaning, register, survey terminology, punctuation, line breaks, response semantics, placeholders, interpolation tokens, URLs, and identifiers that should not be translated.\",\n \"Keep repeated terminology consistent across all entries and target locales. Do not use a neighboring translation when its meaning differs.\",\n \"Return plain strings keyed first by target locale and then by the original entry id. Return every requested locale and entry exactly once.\",\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"localization\"],\n });\n\n const translations: SurveyAssistantTranslateContentResult[\"translations\"] = {};\n for (const locale of input.targetLocales) {\n const entries = result.translations[locale];\n if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);\n const translatedEntries: Record<string, string> = {};\n for (const entry of input.entries) {\n const translation = entries[entry.id];\n if (typeof translation !== \"string\" || translation.trim().length === 0) {\n throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);\n }\n const sourceTokens = getProtectedTokens(entry.text).sort();\n const translatedTokens = getProtectedTokens(translation).sort();\n if (sourceTokens.join(\"\\u0000\") !== translatedTokens.join(\"\\u0000\")) {\n throw new Error(\n `Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`,\n );\n }\n translatedEntries[entry.id] = translation;\n }\n translations[locale] = translatedEntries;\n }\n return { translations };\n};\n\nconst MAX_TASK_REQUEST_BYTES = 512 * 1024;\nconst DEFAULT_MAX_TASK_CONCURRENT_REQUESTS = 4;\nconst DEFAULT_MAX_TASK_DURATION_MS = 60_000;\n\nexport interface SurveyAssistantTaskAuthorizedIdentity {\n resourceId: string;\n surveyId?: string;\n}\n\nexport interface SurveyAssistantTaskAuthorizationInput {\n request: Request;\n requestedResourceId?: string;\n requestedSurveyId?: string;\n}\n\nexport interface SurveyAssistantTaskModelResolutionInput {\n identity: SurveyAssistantTaskAuthorizedIdentity;\n request: Request;\n requestedModelId?: string;\n}\n\nexport interface CreateSurveyAssistantTaskHandlerOptions {\n agent:\n | Pick<Agent, \"generate\">\n | (() => Pick<Agent, \"generate\"> | Promise<Pick<Agent, \"generate\">>);\n authorize(\n input: SurveyAssistantTaskAuthorizationInput,\n ): SurveyAssistantTaskAuthorizedIdentity | Promise<SurveyAssistantTaskAuthorizedIdentity>;\n getReadinessError?(request: Request): string | null | Promise<string | null>;\n isEnabled?(request: Request): boolean | Promise<boolean>;\n maxConcurrentRequests?: number;\n maxDurationMs?: number;\n onTaskMetrics?(input: {\n durationMs: number;\n identity: SurveyAssistantTaskAuthorizedIdentity;\n status: \"completed\" | \"failed\";\n taskId: string;\n }): void;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel?(\n input: SurveyAssistantTaskModelResolutionInput,\n ):\n | SurveyAssistantModelSelection\n | null\n | undefined\n | Promise<SurveyAssistantModelSelection | null | undefined>;\n}\n\nconst taskErrorResponse = (error: unknown) => {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : error instanceof SyntaxError || (error instanceof Error && error.name === \"ZodError\")\n ? 400\n : 500;\n const message =\n error instanceof SurveyAssistantRequestError\n ? error.message\n : status === 401 || status === 403 || status === 404\n ? status === 404\n ? \"Survey assistant task not found.\"\n : \"The survey assistant task is not authorized.\"\n : status >= 500\n ? \"The survey assistant task could not be completed.\"\n : \"The survey assistant task request is invalid.\";\n return Response.json(\n {\n code:\n status === 401 || status === 403 || status === 404\n ? \"authorization_failed\"\n : \"request_failed\",\n error: message,\n },\n { status },\n );\n};\n\nexport const createSurveyAssistantTaskHandler = ({\n agent,\n authorize,\n getReadinessError,\n isEnabled,\n maxConcurrentRequests = DEFAULT_MAX_TASK_CONCURRENT_REQUESTS,\n maxDurationMs = DEFAULT_MAX_TASK_DURATION_MS,\n onTaskMetrics,\n providerOptions,\n resolveModel,\n}: CreateSurveyAssistantTaskHandlerOptions) => {\n const concurrency =\n Number.isInteger(maxConcurrentRequests) && maxConcurrentRequests > 0\n ? maxConcurrentRequests\n : DEFAULT_MAX_TASK_CONCURRENT_REQUESTS;\n const duration =\n Number.isFinite(maxDurationMs) && maxDurationMs > 0\n ? maxDurationMs\n : DEFAULT_MAX_TASK_DURATION_MS;\n let activeRequests = 0;\n\n return async (request: Request): Promise<Response> => {\n if (activeRequests >= concurrency) {\n return Response.json(\n {\n code: \"rate_limited\",\n error: \"The survey assistant is handling too many tasks. Try again shortly.\",\n },\n { status: 429 },\n );\n }\n activeRequests += 1;\n const startedAt = Date.now();\n let metricsIdentity: SurveyAssistantTaskAuthorizedIdentity | undefined;\n let metricsTaskId = \"unknown\";\n let completed = false;\n try {\n if (isEnabled && !(await isEnabled(request))) {\n return Response.json(\n { code: \"request_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n const task = surveyAssistantTaskRequestSchema.parse(\n await readSurveyAssistantRequestJson(request, MAX_TASK_REQUEST_BYTES),\n );\n metricsTaskId = task.taskId;\n const identity = await authorize({\n request,\n requestedResourceId: task.resourceId,\n requestedSurveyId: task.surveyId,\n });\n if (\n !identity?.resourceId?.trim() ||\n identity.resourceId.trim().length > 240 ||\n (identity.surveyId !== undefined &&\n (!identity.surveyId.trim() || identity.surveyId.trim().length > 240))\n ) {\n throw Object.assign(new Error(\"The host returned an invalid task identity.\"), {\n status: 500,\n });\n }\n metricsIdentity = {\n resourceId: identity.resourceId.trim(),\n ...(identity.surveyId?.trim() ? { surveyId: identity.surveyId.trim() } : {}),\n };\n\n const readinessError = await getReadinessError?.(request);\n if (readinessError) {\n return Response.json({ code: \"request_failed\", error: readinessError }, { status: 503 });\n }\n\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n if (resolveModel) {\n const modelSelection = await resolveModel({\n identity: metricsIdentity,\n request,\n requestedModelId: task.modelId,\n });\n if (!modelSelection) {\n return Response.json(\n {\n code: \"request_failed\",\n error: \"The selected survey assistant model is unavailable.\",\n },\n { status: 400 },\n );\n }\n requestContext.set(\"modelSelection\", modelSelection);\n }\n\n const resolvedAgent = typeof agent === \"function\" ? await agent() : agent;\n const runtime: RunSurveyAssistantBuiltInTaskOptions = {\n abortSignal: AbortSignal.any([request.signal, AbortSignal.timeout(duration)]),\n agent: resolvedAgent,\n context: task.context,\n mode: task.mode,\n requestContext,\n providerOptions,\n };\n const result =\n task.taskId === \"suggest-item-key\"\n ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime)\n : task.taskId === \"suggest-item-label\"\n ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime)\n : await runSurveyAssistantTranslateContentTask(task.input, runtime);\n completed = true;\n return Response.json(result);\n } catch (error) {\n return taskErrorResponse(error);\n } finally {\n activeRequests = Math.max(0, activeRequests - 1);\n if (metricsIdentity) {\n try {\n onTaskMetrics?.({\n durationMs: Date.now() - startedAt,\n identity: metricsIdentity,\n status: completed ? \"completed\" : \"failed\",\n taskId: metricsTaskId,\n });\n } catch {\n // Host metrics must not change the task response.\n }\n }\n }\n };\n};\n"],"mappings":";;;;;;;;;AAsCA,MAAa,kCAAkC,EAAE,YAC/C,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cACE;CACF;CACD,CAAC;AAeJ,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD;AAED,MAAa,yBAAyB,OAAkC,EACtE,OACA,QACA,OACA,SACA,QACA,cACA,kBAAkB,EAAE,EACpB,gBACA,iBACA,kBACwE;CACxE,MAAM,aAAa,gBAAgB,KAAK,WAAW;EACjD;EACA,OAAO,0BAA0B,OAAO;EACxC,SAAS,0BAA0B,OAAO;EAC3C,EAAE;CACH,MAAM,WAAW,MAAM,MAAM,SAC3B,KAAK,UAAU;EAAE;EAAQ;EAAO,sBAAsB;EAAS,CAAC,EAChE;EACE,cAAc;GACZ,GAAG;GACH,GAAG;GACH,GAAG,WAAW,KAAK,UAAU,cAAc,MAAM,MAAM,IAAI,MAAM,UAAU;GAC5E;EACD,aAAa,EAAE;EACf,iBAAiB,EAAE;EACnB,UAAU;EACV,kBAAkB;GAChB;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IACX;IACA;IACD;GACD,MAAM,SACJ,KAAK,WAAW,qBACZ,MAAM,qCAAqC,KAAK,OAAO,QAAQ,GAC/D,KAAK,WAAW,uBACd,MAAM,uCAAuC,KAAK,OAAO,QAAQ,GACjE,MAAM,uCAAuC,KAAK,OAAO,QAAQ;AACzE,eAAY;AACZ,UAAO,SAAS,KAAK,OAAO;WACrB,OAAO;AACd,UAAO,kBAAkB,MAAM;YACvB;AACR,oBAAiB,KAAK,IAAI,GAAG,iBAAiB,EAAE;AAChD,OAAI,gBACF,KAAI;AACF,oBAAgB;KACd,YAAY,KAAK,KAAK,GAAG;KACzB,UAAU;KACV,QAAQ,YAAY,cAAc;KAClC,QAAQ;KACT,CAAC;WACI"}
1
+ {"version":3,"file":"server-tasks.mjs","names":[],"sources":["../src/server/tasks.ts"],"sourcesContent":["import { Agent, type AgentConfig, type AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport { surveyAssistantTaskRequestSchema } from \"../protocol\";\nimport type {\n SurveyAssistantSuggestItemKeyInput,\n SurveyAssistantSuggestItemKeyResult,\n SurveyAssistantKeySuggestionCategory,\n SurveyAssistantSuggestItemLabelInput,\n SurveyAssistantSuggestItemLabelResult,\n SurveyAssistantTaskInvocationMode,\n SurveyAssistantTaskContext,\n SurveyAssistantTranslateContentInput,\n SurveyAssistantTranslateContentResult,\n} from \"../protocol\";\nimport {\n surveyAuthoringReferences,\n type SurveyAuthoringReferenceTopic,\n} from \"./authoring-references\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport { SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\nimport { FAIR_ITEM_KEY_RULES_TEXT } from \"./fair-guidance\";\nimport { readSurveyAssistantRequestJson, SurveyAssistantRequestError } from \"./request-guardrails\";\n\ntype SurveyAssistantTaskAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n>;\n\nexport interface CreateSurveyAssistantTaskAgentOptions {\n model: SurveyAssistantTaskAgentConfig[\"model\"];\n}\n\nexport const createSurveyAssistantTaskAgent = ({ model }: CreateSurveyAssistantTaskAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_TASK_AGENT_ID,\n name: \"Survey Assistant Tasks\",\n instructions:\n \"Perform the supplied bounded survey-authoring task and return only its requested structured output.\",\n model,\n });\n\nexport interface RunSurveyAssistantTaskOptions<TSchema extends z.ZodType> {\n agent: Pick<Agent, \"generate\">;\n taskId: string;\n input: unknown;\n context: SurveyAssistantTaskContext;\n schema: TSchema;\n instructions: readonly string[];\n referenceTopics?: readonly SurveyAuthoringReferenceTopic[];\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst BASE_TASK_INSTRUCTIONS = [\n \"You perform one bounded CASE Survey Editor AI task and return only the requested structured result.\",\n \"The supplied task context was derived from the current canonical survey document snapshot. Use it as current survey context, but do not mutate it and do not claim that any editor change was applied.\",\n \"Follow the supplied CASE authoring references where relevant. Do not invent item types, locales, ids, or capabilities that are absent from the task input and context.\",\n \"Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.\",\n \"Be fast, don't think.\",\n] as const;\n\nexport const runSurveyAssistantTask = async <TSchema extends z.ZodType>({\n agent,\n taskId,\n input,\n context,\n schema,\n instructions,\n referenceTopics = [],\n requestContext,\n providerOptions,\n abortSignal,\n}: RunSurveyAssistantTaskOptions<TSchema>): Promise<z.output<TSchema>> => {\n const references = referenceTopics.map((topic) => ({\n topic,\n title: surveyAuthoringReferences[topic].title,\n content: surveyAuthoringReferences[topic].content,\n }));\n const response = await agent.generate(\n JSON.stringify({ taskId, input, currentSurveyContext: context }),\n {\n instructions: [\n ...BASE_TASK_INSTRUCTIONS,\n ...instructions,\n ...references.map((entry) => `Reference: ${entry.title}\\n${entry.content}`),\n ],\n activeTools: [],\n inputProcessors: [],\n maxSteps: 1,\n structuredOutput: {\n schema,\n errorStrategy: \"strict\",\n },\n ...(requestContext ? { requestContext } : {}),\n ...(providerOptions ? { providerOptions } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n },\n );\n\n return schema.parse(response.object);\n};\n\nconst keySuggestionValueSchema = z.object({\n text: z.string().min(1),\n rationale: z.string().optional(),\n});\n\nconst keySuggestionCategorySchema = z.enum([\"survey-pattern\", \"compact\", \"preferred\", \"fair\"]);\n\nconst keySuggestionSchema = z.object({\n surveyPattern: keySuggestionValueSchema.describe(\n \"A key that follows the strongest naming and numbering pattern in the current survey.\",\n ),\n compact: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(2)\n .max(5)\n .regex(/^[A-Z][A-Z0-9]{1,4}$/)\n .describe(\"A recognizable 2-5 character uppercase abbreviation.\"),\n }),\n preferred: keySuggestionValueSchema.describe(\n \"The key the model considers clearest without a category-specific naming constraint.\",\n ),\n fair: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(1)\n .max(32)\n .regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/)\n .describe(\"A FAIR-by-design lowercase snake_case variable name.\"),\n }),\n alternatives: z\n .array(\n keySuggestionValueSchema.extend({\n category: keySuggestionCategorySchema,\n }),\n )\n .max(2),\n});\n\nconst labelSuggestionSchema = z.object({\n suggestions: z.array(\n z.object({\n text: z.string().min(1),\n }),\n ),\n});\n\nconst translationsSchema = z.object({\n translations: z.record(z.string(), z.record(z.string(), z.string())),\n});\n\nexport interface RunSurveyAssistantBuiltInTaskOptions {\n agent: Pick<Agent, \"generate\">;\n context: SurveyAssistantTaskContext;\n mode?: SurveyAssistantTaskInvocationMode;\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst clampLimit = (value: number | undefined, fallback: number, maximum: number) =>\n Math.min(Math.max(1, value ?? fallback), maximum);\n\nconst sanitizeCodingKey = (value: string) =>\n value\n .trim()\n .replace(/[.\\s-]+/g, \"_\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst getCodingKeyIdentity = (value: string) => sanitizeCodingKey(value).toLocaleLowerCase();\n\nconst getNumberedKeyParts = (value: string) => {\n const match = /^(.+?)_(\\d+)$/.exec(getCodingKeyIdentity(value));\n return match ? { stem: match[1], number: Number(match[2]) } : undefined;\n};\n\nconst isUnsupportedFocusedItemSequence = (\n candidate: string,\n input: SurveyAssistantSuggestItemKeyInput,\n context: SurveyAssistantTaskContext,\n) => {\n const candidateParts = getNumberedKeyParts(candidate);\n const focusItem = context.focus?.item;\n if (!candidateParts || !focusItem) return false;\n\n const focusedKeyParts = [input.currentKey, input.draftKey, focusItem.key]\n .map(getNumberedKeyParts)\n .find((parts) => parts?.stem === candidateParts.stem && parts.number < candidateParts.number);\n if (!focusedKeyParts) return false;\n\n return !context.naming?.keyExamples.some((example) => {\n const exampleParts = getNumberedKeyParts(example.key);\n return example.itemType === focusItem.itemType && exampleParts?.stem === candidateParts.stem;\n });\n};\n\nconst invocationInstruction = (mode: SurveyAssistantTaskInvocationMode | undefined) =>\n mode === \"background\"\n ? \"This is a background invocation. Be efficient, but do not relax task conventions, completeness, or output quality.\"\n : \"This is an explicit user invocation. Prioritize quality and useful variation.\";\n\nexport const runSurveyAssistantSuggestItemKeyTask = async (\n input: SurveyAssistantSuggestItemKeyInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemKeyResult> => {\n const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-key\",\n input,\n schema: keySuggestionSchema,\n instructions: [\n \"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.\",\n \"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.\",\n \"For a group or other container, treat its own descendants as the primary evidence for what the container represents. Derive a descriptive group key from those children before considering generic default container names.\",\n \"The input currentKey and draftKey, plus the focused item's key and fullKey in currentSurveyContext, identify the value being replaced. They may provide topic hints, but they are not evidence of an established naming or numbering pattern.\",\n \"Use only currentSurveyContext.naming.keyExamples and sibling keys from other items to infer the survey's established naming pattern. Pay particular attention to prefixes, casing, separators, numeric sequences, and zero padding.\",\n \"Treat a numeric pattern as established only when at least one other survey item supports it. For example, another item Q1_APPLES can support a topic-appropriate Q2_... key, while Q1_APPLES and Q2_ORANGES support Q3_.... The focused item's current key choice_1 by itself does not support choice_2 or a numeric suffix in other suggestions.\",\n \"In particular, a focused group named group_1 is a default placeholder, not a group-numbering pattern. Do not propose group_2 (or another group_N key) from it unless another group/container in currentSurveyContext.naming.keyExamples independently uses the same group_N pattern. The group's children provide semantic context, not evidence of a group-numbering pattern.\",\n \"Return one surveyPattern key that follows the strongest detected local pattern. Preserve that pattern's casing and increment a clear sequence rather than copying an existing number. If no meaningful pattern exists, use a consistent descriptive key.\",\n \"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.\",\n \"Return one preferred key: the key you consider clearest and most useful without category-specific naming constraints, while still using only letters, digits, and underscores.\",\n `Return one fair key following these FAIR-by-design rules: ${FAIR_ITEM_KEY_RULES_TEXT}. Meaning belongs in metadata, so do not turn it into a sentence.`,\n `You may return up to ${Math.max(0, maxSuggestions - 4)} genuinely useful alternatives when another category has more than one strong candidate. Tag each alternative with its category.`,\n \"Never repeat the same suggestion, including case-only or punctuation-only variations.\",\n \"Do not return the current key, a sibling key, or a semantically unrelated abbreviation.\",\n `Return between 4 and ${maxSuggestions} distinct suggestions in total.`,\n invocationInstruction(options.mode),\n ],\n });\n\n const excluded = new Set(\n [input.currentKey, ...input.siblingKeys].map(getCodingKeyIdentity).filter(Boolean),\n );\n const seen = new Set<string>();\n const categorizedSuggestions: Array<{\n text: string;\n rationale?: string;\n category: SurveyAssistantKeySuggestionCategory;\n }> = [\n { ...result.surveyPattern, category: \"survey-pattern\" },\n { ...result.compact, category: \"compact\" },\n { ...result.preferred, category: \"preferred\" },\n { ...result.fair, category: \"fair\" },\n ...result.alternatives,\n ];\n const suggestions = categorizedSuggestions\n .flatMap((suggestion) => {\n const text = sanitizeCodingKey(suggestion.text);\n const identity = getCodingKeyIdentity(text);\n if (\n !text ||\n excluded.has(identity) ||\n seen.has(identity) ||\n isUnsupportedFocusedItemSequence(text, input, options.context)\n ) {\n return [];\n }\n seen.add(identity);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions);\n return { suggestions };\n};\n\nexport const runSurveyAssistantSuggestItemLabelTask = async (\n input: SurveyAssistantSuggestItemLabelInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemLabelResult> => {\n const maxSuggestions = clampLimit(input.maxSuggestions, 3, 10);\n const locale = input.locale ?? options.context.survey.selectedLocale;\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-label\",\n input,\n schema: labelSuggestionSchema,\n instructions: [\n \"Suggest concise editor-only item labels, not coding keys and not respondent-facing question text.\",\n \"Infer the item's purpose from its type, draft label, visible content, hierarchy, siblings, and descendants.\",\n \"Use currentSurveyContext.naming.labelExamples to infer established capitalization, prefixes, abbreviations, delimiters, and typical length.\",\n \"If existing label examples are available, the first suggestion must follow their dominant pattern while still describing the focused item accurately. Other suggestions may offer useful concise alternatives.\",\n \"Do not copy the subject matter of an unrelated example merely to imitate its style, and do not return an existing unrelated label verbatim.\",\n `Write labels in locale ${locale}.`,\n `Return at most ${maxSuggestions} distinct, specific, human-readable suggestions.`,\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"core-rules\"],\n });\n\n const normalizeLabel = (value: string) => value.trim().toLocaleLowerCase();\n const excludedLabels = new Set([\n normalizeLabel(input.draftLabel),\n ...(options.context.naming?.labelExamples ?? []).map((example) =>\n normalizeLabel(example.label),\n ),\n ]);\n const seen = new Set<string>();\n return {\n suggestions: result.suggestions\n .flatMap((suggestion) => {\n const text = suggestion.text.trim();\n const normalizedText = normalizeLabel(text);\n if (!text || excludedLabels.has(normalizedText) || seen.has(normalizedText)) return [];\n seen.add(normalizedText);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions),\n };\n};\n\nconst getProtectedTokens = (value: string) =>\n value.match(/\\{\\{[^{}]+\\}\\}|\\{[^{}]+\\}|\\$\\{[^{}]+\\}|%\\d*\\$?[a-z]/gi) ?? [];\n\nexport const runSurveyAssistantTranslateContentTask = async (\n input: SurveyAssistantTranslateContentInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantTranslateContentResult> => {\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"translate-content\",\n input,\n schema: translationsSchema,\n instructions: [\n \"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.\",\n `Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(\", \")}.`,\n \"Use currentSurveyContext.translation.examples as a terminology and style reference when relevant. The supplied source entries remain authoritative.\",\n \"Preserve meaning, register, survey terminology, punctuation, line breaks, response semantics, placeholders, interpolation tokens, URLs, and identifiers that should not be translated.\",\n \"Keep repeated terminology consistent across all entries and target locales. Do not use a neighboring translation when its meaning differs.\",\n \"Return plain strings keyed first by target locale and then by the original entry id. Return every requested locale and entry exactly once.\",\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"localization\"],\n });\n\n const translations: SurveyAssistantTranslateContentResult[\"translations\"] = {};\n for (const locale of input.targetLocales) {\n const entries = result.translations[locale];\n if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);\n const translatedEntries: Record<string, string> = {};\n for (const entry of input.entries) {\n const translation = entries[entry.id];\n if (typeof translation !== \"string\" || translation.trim().length === 0) {\n throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);\n }\n const sourceTokens = getProtectedTokens(entry.text).sort();\n const translatedTokens = getProtectedTokens(translation).sort();\n if (sourceTokens.join(\"\\u0000\") !== translatedTokens.join(\"\\u0000\")) {\n throw new Error(\n `Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`,\n );\n }\n translatedEntries[entry.id] = translation;\n }\n translations[locale] = translatedEntries;\n }\n return { translations };\n};\n\nconst MAX_TASK_REQUEST_BYTES = 512 * 1024;\nconst DEFAULT_MAX_TASK_CONCURRENT_REQUESTS = 4;\nconst DEFAULT_MAX_TASK_DURATION_MS = 60_000;\n\nexport interface SurveyAssistantTaskAuthorizedIdentity {\n resourceId: string;\n surveyId?: string;\n}\n\nexport interface SurveyAssistantTaskAuthorizationInput {\n request: Request;\n requestedResourceId?: string;\n requestedSurveyId?: string;\n}\n\nexport interface SurveyAssistantTaskModelResolutionInput {\n identity: SurveyAssistantTaskAuthorizedIdentity;\n request: Request;\n requestedModelId?: string;\n}\n\nexport interface CreateSurveyAssistantTaskHandlerOptions {\n agent:\n | Pick<Agent, \"generate\">\n | (() => Pick<Agent, \"generate\"> | Promise<Pick<Agent, \"generate\">>);\n authorize(\n input: SurveyAssistantTaskAuthorizationInput,\n ): SurveyAssistantTaskAuthorizedIdentity | Promise<SurveyAssistantTaskAuthorizedIdentity>;\n getReadinessError?(request: Request): string | null | Promise<string | null>;\n isEnabled?(request: Request): boolean | Promise<boolean>;\n maxConcurrentRequests?: number;\n maxDurationMs?: number;\n onTaskMetrics?(input: {\n durationMs: number;\n identity: SurveyAssistantTaskAuthorizedIdentity;\n status: \"completed\" | \"failed\";\n taskId: string;\n }): void;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel?(\n input: SurveyAssistantTaskModelResolutionInput,\n ):\n | SurveyAssistantModelSelection\n | null\n | undefined\n | Promise<SurveyAssistantModelSelection | null | undefined>;\n}\n\nconst taskErrorResponse = (error: unknown) => {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : error instanceof SyntaxError || (error instanceof Error && error.name === \"ZodError\")\n ? 400\n : 500;\n const message =\n error instanceof SurveyAssistantRequestError\n ? error.message\n : status === 401 || status === 403 || status === 404\n ? status === 404\n ? \"Survey assistant task not found.\"\n : \"The survey assistant task is not authorized.\"\n : status >= 500\n ? \"The survey assistant task could not be completed.\"\n : \"The survey assistant task request is invalid.\";\n return Response.json(\n {\n code:\n status === 401 || status === 403 || status === 404\n ? \"authorization_failed\"\n : \"request_failed\",\n error: message,\n },\n { status },\n );\n};\n\nexport const createSurveyAssistantTaskHandler = ({\n agent,\n authorize,\n getReadinessError,\n isEnabled,\n maxConcurrentRequests = DEFAULT_MAX_TASK_CONCURRENT_REQUESTS,\n maxDurationMs = DEFAULT_MAX_TASK_DURATION_MS,\n onTaskMetrics,\n providerOptions,\n resolveModel,\n}: CreateSurveyAssistantTaskHandlerOptions) => {\n const concurrency =\n Number.isInteger(maxConcurrentRequests) && maxConcurrentRequests > 0\n ? maxConcurrentRequests\n : DEFAULT_MAX_TASK_CONCURRENT_REQUESTS;\n const duration =\n Number.isFinite(maxDurationMs) && maxDurationMs > 0\n ? maxDurationMs\n : DEFAULT_MAX_TASK_DURATION_MS;\n let activeRequests = 0;\n\n return async (request: Request): Promise<Response> => {\n if (activeRequests >= concurrency) {\n return Response.json(\n {\n code: \"rate_limited\",\n error: \"The survey assistant is handling too many tasks. Try again shortly.\",\n },\n { status: 429 },\n );\n }\n activeRequests += 1;\n const startedAt = Date.now();\n let metricsIdentity: SurveyAssistantTaskAuthorizedIdentity | undefined;\n let metricsTaskId = \"unknown\";\n let completed = false;\n try {\n if (isEnabled && !(await isEnabled(request))) {\n return Response.json(\n { code: \"request_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n const task = surveyAssistantTaskRequestSchema.parse(\n await readSurveyAssistantRequestJson(request, MAX_TASK_REQUEST_BYTES),\n );\n metricsTaskId = task.taskId;\n const identity = await authorize({\n request,\n requestedResourceId: task.resourceId,\n requestedSurveyId: task.surveyId,\n });\n if (\n !identity?.resourceId?.trim() ||\n identity.resourceId.trim().length > 240 ||\n (identity.surveyId !== undefined &&\n (!identity.surveyId.trim() || identity.surveyId.trim().length > 240))\n ) {\n throw Object.assign(new Error(\"The host returned an invalid task identity.\"), {\n status: 500,\n });\n }\n metricsIdentity = {\n resourceId: identity.resourceId.trim(),\n ...(identity.surveyId?.trim() ? { surveyId: identity.surveyId.trim() } : {}),\n };\n\n const readinessError = await getReadinessError?.(request);\n if (readinessError) {\n return Response.json({ code: \"request_failed\", error: readinessError }, { status: 503 });\n }\n\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n let modelSelection: SurveyAssistantModelSelection | undefined;\n if (resolveModel) {\n modelSelection =\n (await resolveModel({\n identity: metricsIdentity,\n request,\n requestedModelId: task.modelId,\n })) ?? undefined;\n if (!modelSelection) {\n return Response.json(\n {\n code: \"request_failed\",\n error: \"The selected survey assistant model is unavailable.\",\n },\n { status: 400 },\n );\n }\n requestContext.set(\"modelSelection\", modelSelection);\n }\n\n const resolvedAgent = typeof agent === \"function\" ? await agent() : agent;\n const runtime: RunSurveyAssistantBuiltInTaskOptions = {\n abortSignal: AbortSignal.any([request.signal, AbortSignal.timeout(duration)]),\n agent: resolvedAgent,\n context: task.context,\n mode: task.mode,\n requestContext,\n providerOptions: modelSelection?.providerOptions ?? providerOptions,\n };\n const result =\n task.taskId === \"suggest-item-key\"\n ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime)\n : task.taskId === \"suggest-item-label\"\n ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime)\n : await runSurveyAssistantTranslateContentTask(task.input, runtime);\n completed = true;\n return Response.json(result);\n } catch (error) {\n return taskErrorResponse(error);\n } finally {\n activeRequests = Math.max(0, activeRequests - 1);\n if (metricsIdentity) {\n try {\n onTaskMetrics?.({\n durationMs: Date.now() - startedAt,\n identity: metricsIdentity,\n status: completed ? \"completed\" : \"failed\",\n taskId: metricsTaskId,\n });\n } catch {\n // Host metrics must not change the task response.\n }\n }\n }\n };\n};\n"],"mappings":";;;;;;;;;AAsCA,MAAa,kCAAkC,EAAE,YAC/C,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cACE;CACF;CACD,CAAC;AAeJ,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,yBAAyB,OAAkC,EACtE,OACA,QACA,OACA,SACA,QACA,cACA,kBAAkB,EAAE,EACpB,gBACA,iBACA,kBACwE;CACxE,MAAM,aAAa,gBAAgB,KAAK,WAAW;EACjD;EACA,OAAO,0BAA0B,OAAO;EACxC,SAAS,0BAA0B,OAAO;EAC3C,EAAE;CACH,MAAM,WAAW,MAAM,MAAM,SAC3B,KAAK,UAAU;EAAE;EAAQ;EAAO,sBAAsB;EAAS,CAAC,EAChE;EACE,cAAc;GACZ,GAAG;GACH,GAAG;GACH,GAAG,WAAW,KAAK,UAAU,cAAc,MAAM,MAAM,IAAI,MAAM,UAAU;GAC5E;EACD,aAAa,EAAE;EACf,iBAAiB,EAAE;EACnB,UAAU;EACV,kBAAkB;GAChB;GACA,eAAe;GAChB;EACD,GAAI,iBAAiB,EAAE,gBAAgB,GAAG,EAAE;EAC5C,GAAI,kBAAkB,EAAE,iBAAiB,GAAG,EAAE;EAC9C,GAAI,cAAc,EAAE,aAAa,GAAG,EAAE;EACvC,CACF;AAED,QAAO,OAAO,MAAM,SAAS,OAAO;;AAGtC,MAAM,2BAA2B,EAAE,OAAO;CACxC,MAAM,EAAE,QAAQ,CAAC,IAAI,EAAE;CACvB,WAAW,EAAE,QAAQ,CAAC,UAAU;CACjC,CAAC;AAEF,MAAM,8BAA8B,EAAE,KAAK;CAAC;CAAkB;CAAW;CAAa;CAAO,CAAC;AAE9F,MAAM,sBAAsB,EAAE,OAAO;CACnC,eAAe,yBAAyB,SACtC,uFACD;CACD,SAAS,yBAAyB,OAAO,EACvC,MA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2 +1,2 @@
1
- import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-Bp5W_oPa.mjs";
1
+ import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-biZnRl-h.mjs";
2
2
  export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
@@ -1,2 +1,2 @@
1
- import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-GDd5_GUh.mjs";
1
+ import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-TXI8bfzZ.mjs";
2
2
  export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
package/dist/server.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { p as SurveyAssistantTurnTerminationReason } from "./index-EDL1V168.mjs";
2
- import { y as TurnSurveyDraft } from "./index-CPOQgkTN.mjs";
3
- import { a as SurveyAssistantThreadDocumentRepository, c as loadSurveyAssistantThreadAttachments, d as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as SurveyAssistantThreadDocumentContent, l as registerSurveyAssistantThreadAttachments, n as SurveyAssistantModelAttachment, o as getSurveyAssistantReplayableDocuments, r as SurveyAssistantThreadDocument, s as loadSurveyAssistantDocuments, t as SurveyAssistantAttachmentAccess, u as removeHistoricalSurveyAssistantAttachments } from "./thread-documents-C3kf0Vds.mjs";
4
- import { a as SurveyAssistantModelSelection, c as deriveSurveyAssistantDocumentTransition, d as parseSurveyAssistantSnapshot, f as requireSurveyAssistantTurnState, i as SurveyAssistantIdentityContext, l as parseSurveyAssistantPreviousApplyOutcome, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext, r as SurveyAssistantDocumentTransition, s as buildSurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID, u as parseSurveyAssistantPreviousSettledVersion } from "./constants-BK1-g6pR.mjs";
5
- import { A as validateSurveyAssistantMessages, C as SURVEY_ASSISTANT_MAX_MESSAGES, D as SurveyAssistantRequestError, E as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, O as SurveyAssistantRequestLimits, S as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, T as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, _ as formatSurveyAssistantStreamError, a as createSurveyAssistantThreadHandlers, b as SURVEY_ASSISTANT_MAX_ATTACHMENTS, c as SurveyAssistantAuthorize, d as SurveyAssistantModelResolutionInput, f as SurveyAssistantResolveModel, g as describeSurveyAssistantStreamError, h as createSurveyAssistantChatHandler, i as SurveyAssistantThreadRepository, k as readSurveyAssistantRequestJson, l as SurveyAssistantAuthorizedIdentity, m as SurveyAssistantTurnMetrics, n as SurveyAssistantStoredThread, o as SurveyAssistantAuthorizationError, p as SurveyAssistantStreamErrorContext, r as SurveyAssistantThreadIdentity, s as SurveyAssistantAuthorizationInput, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions, v as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, w as SURVEY_ASSISTANT_MAX_REQUEST_BYTES, x as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, y as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./thread-handlers-DZ1WsorO.mjs";
6
- import { a as SurveyAssistantTaskAuthorizationInput, g as surveyAuthoringReferences, h as surveyAuthoringReferenceTopics, m as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity } from "./tasks-DIZgr4nD.mjs";
1
+ import { p as SurveyAssistantTurnTerminationReason } from "./lifecycle-DWv5CiSu.mjs";
2
+ import { y as TurnSurveyDraft } from "./index-r8HVcn5b.mjs";
3
+ import { a as SurveyAssistantThreadDocumentRepository, c as loadSurveyAssistantThreadAttachments, d as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as SurveyAssistantThreadDocumentContent, l as registerSurveyAssistantThreadAttachments, n as SurveyAssistantModelAttachment, o as getSurveyAssistantReplayableDocuments, r as SurveyAssistantThreadDocument, s as loadSurveyAssistantDocuments, t as SurveyAssistantAttachmentAccess, u as removeHistoricalSurveyAssistantAttachments } from "./thread-documents-Dvo6XS7o.mjs";
4
+ import { a as SurveyAssistantModelSelection, c as deriveSurveyAssistantDocumentTransition, d as parseSurveyAssistantSnapshot, f as requireSurveyAssistantTurnState, i as SurveyAssistantIdentityContext, l as parseSurveyAssistantPreviousApplyOutcome, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext, r as SurveyAssistantDocumentTransition, s as buildSurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID, u as parseSurveyAssistantPreviousSettledVersion } from "./constants-k1b_evIb.mjs";
5
+ import { A as validateSurveyAssistantMessages, C as SURVEY_ASSISTANT_MAX_MESSAGES, D as SurveyAssistantRequestError, E as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, O as SurveyAssistantRequestLimits, S as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, T as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, _ as formatSurveyAssistantStreamError, a as createSurveyAssistantThreadHandlers, b as SURVEY_ASSISTANT_MAX_ATTACHMENTS, c as SurveyAssistantAuthorize, d as SurveyAssistantModelResolutionInput, f as SurveyAssistantResolveModel, g as describeSurveyAssistantStreamError, h as createSurveyAssistantChatHandler, i as SurveyAssistantThreadRepository, k as readSurveyAssistantRequestJson, l as SurveyAssistantAuthorizedIdentity, m as SurveyAssistantTurnMetrics, n as SurveyAssistantStoredThread, o as SurveyAssistantAuthorizationError, p as SurveyAssistantStreamErrorContext, r as SurveyAssistantThreadIdentity, s as SurveyAssistantAuthorizationInput, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions, v as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, w as SURVEY_ASSISTANT_MAX_REQUEST_BYTES, x as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, y as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./thread-handlers-D8gkLfU6.mjs";
6
+ import { a as SurveyAssistantTaskAuthorizationInput, g as surveyAuthoringReferences, h as surveyAuthoringReferenceTopics, m as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity } from "./tasks-BWmTMXoK.mjs";
7
7
  import { UIMessageChunk } from "ai";
8
8
  import { MastraMemory } from "@mastra/core/memory";
9
9
 
@@ -11,9 +11,9 @@ import { MastraMemory } from "@mastra/core/memory";
11
11
  type ThreadMemory = Pick<MastraMemory, "createThread" | "deleteThread" | "getThreadById" | "listThreads" | "recall" | "updateThread">;
12
12
  interface CreateMastraMemoryThreadRepositoryOptions {
13
13
  getMemory(): ThreadMemory | Promise<ThreadMemory>;
14
- /** Maximum recent messages returned when hydrating a transcript. */
14
+ /** Maximum recent messages returned per transcript page. */
15
15
  maxMessagesPerTranscript?: number;
16
- /** Maximum recent threads returned by the history endpoint. */
16
+ /** Maximum threads returned per history page. */
17
17
  maxThreadsPerList?: number;
18
18
  threadDocuments?: SurveyAssistantThreadDocumentRepository;
19
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/memory-thread-repository.ts","../src/server/survey-lifecycle.ts","../src/server/turn-stream.ts"],"mappings":";;;;;;;;;;KAKK,YAAA,GAAe,IAAA,CAClB,YAAA;AAAA,UAIe,yCAAA;EACf,SAAA,IAAa,YAAA,GAAe,OAAA,CAAQ,YAAA;;EAEpC,wBAAA;;EAEA,iBAAA;EACA,eAAA,GAAkB,uCAAA;AAAA;AAAA,cAGP,kCAAA;EAAsC,SAAA;EAAA,wBAAA;EAAA,iBAAA;EAAA;AAAA,GAKhD,yCAAA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A;EAAA;AAAA,GAKlD,2CAAA,KAA8C,8BAAA;;;UCnIhC,gCAAA;EACf,MAAA,EAAQ,cAAA,CAAe,cAAA;EACvB,SAAA,EAAW,eAAA;EACX,MAAA,GAAS,WAAA;EACT,iBAAA,IAAqB,KAAA;EACrB,UAAA;EACA,SAAA;EACA,iBAAA;EACA,yBAAA,SAAkC,oCAAA;EAClC,aAAA;AAAA;AAAA,cAqBW,+BAAA;EAAmC,SAAA;EAAA,iBAAA;EAAA,yBAAA;EAAA,UAAA;EAAA,SAAA;EAAA,iBAAA;EAAA,MAAA;EAAA,MAAA;EAAA;AAAA,GAU7C,gCAAA,KAAmC,cAAA,CAAe,cAAA"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/memory-thread-repository.ts","../src/server/survey-lifecycle.ts","../src/server/turn-stream.ts"],"mappings":";;;;;;;;;;KAKK,YAAA,GAAe,IAAA,CAClB,YAAA;AAAA,UAIe,yCAAA;EACf,SAAA,IAAa,YAAA,GAAe,OAAA,CAAQ,YAAA;;EAEpC,wBAAA;;EAEA,iBAAA;EACA,eAAA,GAAkB,uCAAA;AAAA;AAAA,cAGP,kCAAA;EAAsC,SAAA;EAAA,wBAAA;EAAA,iBAAA;EAAA;AAAA,GAKhD,yCAAA,KAA4C,+BAAA;;;cCTlC,uCAAA;AAAA,KAER,qBAAA,GAAwB,IAAA,CAC3B,YAAA;AAAA,UAIe,2CAAA;EACf,SAAA,IAAa,qBAAA,GAAwB,OAAA,CAAQ,qBAAA;;EAE7C,YAAA,EAAc,QAAA;EDpBX;;;;ECyBH,aAAA,EAAe,MAAA;EDpBA;;;;ECyBf,eAAA,EAAiB,uCAAA;AAAA;AAAA,UAGF,uCAAA;EACf,QAAA;EDvByD;ECyBzD,UAAA;AAAA;AAAA,UAGe,kCAAA;EACf,gBAAA;EACA,kBAAA;AAAA;AAAA,KAGU,wCAAA,GAA2C,kCAAA;AAAA,UAEtC,+BAAA;EACf,UAAA;EACA,QAAA;EACA,SA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1
  import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CFUWrRtl.mjs";
2
- import { a as parseSurveyAssistantPreviousSettledVersion, i as parseSurveyAssistantPreviousApplyOutcome, n as deriveSurveyAssistantDocumentTransition, o as parseSurveyAssistantSnapshot, s as requireSurveyAssistantTurnState, t as buildSurveyAssistantRequestContext } from "./request-context-BEjnaaFr.mjs";
2
+ import { a as parseSurveyAssistantPreviousSettledVersion, i as parseSurveyAssistantPreviousApplyOutcome, n as deriveSurveyAssistantDocumentTransition, o as parseSurveyAssistantSnapshot, s as requireSurveyAssistantTurnState, t as buildSurveyAssistantRequestContext } from "./request-context-DixY5DYu.mjs";
3
3
  import { a as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, c as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, d as readSurveyAssistantRequestJson, f as validateSurveyAssistantMessages, i as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, l as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, n as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, o as SURVEY_ASSISTANT_MAX_MESSAGES, r as SURVEY_ASSISTANT_MAX_ATTACHMENTS, s as SURVEY_ASSISTANT_MAX_REQUEST_BYTES, t as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, u as SurveyAssistantRequestError } from "./request-guardrails-h4t6u8mP.mjs";
4
- import { a as describeSurveyAssistantStreamError, c as loadSurveyAssistantDocuments, d as removeHistoricalSurveyAssistantAttachments, f as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as createSurveyAssistantChatHandler, l as loadSurveyAssistantThreadAttachments, n as createSurveyAssistantThreadHandlers, o as formatSurveyAssistantStreamError, p as createSurveyAssistantTurnStream, r as SurveyAssistantAuthorizationError, s as getSurveyAssistantReplayableDocuments, t as createMastraMemoryThreadRepository, u as registerSurveyAssistantThreadAttachments } from "./memory-thread-repository-acbz6HZJ.mjs";
5
- import { i as surveyAuthoringReferences, r as surveyAuthoringReferenceTopics } from "./authoring-references-ChDTVnms.mjs";
4
+ import { a as describeSurveyAssistantStreamError, c as loadSurveyAssistantDocuments, d as removeHistoricalSurveyAssistantAttachments, f as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as createSurveyAssistantChatHandler, l as loadSurveyAssistantThreadAttachments, n as createSurveyAssistantThreadHandlers, o as formatSurveyAssistantStreamError, p as createSurveyAssistantTurnStream, r as SurveyAssistantAuthorizationError, s as getSurveyAssistantReplayableDocuments, t as createMastraMemoryThreadRepository, u as registerSurveyAssistantThreadAttachments } from "./memory-thread-repository-xBZOog_q.mjs";
5
+ import { i as surveyAuthoringReferences, r as surveyAuthoringReferenceTopics } from "./authoring-references-yyYC4Ydi.mjs";
6
6
  //#region src/server/survey-lifecycle.ts
7
7
  const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = "surveyId";
8
8
  const normalizeIdentifier = (value, label) => {
@@ -1,4 +1,4 @@
1
- import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-C3kf0Vds.mjs";
1
+ import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-Dvo6XS7o.mjs";
2
2
  import { PostgresStore, PostgresStoreConfig } from "@mastra/pg";
3
3
 
4
4
  //#region src/storage/postgres.d.ts
@@ -1,5 +1,5 @@
1
- import { F as SurveyAssistantSuggestItemLabelInput, I as SurveyAssistantSuggestItemLabelResult, N as SurveyAssistantSuggestItemKeyInput, P as SurveyAssistantSuggestItemKeyResult, R as SurveyAssistantTaskContext, U as SurveyAssistantTranslateContentInput, W as SurveyAssistantTranslateContentResult, z as SurveyAssistantTaskInvocationMode } from "./index-EDL1V168.mjs";
2
- import { a as SurveyAssistantModelSelection, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext } from "./constants-BK1-g6pR.mjs";
1
+ import { c as SurveyAssistantSuggestItemKeyInput, d as SurveyAssistantSuggestItemLabelResult, l as SurveyAssistantSuggestItemKeyResult, m as SurveyAssistantTaskInvocationMode, p as SurveyAssistantTaskContext, u as SurveyAssistantSuggestItemLabelInput, v as SurveyAssistantTranslateContentInput, y as SurveyAssistantTranslateContentResult } from "./index-8x1Eqlnz.mjs";
2
+ import { a as SurveyAssistantModelSelection, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext } from "./constants-k1b_evIb.mjs";
3
3
  import { z } from "zod";
4
4
  import { RequestContext } from "@mastra/core/request-context";
5
5
  import * as _$_mastra_core_agent0 from "@mastra/core/agent";
@@ -141,4 +141,4 @@ declare const createSurveyAssistantTaskHandler: ({
141
141
  }: CreateSurveyAssistantTaskHandlerOptions) => (request: Request) => Promise<Response>;
142
142
  //#endregion
143
143
  export { SurveyAssistantTaskAuthorizationInput as a, createSurveyAssistantTaskAgent as c, runSurveyAssistantSuggestItemLabelTask as d, runSurveyAssistantTask as f, surveyAuthoringReferences as g, surveyAuthoringReferenceTopics as h, RunSurveyAssistantTaskOptions as i, createSurveyAssistantTaskHandler as l, SurveyAuthoringReferenceTopic as m, CreateSurveyAssistantTaskHandlerOptions as n, SurveyAssistantTaskAuthorizedIdentity as o, runSurveyAssistantTranslateContentTask as p, RunSurveyAssistantBuiltInTaskOptions as r, SurveyAssistantTaskModelResolutionInput as s, CreateSurveyAssistantTaskAgentOptions as t, runSurveyAssistantSuggestItemKeyTask as u };
144
- //# sourceMappingURL=tasks-DIZgr4nD.d.mts.map
144
+ //# sourceMappingURL=tasks-BWmTMXoK.d.mts.map