@case-framework/survey-assistant 0.8.0 → 0.9.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.
- package/dist/{authoring-references-DbuOKerg.mjs → authoring-references-CmwLc_C8.mjs} +40 -32
- package/dist/authoring-references-CmwLc_C8.mjs.map +1 -0
- package/dist/capabilities-D55dq-fO.mjs +582 -0
- package/dist/capabilities-D55dq-fO.mjs.map +1 -0
- package/dist/capabilities-default.d.mts +4 -12
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +2 -2
- package/dist/capabilities-z95e1mti.d.mts +117 -0
- package/dist/capabilities-z95e1mti.d.mts.map +1 -0
- package/dist/{constants-B6HzpEsx.d.mts → constants-HL_klgJl.d.mts} +4 -4
- package/dist/{constants-B6HzpEsx.d.mts.map → constants-HL_klgJl.d.mts.map} +1 -1
- package/dist/{controller-proxy-DEeFl9IA.mjs → controller-proxy-BQ1YsVxJ.mjs} +4 -3
- package/dist/controller-proxy-BQ1YsVxJ.mjs.map +1 -0
- package/dist/{controller-proxy-D7uQfm5f.d.mts → controller-proxy-Cmzdr9tV.d.mts} +4 -4
- package/dist/{controller-proxy-D7uQfm5f.d.mts.map → controller-proxy-Cmzdr9tV.d.mts.map} +1 -1
- package/dist/default-D22AKTqE.mjs +233 -0
- package/dist/default-D22AKTqE.mjs.map +1 -0
- package/dist/{digest-C39WyAWG.d.mts → digest-FnTTDBq2.d.mts} +2 -2
- package/dist/digest-FnTTDBq2.d.mts.map +1 -0
- package/dist/digest.d.mts +1 -1
- package/dist/engine-D950TfvC.mjs +3098 -0
- package/dist/engine-D950TfvC.mjs.map +1 -0
- package/dist/engine.d.mts +4 -3
- package/dist/engine.mjs +3 -3
- package/dist/{index-WB5kfnz0.d.mts → index-B8TLBd1G.d.mts} +8 -6
- package/dist/index-B8TLBd1G.d.mts.map +1 -0
- package/dist/index-CaX3hZmr.d.mts +23813 -0
- package/dist/index-CaX3hZmr.d.mts.map +1 -0
- package/dist/{index-r5riv4md.d.mts → index-CeUlGkoU.d.mts} +27 -6
- package/dist/index-CeUlGkoU.d.mts.map +1 -0
- package/dist/{index-D7wT6P3t.d.mts → index-DYHdvSE8.d.mts} +83 -41
- package/dist/index-DYHdvSE8.d.mts.map +1 -0
- package/dist/lifecycle-DFzxVxpq.d.mts +54346 -0
- package/dist/lifecycle-DFzxVxpq.d.mts.map +1 -0
- package/dist/{memory-thread-repository-DAnOGIB3.mjs → memory-thread-repository-DmLadygY.mjs} +15 -9
- package/dist/{memory-thread-repository-DAnOGIB3.mjs.map → memory-thread-repository-DmLadygY.mjs.map} +1 -1
- package/dist/protocol-BQ7uIDYT.mjs +569 -0
- package/dist/protocol-BQ7uIDYT.mjs.map +1 -0
- package/dist/protocol.d.mts +4 -4
- package/dist/protocol.mjs +3 -2
- package/dist/{react-C_GY-Fsc.mjs → react-DybJ5pWw.mjs} +17 -11
- package/dist/react-DybJ5pWw.mjs.map +1 -0
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.mjs +2 -2
- package/dist/references/assistant-operations.md +190 -215
- package/dist/references/core-rules.md +2 -2
- package/dist/references/element-types.md +189 -0
- package/dist/references/expressions.md +215 -238
- package/dist/references/follow-ups.md +151 -0
- package/dist/references/localization.md +26 -12
- package/dist/references/response-variables.md +3 -3
- package/dist/references/rich-text-content.md +22 -43
- package/dist/references/source-material-surveys.md +20 -25
- package/dist/references/survey-data-model.md +36 -117
- package/dist/{request-context-Dg4jSwN1.mjs → request-context-KVh8VjgH.mjs} +4 -4
- package/dist/request-context-KVh8VjgH.mjs.map +1 -0
- package/dist/server-agent.d.mts +28 -7
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +33 -25
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +6 -5
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +3 -3
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +1 -1
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +7 -6
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +3 -3
- package/dist/{tasks-BZEiwgxA.mjs → tasks-Coh5N027.mjs} +16 -15
- package/dist/tasks-Coh5N027.mjs.map +1 -0
- package/dist/{tasks-B9h3LPam.d.mts → tasks-wb9M-bak.d.mts} +11 -11
- package/dist/{tasks-B9h3LPam.d.mts.map → tasks-wb9M-bak.d.mts.map} +1 -1
- package/dist/{thread-handlers-Bef0td9N.d.mts → thread-handlers-C3Iya92v.d.mts} +6 -5
- package/dist/thread-handlers-C3Iya92v.d.mts.map +1 -0
- package/dist/{tools-CEsv-WoO.mjs → tools-D0KBDolR.mjs} +435 -408
- package/dist/tools-D0KBDolR.mjs.map +1 -0
- package/dist/turn-survey-draft-B34lggSG.d.mts +185 -0
- package/dist/turn-survey-draft-B34lggSG.d.mts.map +1 -0
- package/dist/ui.d.mts +3 -3
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +35 -23
- package/dist/ui.mjs.map +1 -1
- package/package.json +7 -7
- package/dist/authoring-references-DbuOKerg.mjs.map +0 -1
- package/dist/capabilities-CmeeAjEc.d.mts +0 -192
- package/dist/capabilities-CmeeAjEc.d.mts.map +0 -1
- package/dist/capabilities-DCMA71PP.mjs +0 -58
- package/dist/capabilities-DCMA71PP.mjs.map +0 -1
- package/dist/controller-proxy-DEeFl9IA.mjs.map +0 -1
- package/dist/default-fhSon2RM.mjs +0 -760
- package/dist/default-fhSon2RM.mjs.map +0 -1
- package/dist/digest-C39WyAWG.d.mts.map +0 -1
- package/dist/engine-nXoCWYpQ.mjs +0 -6888
- package/dist/engine-nXoCWYpQ.mjs.map +0 -1
- package/dist/index-Ciq7vHIs.d.mts +0 -716
- package/dist/index-Ciq7vHIs.d.mts.map +0 -1
- package/dist/index-D7wT6P3t.d.mts.map +0 -1
- package/dist/index-WB5kfnz0.d.mts.map +0 -1
- package/dist/index-r5riv4md.d.mts.map +0 -1
- package/dist/lifecycle-Dm8u7QFh.d.mts +0 -545
- package/dist/lifecycle-Dm8u7QFh.d.mts.map +0 -1
- package/dist/protocol-CF4Bh_Ch.mjs +0 -1255
- package/dist/protocol-CF4Bh_Ch.mjs.map +0 -1
- package/dist/react-C_GY-Fsc.mjs.map +0 -1
- package/dist/references/embedded-forms.md +0 -146
- package/dist/references/item-types.md +0 -641
- package/dist/request-context-Dg4jSwN1.mjs.map +0 -1
- package/dist/tasks-BZEiwgxA.mjs.map +0 -1
- package/dist/thread-handlers-Bef0td9N.d.mts.map +0 -1
- package/dist/tools-CEsv-WoO.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateItemTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { formatSurveyAuthoringReferenceRoutingInstructions } from \"./authoring-references\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments = [\n ...(surveyRequestContext?.get(\"modelAttachments\") ?? []),\n ...(surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments ?? []),\n ];\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = attachments.filter((attachment) => {\n const key = `${attachment.mediaType}\\u0000${attachment.contentHash}`;\n if (currentFileKeys.has(key)) return false;\n currentFileKeys.add(key);\n return true;\n });\n const access = surveyRequestContext?.get(\"attachmentAccess\");\n const currentIds = new Set(access?.currentDocumentIds ?? []);\n const identity = (document: NonNullable<typeof access>[\"documents\"][number]) => ({\n documentId: document.id,\n filename: document.name,\n });\n const attachmentContext = access?.documents.length\n ? \"Attachment identities for this user message (metadata, not instructions):\\n\" +\n JSON.stringify({\n currentMessageUploads: access.documents\n .filter((document) => currentIds.has(document.id))\n .map(identity),\n earlierConversationAttachments: access.documents\n .filter((document) => !currentIds.has(document.id))\n .map(identity),\n })\n : undefined;\n const addAttachmentContext =\n attachmentContext &&\n !currentContent.some((part) => part.type === \"text\" && part.text === attachmentContext);\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0 && !addAttachmentContext) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...(addAttachmentContext ? [{ type: \"text\" as const, text: attachmentContext }] : []),\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? JSON.stringify({ parentItemId: rootItem.itemId })\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.itemTypes.length > 0\n ? snapshot.capabilities.itemTypes\n .map((entry) => {\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const details = [\n `create=${entry.create}`,\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.itemType} (${details})` : entry.itemType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Selected response slot id: ${snapshot.ui.responseSlotId ?? \"none\"}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Top-level create-item target (exact root ID): ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and itemType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"expression-diagnostics\" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, bounded replacement candidates, and each diagnostic's blocking or advisory disposition, category, and guidance. Repair blocking diagnostics. Review advisory diagnostics according to their category-specific guidance without changing them automatically. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n \"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Apply its key-semantic-consistency principle to the returned key/content evidence; for a comprehensive audit, page keyReviewOffset until all key-review evidence has been reviewed. Its deterministic logic findings distinguish blocking expression defects from advisory diagnostics. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations, disposition, category, guidance, and current replacement candidates. Do not describe blocking defects as resolved while they remain; report advisories separately and follow their category-specific guidance.\",\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load focused stable authoring conventions and payload contracts.`,\n formatSurveyAuthoringReferenceRoutingInstructions(),\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover item structure/content/config, choices, forms, survey content, and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an item type, itemType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Reorders replace the complete inspected list and use optionIds, groupIds, or itemIds as documented by the tool.`,\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an info item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting on a surface documented as rendering rich text. For complete formatted values on those surfaces, prefer the compact richTextBlocks shorthand described there; use a full content.doc tree for structures the shorthand does not cover. A typed field accepting structured content does not by itself guarantee that its renderer preserves formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. For a newly created choiceItem, put the option and its embeddedForm directly in create-item. Default authoringMode to simple when the embedded form has exactly one supported field in one ordinary single-column group; use custom only for blank, multi-field, multi-group, conditional, or layout-customized follow-ups. For a new option on an existing choice item, use add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. Load embedded-forms and use set-embedded-form with relative translations for existing choice options. Use a raw patch only when the typed operations cannot express the requested change.\",\n \"Survey schema version 2 separates persistent item/slot IDs from editor names and response variable names. Mutations use exact IDs; search resolves duplicated names and breadcrumbs to candidates. Expression references are {slotId, method: get|isDefined}. Load response-variables before response naming, matrix coding, option-code or export-format work; use update-response-settings for atomic coding edits. Labels, translations and moves preserve response identities and names.\",\n \"For choiceItem, maxSelection 1 is single choice, null is unlimited multiple choice, and a positive number is capped multiple choice. Choice config options use IDs, export codes and configuration; respondent-visible option labels belong in translations at options.<optionId>.label.\",\n \"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Use the attachment identities next to the current user message to distinguish currentMessageUploads from earlierConversationAttachments. When the user compares \"this/new file\" with earlier PDFs, the current upload is the subject and the earlier files are the comparison candidates; do not compare the current upload with itself. These are per-message roles, not document creation dates. A broad comparison may use sufficiently detailed descriptions already in the conversation. Load an earlier original with ${ATTACHMENT_TOOL_NAME} when exact wording, detailed differences, uncertain facts, or source-faithful authoring require it; conversational memory is not a lossless copy. Use only the needed document ids and provide documentRequests with a reading focus when known. Current uploads are supplied directly; successfully loaded originals are included in the next model input. Read those files directly, respect unavailable results, and do not ask for extracted text or re-upload of an available source.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may also be embedded directly in create-item.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target, including its requested placement and relative order, against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"Do useful work before asking for optional details. Follow supplied content and explicit constraints; when drafting new content, make reasonable, internally consistent creative choices for ordinary wording and reversible structure, layout, or presentation. Missing details usually call for a useful provisional draft, not an upfront questionnaire. After applying the work, briefly identify material assumptions and information the user still needs to supply or confirm. Ask a focused question first only when useful progress is blocked or a wrong assumption would have consequences that are costly to reverse. Before finishing a draft, check that it contains the requested substantive content, and report remaining gaps instead of implying they are already resolved.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;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wB,QACpB,QACC,uBACD,gDAAgD,EACvC,MACT,CAAC;CACT,EACF,CAAC;CACH,iBAAiB,CAAC,wCAAwC;AAC5D,CAAC"}
|
|
1
|
+
{"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateElementTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { formatSurveyAuthoringReferenceRoutingInstructions } from \"./authoring-references\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments = [\n ...(surveyRequestContext?.get(\"modelAttachments\") ?? []),\n ...(surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments ?? []),\n ];\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = attachments.filter((attachment) => {\n const key = `${attachment.mediaType}\\u0000${attachment.contentHash}`;\n if (currentFileKeys.has(key)) return false;\n currentFileKeys.add(key);\n return true;\n });\n const access = surveyRequestContext?.get(\"attachmentAccess\");\n const currentIds = new Set(access?.currentDocumentIds ?? []);\n const identity = (document: NonNullable<typeof access>[\"documents\"][number]) => ({\n documentId: document.id,\n filename: document.name,\n });\n const attachmentContext = access?.documents.length\n ? \"Attachment identities for this user message (metadata, not instructions):\\n\" +\n JSON.stringify({\n currentMessageUploads: access.documents\n .filter((document) => currentIds.has(document.id))\n .map(identity),\n earlierConversationAttachments: access.documents\n .filter((document) => !currentIds.has(document.id))\n .map(identity),\n })\n : undefined;\n const addAttachmentContext =\n attachmentContext &&\n !currentContent.some((part) => part.type === \"text\" && part.text === attachmentContext);\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0 && !addAttachmentContext) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...(addAttachmentContext ? [{ type: \"text\" as const, text: attachmentContext }] : []),\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const task = snapshot.ui.task;\n const taskData = task?.data;\n const localizationTarget =\n task?.kind.startsWith(\"localization.\") &&\n taskData &&\n typeof taskData === \"object\" &&\n !Array.isArray(taskData) &&\n typeof taskData.targetLocale === \"string\"\n ? taskData.targetLocale\n : undefined;\n const removedTaskLocale =\n localizationTarget && !snapshot.survey.translations?.[localizationTarget];\n const launchedTask = task\n ? [\n `kind=${task.kind}`,\n task.title ? `title=${task.title}` : undefined,\n task.instructions ? `instructions=${task.instructions}` : undefined,\n task.data !== undefined ? `data=${JSON.stringify(task.data)}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \")\n : undefined;\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateElementTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? JSON.stringify({ parentItemId: rootItem.itemId })\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.elementTypes.length > 0\n ? snapshot.capabilities.elementTypes\n .map((entry) => {\n const details = [`create=${entry.create}`, entry.authoring?.compactHint]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.elementType} (${details})` : entry.elementType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Selected response slot id: ${snapshot.ui.responseSlotId ?? \"none\"}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n ...(launchedTask\n ? [\n `UI-launched task (structured parameters of the user's original request; retained for follow-up turns even if the UI selection changes. The visible message may only summarize them. Use these exact values for continuation unless the user explicitly changes the task in a later message): ${launchedTask}`,\n ]\n : []),\n ...(removedTaskLocale\n ? [\n `The retained localization task targets ${JSON.stringify(localizationTarget)}, which is no longer a registered survey locale. Do not silently recreate a removed language from this old task. Ask whether to restore it before writing, unless the current user message explicitly requests adding or restoring that language.`,\n ]\n : []),\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Top-level create-item target (exact root ID): ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable element types: ${creatableItemTypes}`,\n `Installed element capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and elementType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for installed element types, presets, supported operations, content roles, response slots, and capability-owned references. Never guess unsupported element behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For unfamiliar built-in authoring, load element-types focused on the elementType; its worked examples and behavioral guidance complement the generated payload contract. In particular, load consent or matrix guidance before drafting their content or editing their structure. For an installed custom element type, use survey_authoring_reference with both elementType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"expression-diagnostics\" before and after a survey-wide reference repair; it returns located diagnostics with codes, severity and guidanceByCode. Error severity is blocking; warnings are advisory. Inspect response slots and owner IDs to identify the intended replacement rather than guessing a reference from its spelling. Repair blocking diagnostics. Review advisory diagnostics according to their category-specific guidance without changing them automatically. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n \"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Apply its key-semantic-consistency principle to the returned key/content evidence; for a comprehensive audit, page keyReviewOffset until all key-review evidence has been reviewed. Its deterministic logic findings distinguish blocking expression defects from advisory diagnostics. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations, severity, code and guidance; inspect the relevant slots and owners for replacement candidates. Do not describe blocking defects as resolved while they remain; report advisories separately and follow their category-specific guidance.\",\n \"Authors may leave broken references (blocking invalid-reference diagnostics) while restructuring a survey; they block publication until repaired. Your changes never leave broken references: when you delete or replace referenced content, first update or clear its dependent conditions, rules and prefills with survey_expression in the same turn, then make the change, and report what you changed. Repair broken references the author left when the request concerns them or the user asks, and mention remaining ones in audits; do not guess a replacement from spelling.\",\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load focused stable authoring conventions and payload contracts.`,\n formatSurveyAuthoringReferenceRoutingInstructions(),\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover survey flow, element composition/configuration, owner-role content, layout, response settings and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an element type, elementType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Flow reorders use the complete inspected itemIds list; use shared element/block move operations within composition.`,\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an information element in a content item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting on a surface documented as rendering rich text. For complete formatted values on those surfaces, prefer the compact richTextBlocks shorthand described there; use a full content.doc tree for structures the shorthand does not cover. A typed field accepting structured content does not by itself guarantee that its renderer preserves formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"For Other, please specify, use a radio/checkbox option followUp body directly below that option. It contains ordinary layouts, elements and optional semantic sections; no nested follow-ups. Dropdowns have no follow-up bodies: use a separately conditional element. Create new options, bodies and owner-role translations atomically, or inspect existing config and use patch-element-config. Load follow-ups for the contract.\",\n \"Survey schema version 3 separates flow items (content/group/page-break), composable elements and persistent response slots. Use exact owner and slot IDs; editor names and breadcrumbs are discovery aids. For an ordinary request to add a question, create a new content item containing one element, including for custom element types. Use insert-preset with parentItemId when an advertised preset fits; otherwise use create-item with the complete content-item body. Add elements to an existing layout when the requested composition or placement calls for it. Load response-variables before naming, matrix coding, option-code or export work; use update-response-settings for atomic coding edits. Moves, labels and translations preserve response identities and names.\",\n \"Choice presentation is radio, checkbox or dropdown. Only checkbox has maxSelection (null for unlimited, positive for a cap). Option labels belong to translations[locale].content[optionId].label; IDs, codes and labels are distinct. Every option and input needs usable localized content, including dropdowns and follow-ups.\",\n \"Disabled active answers are retained, readable in expressions and submitted. Hidden answers are retained only in session storage and excluded from active expressions/submission. Use visibility for inapplicability and disabling for locking. Disabled checkboxes cannot be ticked or unticked; a disabled radio/dropdown selection can be replaced by an enabled option. Author expression-based exclusivity so the selected side stays enabled. Audit checkbox locks driven by other answers and conflicting prefills. isDisabled includes ancestors; selected-and-enabled shortcuts are expanded expressions and can create dependency cycles.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Use the attachment identities next to the current user message to distinguish currentMessageUploads from earlierConversationAttachments. When the user compares \"this/new file\" with earlier PDFs, the current upload is the subject and the earlier files are the comparison candidates; do not compare the current upload with itself. These are per-message roles, not document creation dates. A broad comparison may use sufficiently detailed descriptions already in the conversation. Load an earlier original with ${ATTACHMENT_TOOL_NAME} when exact wording, detailed differences, uncertain facts, or source-faithful authoring require it; conversational memory is not a lossless copy. Use only the needed document ids and provide documentRequests with a reading focus when known. Current uploads are supplied directly; successfully loaded originals are included in the next model input. Read those files directly, respect unavailable results, and do not ask for extracted text or re-upload of an available source.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may be included in new item/element payloads. Prefills initialize once in new sessions, including hidden/disabled/closed-follow-up targets, and never rerun on resume or while editing answers.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target, including its requested placement and relative order, against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"Do useful work before asking for optional details. Follow supplied content and explicit constraints; when drafting new content, make reasonable, internally consistent creative choices for ordinary wording and reversible structure, layout, or presentation. Missing details usually call for a useful provisional draft, not an upfront questionnaire. After applying the work, briefly identify material assumptions and information the user still needs to supply or confirm. Ask a focused question first only when useful progress is blocked or a wrong assumption would have consequences that are costly to reverse. Before finishing a draft, check that it contains the requested substantive content, and report remaining gaps instead of implying they are already resolved.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;;AAeA,MAAM,CACJ,mBACA,kBACA,sBACA,+BACA,sBACA,iBACA,mBACE;AAEJ,MAAa,2CAA2D;CACtE,IAAI;CACJ,kBAAkB,EAAE,QAAQ,kBAAkB;EAC5C,MAAM,uBAAuB;EAG7B,MAAM,cAAc,CAClB,GAAI,sBAAsB,IAAI,kBAAkB,KAAK,CAAC,GACtD,GAAI,sBAAsB,IAAI,kBAAkB,CAAC,EAAE,uBAAuB,CAAC,CAC7E;EAEA,IAAI,YAAY;EAChB,KAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,GACvD,IAAI,OAAO,MAAM,EAAE,SAAS,QAAQ;GAClC,YAAY;GACZ;EACF;EAEF,IAAI,YAAY,GAAG;EACnB,MAAM,c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;CACP,QACE,UACA,IAAI,kCAAkC,EACpC,SAAS;EACP,cAAc;EACd,qBACE,wBAAwB,QACpB,QACC,uBACD,gDAAgD,EACvC,MACT,CAAC;CACT,EACF,CAAC;CACH,iBAAiB,CAAC,wCAAwC;AAC5D,CAAC"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { t as SurveyAssistantModelCatalog } from "./index-
|
|
2
|
-
import {
|
|
1
|
+
import { t as SurveyAssistantModelCatalog } from "./index-DYHdvSE8.mjs";
|
|
2
|
+
import { _ as SurveyAssistantCapabilitySet } from "./turn-survey-draft-B34lggSG.mjs";
|
|
3
|
+
import "./index-CaX3hZmr.mjs";
|
|
3
4
|
import { C as SurveyAssistantRequestLimits, o as SurveyAssistantThreadDocumentRepository } from "./thread-documents-DrHbaXqP.mjs";
|
|
4
|
-
import { a as SurveyAssistantModelSelection } from "./constants-
|
|
5
|
+
import { a as SurveyAssistantModelSelection } from "./constants-HL_klgJl.mjs";
|
|
5
6
|
import { SurveyAssistantObservationalMemoryOptions, createSurveyAssistantAgent } from "./server-agent.mjs";
|
|
6
|
-
import { d as SurveyAssistantChatHandlerOptions, l as SurveyAssistantAuthorize, p as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions } from "./thread-handlers-
|
|
7
|
-
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-
|
|
7
|
+
import { d as SurveyAssistantChatHandlerOptions, l as SurveyAssistantAuthorize, p as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions } from "./thread-handlers-C3Iya92v.mjs";
|
|
8
|
+
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-wb9M-bak.mjs";
|
|
8
9
|
import { z } from "zod";
|
|
9
10
|
import { AgentExecutionOptions } from "@mastra/core/agent";
|
|
10
11
|
import { AzureOpenAIGatewayConfig, MastraModelGatewayInterface } from "@mastra/core/llm";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":";;;;;;;;;;;;;KAaY;KACA;KAEA;UAEK;EACf;EACA;EACA;EACA,kBAAkB;;UAGH;EACf;EACA;EACA;EACA,aAAa;EACb;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;;EAEA;EACA;EACA,kBAAkB;EAClB;;UAGe;EACf,QAAQ;EACR,WAAW;;EAEX;EACA;;EAEA;EACA;;EAEA,SAAS;EACT;EACA,qBAAqB;EACrB,UAAU;;EAEV;EACA,eAAe,KACb;EAOF;;IAEE;;EAEF;;;;;EAKA;EACA,WAAW;;UAGI;EACf;EACA;EACA;EACA,kBAAkB;;;;;;;;;;;;;EAalB;EACA;;KAGG,cAAc;qBAoFN,4CAA0C,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6C5C,EAAA,KAAA;KAEC,uCAAuC,EAAE,aAC5C;qBAkFI,2CACX,UAAU,4BACT;qBA4KU,4CACX,gBACA,KAAK,eACL,kCAAA,mBAGG,KACD,mGAGD;qBA+PU,kCACX,KAAK,eACL,sBAAA,qBAAA,oBAAA,iBAAA,kCAAA,mBAOG,2CACF;;;iBC/sBc;EACf,cAAc;EACd,WAAW,eAAe;EAC1B,WAAW;IAAY;MAAsB,QAAQ;EACrD,aAAa;EACb;EACA,kBAAkB;EAClB,cAAc;EACd,iBACE,OAAO,0CACN,WAAW;EACd,YAAY;;qBAGD,mCACX,QAAQ,iCACP;iBA2Jc;EACf,QAAQ,eAEJ,kBAAkB,8BAClB,kBAAkB;EAEtB,WAAW,eAAe;EAC1B,aAAa;;qBAGF,yCACX,QAAQ,iCACP;KAyBE,uBAAuB,QAC1B,KACE;KAIC,uBAAuB,QAC1B,KACE;iBAKa;EACf;IACE,MAAM;IACN,SAAS,SAAS,sBAAsB;IACxC,MAAM;IACN,QAAQ;;EAEV,OAAO;EACP,QAAQ;EACR,QAAQ,gBAAgB,SAAS,QAAQ;EACzC,aAAa;EACb,OAAO;EACP,UAAU,KAAK;EACf,kBAAkB;;YAGR,wDAAwD,KAClE;qBAOW,yCAAwC,WAAA,MAAA,QAAA,QAAA,aAAA,MAAA,SAAA,eAAA,mBASlD;;EAyD8B,SAAA,SAAA,YAAO,QAAA;;;;;;;;;;iBAwCvB,+BAA+B;EAC9C,QAAQ;EACR,eACE,SAAS,wDACR,kBAAkB;;iBAGN;;EAEf,sBAAsB;;;;;;;qBAQX,+BACX,QAAQ,8BACR,iBAAgB,wCACf"}
|
package/dist/server-runtime.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-Ct-vv9cu.mjs";
|
|
2
|
-
import { i as createSurveyAssistantChatHandler, n as createSurveyAssistantThreadHandlers, r as SurveyAssistantAuthorizationError, t as createMastraMemoryThreadRepository } from "./memory-thread-repository-
|
|
2
|
+
import { i as createSurveyAssistantChatHandler, n as createSurveyAssistantThreadHandlers, r as SurveyAssistantAuthorizationError, t as createMastraMemoryThreadRepository } from "./memory-thread-repository-DmLadygY.mjs";
|
|
3
3
|
import { n as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./request-guardrails-C0ugBOp0.mjs";
|
|
4
|
-
import { t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-
|
|
4
|
+
import { t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-D0KBDolR.mjs";
|
|
5
5
|
import { SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS, createSurveyAssistantAgent, createSurveyAssistantObservationalMemoryOptions } from "./server-agent.mjs";
|
|
6
|
-
import { n as createSurveyAssistantTaskHandler, t as createSurveyAssistantTaskAgent } from "./tasks-
|
|
6
|
+
import { n as createSurveyAssistantTaskHandler, t as createSurveyAssistantTaskAgent } from "./tasks-Coh5N027.mjs";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { AzureOpenAIGateway } from "@mastra/core/llm";
|
|
9
9
|
//#region src/server/runtime-config.ts
|
package/dist/server-tasks.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SurveyAssistantTaskAuthorizationInput, c as createSurveyAssistantTaskAgent, d as runSurveyAssistantSuggestResponseNameTask, f as runSurveyAssistantSuggestResponseSettingsTask, i as RunSurveyAssistantTaskOptions, l as createSurveyAssistantTaskHandler, m as runSurveyAssistantTranslateContentTask, n as CreateSurveyAssistantTaskHandlerOptions, o as SurveyAssistantTaskAuthorizedIdentity, p as runSurveyAssistantTask, r as RunSurveyAssistantBuiltInTaskOptions, s as SurveyAssistantTaskModelResolutionInput, t as CreateSurveyAssistantTaskAgentOptions, u as runSurveyAssistantSuggestItemLabelTask } from "./tasks-
|
|
1
|
+
import { a as SurveyAssistantTaskAuthorizationInput, c as createSurveyAssistantTaskAgent, d as runSurveyAssistantSuggestResponseNameTask, f as runSurveyAssistantSuggestResponseSettingsTask, i as RunSurveyAssistantTaskOptions, l as createSurveyAssistantTaskHandler, m as runSurveyAssistantTranslateContentTask, n as CreateSurveyAssistantTaskHandlerOptions, o as SurveyAssistantTaskAuthorizedIdentity, p as runSurveyAssistantTask, r as RunSurveyAssistantBuiltInTaskOptions, s as SurveyAssistantTaskModelResolutionInput, t as CreateSurveyAssistantTaskAgentOptions, u as runSurveyAssistantSuggestItemLabelTask } from "./tasks-wb9M-bak.mjs";
|
|
2
2
|
export { CreateSurveyAssistantTaskAgentOptions, CreateSurveyAssistantTaskHandlerOptions, RunSurveyAssistantBuiltInTaskOptions, RunSurveyAssistantTaskOptions, SurveyAssistantTaskAuthorizationInput, SurveyAssistantTaskAuthorizedIdentity, SurveyAssistantTaskModelResolutionInput, createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantSuggestResponseNameTask, runSurveyAssistantSuggestResponseSettingsTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
|
package/dist/server-tasks.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as runSurveyAssistantSuggestResponseSettingsTask, i as runSurveyAssistantSuggestResponseNameTask, n as createSurveyAssistantTaskHandler, o as runSurveyAssistantTask, r as runSurveyAssistantSuggestItemLabelTask, s as runSurveyAssistantTranslateContentTask, t as createSurveyAssistantTaskAgent } from "./tasks-
|
|
1
|
+
import { a as runSurveyAssistantSuggestResponseSettingsTask, i as runSurveyAssistantSuggestResponseNameTask, n as createSurveyAssistantTaskHandler, o as runSurveyAssistantTask, r as runSurveyAssistantSuggestItemLabelTask, s as runSurveyAssistantTranslateContentTask, t as createSurveyAssistantTaskAgent } from "./tasks-Coh5N027.mjs";
|
|
2
2
|
export { createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantSuggestResponseNameTask, runSurveyAssistantSuggestResponseSettingsTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
|
package/dist/server-tools.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-
|
|
1
|
+
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-CeUlGkoU.mjs";
|
|
2
2
|
export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
|
package/dist/server-tools.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-
|
|
1
|
+
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-D0KBDolR.mjs";
|
|
2
2
|
export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
|
package/dist/server.d.mts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import "./index-
|
|
2
|
-
import { p as SurveyAssistantTurnTerminationReason } from "./lifecycle-
|
|
3
|
-
import {
|
|
1
|
+
import "./index-DYHdvSE8.mjs";
|
|
2
|
+
import { p as SurveyAssistantTurnTerminationReason } from "./lifecycle-DFzxVxpq.mjs";
|
|
3
|
+
import { n as TurnSurveyDraft } from "./turn-survey-draft-B34lggSG.mjs";
|
|
4
|
+
import "./index-CaX3hZmr.mjs";
|
|
4
5
|
import { C as SurveyAssistantRequestLimits, S as SurveyAssistantRequestError, T as validateSurveyAssistantMessages, _ as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, a as SurveyAssistantThreadDocumentContent, b as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, c as loadSurveyAssistantDocuments, d as removeHistoricalSurveyAssistantAttachments, f as replaceCurrentSurveyAssistantAttachmentsWithReferences, g as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, h as SURVEY_ASSISTANT_MAX_ATTACHMENTS, i as SurveyAssistantThreadDocument, l as loadSurveyAssistantThreadAttachments, m as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, n as SurveyAssistantLoadedDocument, o as SurveyAssistantThreadDocumentRepository, p as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, r as SurveyAssistantModelAttachment, s as getSurveyAssistantReplayableDocuments, t as SurveyAssistantAttachmentAccess, u as registerSurveyAssistantThreadAttachments, v as SURVEY_ASSISTANT_MAX_MESSAGES, w as readSurveyAssistantRequestJson, x as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, y as SURVEY_ASSISTANT_MAX_REQUEST_BYTES } from "./thread-documents-DrHbaXqP.mjs";
|
|
5
|
-
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-
|
|
6
|
-
import { _ as describeSurveyAssistantStreamError, a as SurveyAssistantThreadRepository, c as SurveyAssistantAuthorizationInput, d as SurveyAssistantChatHandlerOptions, f as SurveyAssistantModelResolutionInput, g as createSurveyAssistantChatHandler, h as SurveyAssistantTurnMetrics, i as SurveyAssistantThreadIdentity, l as SurveyAssistantAuthorize, m as SurveyAssistantStreamErrorContext, n as SurveyAssistantStoredThread, o as createSurveyAssistantThreadHandlers, p as SurveyAssistantResolveModel, r as SurveyAssistantThreadErrorContext, s as SurveyAssistantAuthorizationError, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantAuthorizedIdentity, v as formatSurveyAssistantStreamError } from "./thread-handlers-
|
|
7
|
-
import { _ as surveyAuthoringReferenceTopics, a as SurveyAssistantTaskAuthorizationInput, g as formatSurveyAuthoringReferenceRoutingInstructions, h as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity, v as surveyAuthoringReferences } from "./tasks-
|
|
6
|
+
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-HL_klgJl.mjs";
|
|
7
|
+
import { _ as describeSurveyAssistantStreamError, a as SurveyAssistantThreadRepository, c as SurveyAssistantAuthorizationInput, d as SurveyAssistantChatHandlerOptions, f as SurveyAssistantModelResolutionInput, g as createSurveyAssistantChatHandler, h as SurveyAssistantTurnMetrics, i as SurveyAssistantThreadIdentity, l as SurveyAssistantAuthorize, m as SurveyAssistantStreamErrorContext, n as SurveyAssistantStoredThread, o as createSurveyAssistantThreadHandlers, p as SurveyAssistantResolveModel, r as SurveyAssistantThreadErrorContext, s as SurveyAssistantAuthorizationError, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantAuthorizedIdentity, v as formatSurveyAssistantStreamError } from "./thread-handlers-C3Iya92v.mjs";
|
|
8
|
+
import { _ as surveyAuthoringReferenceTopics, a as SurveyAssistantTaskAuthorizationInput, g as formatSurveyAuthoringReferenceRoutingInstructions, h as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity, v as surveyAuthoringReferences } from "./tasks-wb9M-bak.mjs";
|
|
8
9
|
import { UIMessageChunk } from "ai";
|
|
9
10
|
import { MastraMemory } from "@mastra/core/memory";
|
|
10
11
|
//#region src/server/memory-thread-repository.d.ts
|
package/dist/server.d.mts.map
CHANGED
|
@@ -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":"
|
|
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,eAAe,KAClB;UAIe;EACf,aAAa,eAAe,QAAQ;;EAEpC;;EAEA;EACA,kBAAkB;;qBAGP,uCAAsC,WAAA,0BAAA,mBAAA,mBAKhD,8CAA4C;;;qBCTlC;KAER,wBAAwB,KAC3B;UAIe;EACf,aAAa,wBAAwB,QAAQ;;EAE7C,cAAc;;;;;EAKd,eAAe;;;;;EAKf,iBAAiB;;UAGF;EACf;;EAEA;;UAGe;EACf;EACA;;KAGU,2CAA2C;UAEtC;EACf;EACA;EACA;;UAGe;;EAEf,eAAe;;EAEf,cACE,OAAO,wCACN;;EAEH,iBAAiB,QAAQ;;EAEzB,WACE,QAAQ,iDACP,UAAU;;EAEb,YAAY;EACZ;EACA;;EAEA,gBAAgB;;UAGD;;EAEf,eAAe,qBAAqB,QAAQ;;EAE5C,aAAa,mBAAmB,QAAQ;EACxC,oBACE,OAAO,0CACN,QAAQ;EACX,UAAU,kBAAkB,qBAAqB;;qBAmCtC,8CAA6C,eAAA;EAIxD,eAAe;EACf;MACE;;;;;;;qBAcS,yCAAwC,WAAA,cAAA,eAAA,mBAKlD,gDAA8C;;;UCnIhC;EACf,QAAQ,eAAe;EACvB,WAAW;EACX,SAAS;EACT,qBAAqB;EACrB;EACA;EACA;EACA,kCAAkC;EAClC;;qBAqBW,oCAAmC,WAAA,mBAAA,2BAAA,YAAA,WAAA,mBAAA,QAAA,QAAA,iBAU7C,qCAAmC,eAAe"}
|
package/dist/server.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-Ct-vv9cu.mjs";
|
|
2
|
-
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-
|
|
3
|
-
import { a as parseSurveyAssistantPreviousSettledVersion, i as parseSurveyAssistantPreviousApplyOutcome, n as deriveSurveyAssistantDocumentTransition, o as parseSurveyAssistantSnapshot, s as requireSurveyAssistantTurnState, t as buildSurveyAssistantRequestContext } from "./request-context-
|
|
2
|
+
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-DmLadygY.mjs";
|
|
3
|
+
import { a as parseSurveyAssistantPreviousSettledVersion, i as parseSurveyAssistantPreviousApplyOutcome, n as deriveSurveyAssistantDocumentTransition, o as parseSurveyAssistantSnapshot, s as requireSurveyAssistantTurnState, t as buildSurveyAssistantRequestContext } from "./request-context-KVh8VjgH.mjs";
|
|
4
4
|
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-C0ugBOp0.mjs";
|
|
5
|
-
import { a as surveyAuthoringReferences, i as surveyAuthoringReferenceTopics, n as formatSurveyAuthoringReferenceRoutingInstructions } from "./authoring-references-
|
|
5
|
+
import { a as surveyAuthoringReferences, i as surveyAuthoringReferenceTopics, n as formatSurveyAuthoringReferenceRoutingInstructions } from "./authoring-references-CmwLc_C8.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,10 +1,11 @@
|
|
|
1
|
-
import { D as surveyAssistantTaskRequestSchema, S as surveyAssistantSuggestResponseSettingsResultSchema
|
|
1
|
+
import { D as surveyAssistantTaskRequestSchema, S as surveyAssistantSuggestResponseSettingsResultSchema } from "./protocol-BQ7uIDYT.mjs";
|
|
2
|
+
import { U as responseExportSettingsSchema } from "./capabilities-D55dq-fO.mjs";
|
|
2
3
|
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID } from "./constants-Ct-vv9cu.mjs";
|
|
3
4
|
import { d as readSurveyAssistantRequestJson, u as SurveyAssistantRequestError } from "./request-guardrails-C0ugBOp0.mjs";
|
|
4
|
-
import { a as surveyAuthoringReferences } from "./authoring-references-
|
|
5
|
+
import { a as surveyAuthoringReferences } from "./authoring-references-CmwLc_C8.mjs";
|
|
5
6
|
import { n as FAIR_ITEM_KEY_RULES_TEXT } from "./fair-guidance-BmO4PswW.mjs";
|
|
6
7
|
import { z } from "zod";
|
|
7
|
-
import { isValidResponseVariableName } from "@case-framework/survey-core";
|
|
8
|
+
import { isValidResponseVariableName, ownValue, setOwnValue, strictKeyedObject } from "@case-framework/survey-core";
|
|
8
9
|
import { RequestContext } from "@mastra/core/request-context";
|
|
9
10
|
import { Agent } from "@mastra/core/agent";
|
|
10
11
|
//#region src/server/response-settings-output.ts
|
|
@@ -30,7 +31,7 @@ const createResponseSettingsGenerationSchema = (compact = false) => {
|
|
|
30
31
|
slotId: z.string().min(1),
|
|
31
32
|
variableName: name
|
|
32
33
|
}).strict(), z.object({
|
|
33
|
-
|
|
34
|
+
elementId: z.string().min(1),
|
|
34
35
|
prefix: name.nullable().optional(),
|
|
35
36
|
rows: components,
|
|
36
37
|
columns: components
|
|
@@ -50,7 +51,7 @@ const entryMap = (values) => {
|
|
|
50
51
|
};
|
|
51
52
|
const decodeResponseSettingsGeneration = (result) => surveyAssistantSuggestResponseSettingsResultSchema.parse({
|
|
52
53
|
naming: result.naming.map((edit) => "slotId" in edit ? edit : {
|
|
53
|
-
|
|
54
|
+
elementId: edit.elementId,
|
|
54
55
|
prefix: edit.prefix ?? void 0,
|
|
55
56
|
rows: entryMap(edit.rows),
|
|
56
57
|
columns: entryMap(edit.columns)
|
|
@@ -210,8 +211,8 @@ const runSurveyAssistantSuggestResponseSettingsTask = async (input, options) =>
|
|
|
210
211
|
const slots = options.context.responseVariables ?? [];
|
|
211
212
|
const selected = slots.filter((slot) => input.slotIds.includes(String(slot.slotId)));
|
|
212
213
|
if (input.slotIds.some((id) => !selected.some((slot) => slot.slotId === id))) throw new Error("The selected response variables are absent from task context.");
|
|
213
|
-
const matrixIds = new Set(selected.filter((slot) => slot.naming?.kind === "matrix").map((slot) => slot.
|
|
214
|
-
const allowed = new Set(slots.filter((slot) => input.slotIds.includes(String(slot.slotId)) || matrixIds.has(slot.
|
|
214
|
+
const matrixIds = new Set(selected.filter((slot) => slot.naming?.kind === "matrix").map((slot) => slot.elementId));
|
|
215
|
+
const allowed = new Set(slots.filter((slot) => input.slotIds.includes(String(slot.slotId)) || matrixIds.has(slot.elementId)).map((slot) => slot.slotId));
|
|
215
216
|
const generated = await runSurveyAssistantTask({
|
|
216
217
|
...options,
|
|
217
218
|
taskId: "suggest-response-settings",
|
|
@@ -222,7 +223,7 @@ const runSurveyAssistantSuggestResponseSettingsTask = async (input, options) =>
|
|
|
222
223
|
"In this structured result, rows, columns, optionCodes and optionLabels are arrays of {id,value} entries, not dictionaries. Use exact existing row/column/option IDs. Omit unchanged fields (or use null); use empty arrays for no edits. The authoring references show the canonical operation format; the application converts these entry arrays to that format.",
|
|
223
224
|
`The requested style is ${input.category}. For compact, use recognizable 2-5 character lowercase abbreviations for scalar names and each matrix prefix/row/column component; derived full matrix names may be longer. For survey-pattern, follow other authored variable names; fall back to FAIR only when no pattern exists. For preferred, prioritize clear useful names. FAIR direction: ${FAIR_ITEM_KEY_RULES_TEXT}. All categories obey the shared syntax and 32-character full-name limit.`,
|
|
224
225
|
"Use the exact slot-specific field/row/column content, value type, units, option labels, and supplied instrument metadata. Never infer a value's meaning from the composite item's dominant topic alone. Existing names from other variables provide naming-pattern evidence; the selected variable's placeholder does not.",
|
|
225
|
-
"For scalars use {slotId,variableName}. For matrices use {
|
|
226
|
+
"For scalars use {slotId,variableName}. For matrices use {elementId,prefix,rows,columns} with the exact row and column IDs. Matrix cells and computed names are derived; never rename an individual matrix slot. Preview all affected family names mentally against existingVariableNames, including names of unselected variables. A selected matrix member permits component edits affecting that entire matrix family.",
|
|
226
227
|
"Option IDs, export codes, labels, and numeric scores are separate. Suggest stable meaningful optionCodes indexed by existing option IDs, preserve supplied instrument/standard codes and scores, and never invent IDs or standards. Shared matrix/dropdown option codes affect all slots that reuse those options.",
|
|
227
228
|
"Only change selected scalars or selected matrix families. Use settings for optionCodes and explicit export settings when needed, otherwise leave settings empty. Do not invent missing-value sentinels. Preserve false, zero, empty selection and missing as distinct values.",
|
|
228
229
|
"Avoid changing already meaningful codes without a clear reason. The editor validates survey-wide uniqueness and projected headers and presents a before/after preview before applying one undoable change."
|
|
@@ -230,7 +231,7 @@ const runSurveyAssistantSuggestResponseSettingsTask = async (input, options) =>
|
|
|
230
231
|
referenceTopics: ["fair-by-design", "response-variables"]
|
|
231
232
|
});
|
|
232
233
|
const result = decodeResponseSettingsGeneration(generated);
|
|
233
|
-
if (result.naming.some((edit) => "slotId" in edit ? !allowed.has(edit.slotId) || (slots.find((slot) => slot.slotId === edit.slotId)?.naming)?.kind === "matrix" : !matrixIds.has(edit.
|
|
234
|
+
if (result.naming.some((edit) => "slotId" in edit ? !allowed.has(edit.slotId) || (slots.find((slot) => slot.slotId === edit.slotId)?.naming)?.kind === "matrix" : !matrixIds.has(edit.elementId)) || result.settings.some((edit) => !allowed.has(edit.slotId))) throw new Error("The suggestion targets variables outside the requested scope or directly names a derived matrix cell.");
|
|
234
235
|
return result;
|
|
235
236
|
};
|
|
236
237
|
const runSurveyAssistantSuggestItemLabelTask = async (input, options) => {
|
|
@@ -273,7 +274,7 @@ const runSurveyAssistantTranslateContentTask = async (input, options) => {
|
|
|
273
274
|
...options,
|
|
274
275
|
taskId: "translate-content",
|
|
275
276
|
input,
|
|
276
|
-
schema: z.
|
|
277
|
+
schema: z.strictObject({ translations: strictKeyedObject(Object.fromEntries(input.targetLocales.map((locale) => [locale, strictKeyedObject(Object.fromEntries(input.entries.map((entry) => [entry.id, z.string()])))]))) }),
|
|
277
278
|
instructions: [
|
|
278
279
|
"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.",
|
|
279
280
|
`Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(", ")}.`,
|
|
@@ -287,18 +288,18 @@ const runSurveyAssistantTranslateContentTask = async (input, options) => {
|
|
|
287
288
|
});
|
|
288
289
|
const translations = {};
|
|
289
290
|
for (const locale of input.targetLocales) {
|
|
290
|
-
const entries = result.translations
|
|
291
|
+
const entries = ownValue(result.translations, locale);
|
|
291
292
|
if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);
|
|
292
293
|
const translatedEntries = {};
|
|
293
294
|
for (const entry of input.entries) {
|
|
294
|
-
const translation = entries
|
|
295
|
+
const translation = ownValue(entries, entry.id);
|
|
295
296
|
if (typeof translation !== "string" || translation.trim().length === 0) throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);
|
|
296
297
|
const sourceTokens = getProtectedTokens(entry.text).sort();
|
|
297
298
|
const translatedTokens = getProtectedTokens(translation).sort();
|
|
298
299
|
if (sourceTokens.join("\0") !== translatedTokens.join("\0")) throw new Error(`Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`);
|
|
299
|
-
translatedEntries
|
|
300
|
+
setOwnValue(translatedEntries, entry.id, translation);
|
|
300
301
|
}
|
|
301
|
-
translations
|
|
302
|
+
setOwnValue(translations, locale, translatedEntries);
|
|
302
303
|
}
|
|
303
304
|
return { translations };
|
|
304
305
|
};
|
|
@@ -393,4 +394,4 @@ const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError,
|
|
|
393
394
|
//#endregion
|
|
394
395
|
export { runSurveyAssistantSuggestResponseSettingsTask as a, runSurveyAssistantSuggestResponseNameTask as i, createSurveyAssistantTaskHandler as n, runSurveyAssistantTask as o, runSurveyAssistantSuggestItemLabelTask as r, runSurveyAssistantTranslateContentTask as s, createSurveyAssistantTaskAgent as t };
|
|
395
396
|
|
|
396
|
-
//# sourceMappingURL=tasks-
|
|
397
|
+
//# sourceMappingURL=tasks-Coh5N027.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tasks-Coh5N027.mjs","names":[],"sources":["../src/server/response-settings-output.ts","../src/server/tasks.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { responseExportSettingsSchema } from \"../protocol/response-settings\";\nimport { surveyAssistantSuggestResponseSettingsResultSchema } from \"../protocol/tasks\";\n\n// Structured-output providers require closed objects. Represent dictionaries as\n// entries on the generation boundary, then validate the normal editor contract.\nconst entries = z.array(z.object({ id: z.string().min(1), value: z.string() }).strict());\nconst optionalEntries = entries.nullable().optional();\nconst exportSettings = responseExportSettingsSchema\n .omit({ optionCodes: true, optionLabels: true })\n .extend({ optionCodes: optionalEntries, optionLabels: optionalEntries });\n\nexport const createResponseSettingsGenerationSchema = (compact = false) => {\n const name = compact\n ? z\n .string()\n .min(2)\n .max(5)\n .regex(/^[a-z][a-z0-9]{1,4}$/)\n : z.string().min(1);\n const components = z\n .array(z.object({ id: z.string().min(1), value: name }).strict())\n .nullable()\n .optional();\n return z\n .object({\n naming: z\n .array(\n z.union([\n z.object({ slotId: z.string().min(1), variableName: name }).strict(),\n z\n .object({\n elementId: z.string().min(1),\n prefix: name.nullable().optional(),\n rows: components,\n columns: components,\n })\n .strict(),\n ]),\n )\n .max(200),\n settings: z\n .array(\n z\n .object({\n slotId: z.string().min(1),\n optionCodes: optionalEntries,\n exportSettings: exportSettings.nullable().optional(),\n })\n .strict(),\n )\n .max(200),\n })\n .strict();\n};\nexport const responseSettingsGenerationSchema = createResponseSettingsGenerationSchema();\n\nconst entryMap = (values: z.infer<typeof optionalEntries>) => {\n if (!values) return undefined;\n if (new Set(values.map((entry) => entry.id)).size !== values.length)\n throw new Error(\"A coding suggestion repeats the same component or option ID.\");\n return Object.fromEntries(values.map(({ id, value }) => [id, value]));\n};\n\nexport const decodeResponseSettingsGeneration = (\n result: z.infer<typeof responseSettingsGenerationSchema>,\n) =>\n surveyAssistantSuggestResponseSettingsResultSchema.parse({\n naming: result.naming.map((edit) =>\n \"slotId\" in edit\n ? edit\n : {\n elementId: edit.elementId,\n prefix: edit.prefix ?? undefined,\n rows: entryMap(edit.rows),\n columns: entryMap(edit.columns),\n },\n ),\n settings: result.settings.map((edit) => ({\n slotId: edit.slotId,\n optionCodes: entryMap(edit.optionCodes),\n exportSettings: edit.exportSettings\n ? {\n ...edit.exportSettings,\n optionCodes: entryMap(edit.exportSettings.optionCodes),\n optionLabels: entryMap(edit.exportSettings.optionLabels),\n }\n : undefined,\n })),\n });\n","import { type SurveyAssistantSuggestResponseSettingsInput } from \"../protocol/tasks\";\nimport {\n createResponseSettingsGenerationSchema,\n decodeResponseSettingsGeneration,\n} from \"./response-settings-output\";\nimport {\n isValidResponseVariableName,\n ownValue,\n setOwnValue,\n strictKeyedObject,\n} from \"@case-framework/survey-core\";\nimport { 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 SurveyAssistantSuggestResponseNameInput,\n SurveyAssistantSuggestResponseNameResult,\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 lowercase 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\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: SurveyAssistantSuggestResponseNameInput,\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.currentName, input.draftName]\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 runSurveyAssistantSuggestResponseNameTask = async (\n input: SurveyAssistantSuggestResponseNameInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestResponseNameResult> => {\n const slot = options.context.responseVariables?.find(\n (slot) => slot.slotId === input.slotId && slot.itemId === input.itemId,\n );\n if (!slot) throw new Error(\"The selected response variable is absent from task context.\");\n if ((slot.naming as { kind?: string } | undefined)?.kind === \"matrix\")\n throw new Error(\n \"Matrix names are derived; request response-settings suggestions for the matrix family.\",\n );\n const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-response-name\",\n input,\n schema: keySuggestionSchema,\n instructions: [\n \"Suggest names for the exact response variable identified by input.slotId. Item editor names are separate from response variable names.\",\n \"Use currentSurveyContext.responseVariables and responseOwners for the slot's field label, help, units, value type, raw/computed status, matrix row/column meaning, option codes, and supplied instrument metadata. Do not name every field after its composite item's dominant topic.\",\n \"Infer conventions only from other variables in naming.keyExamples and existingVariableNames. The focused variable's current or draft placeholder is not evidence of a pattern.\",\n \"Return surveyPattern, compact, preferred and fair alternatives. All must use valid lowercase snake_case, start with a letter and have at most 32 characters. Compact means a recognizable 2-5 character lowercase abbreviation.\",\n `FAIR direction: ${FAIR_ITEM_KEY_RULES_TEXT}. These are project conventions supporting FAIR, not syntax mandated by FAIR. If no meaningful survey convention exists, prefer this direction. Preserve supplied instrument codes without inventing standards.`,\n \"Matrix variables are derived. Do not propose per-cell names; use suggest-response-settings for matrix coding components.\",\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 name, an existing variable name, 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.currentName, ...input.existingNames, ...(options.context.existingVariableNames ?? [])]\n .map(getCodingKeyIdentity)\n .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 = suggestion.text.trim();\n const identity = getCodingKeyIdentity(text);\n if (\n !isValidResponseVariableName(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 runSurveyAssistantSuggestResponseSettingsTask = async (\n input: SurveyAssistantSuggestResponseSettingsInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n) => {\n const slots = options.context.responseVariables ?? [];\n const selected = slots.filter((slot) => input.slotIds.includes(String(slot.slotId)));\n if (input.slotIds.some((id) => !selected.some((slot) => slot.slotId === id)))\n throw new Error(\"The selected response variables are absent from task context.\");\n const matrixIds = new Set(\n selected\n .filter((slot) => (slot.naming as { kind?: string } | undefined)?.kind === \"matrix\")\n .map((slot) => slot.elementId),\n );\n const allowed = new Set(\n slots\n .filter(\n (slot) => input.slotIds.includes(String(slot.slotId)) || matrixIds.has(slot.elementId),\n )\n .map((slot) => slot.slotId),\n );\n const generated = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-response-settings\",\n input,\n schema: createResponseSettingsGenerationSchema(input.category === \"compact\"),\n instructions: [\n \"Suggest coherent response coding for the selected persistent slot IDs. Return naming and settings edits only; nothing has been applied.\",\n \"In this structured result, rows, columns, optionCodes and optionLabels are arrays of {id,value} entries, not dictionaries. Use exact existing row/column/option IDs. Omit unchanged fields (or use null); use empty arrays for no edits. The authoring references show the canonical operation format; the application converts these entry arrays to that format.\",\n `The requested style is ${input.category}. For compact, use recognizable 2-5 character lowercase abbreviations for scalar names and each matrix prefix/row/column component; derived full matrix names may be longer. For survey-pattern, follow other authored variable names; fall back to FAIR only when no pattern exists. For preferred, prioritize clear useful names. FAIR direction: ${FAIR_ITEM_KEY_RULES_TEXT}. All categories obey the shared syntax and 32-character full-name limit.`,\n \"Use the exact slot-specific field/row/column content, value type, units, option labels, and supplied instrument metadata. Never infer a value's meaning from the composite item's dominant topic alone. Existing names from other variables provide naming-pattern evidence; the selected variable's placeholder does not.\",\n \"For scalars use {slotId,variableName}. For matrices use {elementId,prefix,rows,columns} with the exact row and column IDs. Matrix cells and computed names are derived; never rename an individual matrix slot. Preview all affected family names mentally against existingVariableNames, including names of unselected variables. A selected matrix member permits component edits affecting that entire matrix family.\",\n \"Option IDs, export codes, labels, and numeric scores are separate. Suggest stable meaningful optionCodes indexed by existing option IDs, preserve supplied instrument/standard codes and scores, and never invent IDs or standards. Shared matrix/dropdown option codes affect all slots that reuse those options.\",\n \"Only change selected scalars or selected matrix families. Use settings for optionCodes and explicit export settings when needed, otherwise leave settings empty. Do not invent missing-value sentinels. Preserve false, zero, empty selection and missing as distinct values.\",\n \"Avoid changing already meaningful codes without a clear reason. The editor validates survey-wide uniqueness and projected headers and presents a before/after preview before applying one undoable change.\",\n ],\n referenceTopics: [\"fair-by-design\", \"response-variables\"],\n });\n const result = decodeResponseSettingsGeneration(generated);\n if (\n result.naming.some((edit) =>\n \"slotId\" in edit\n ? !allowed.has(edit.slotId) ||\n (\n slots.find((slot) => slot.slotId === edit.slotId)?.naming as\n | { kind?: string }\n | undefined\n )?.kind === \"matrix\"\n : !matrixIds.has(edit.elementId),\n ) ||\n result.settings.some((edit) => !allowed.has(edit.slotId))\n )\n throw new Error(\n \"The suggestion targets variables outside the requested scope or directly names a derived matrix cell.\",\n );\n return result;\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: z.strictObject({\n translations: strictKeyedObject(\n Object.fromEntries(\n input.targetLocales.map((locale) => [\n locale,\n strictKeyedObject(\n Object.fromEntries(input.entries.map((entry) => [entry.id, z.string()])),\n ),\n ]),\n ),\n ),\n }),\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 = ownValue(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 = ownValue(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 setOwnValue(translatedEntries, entry.id, translation);\n }\n setOwnValue(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-response-settings\"\n ? await runSurveyAssistantSuggestResponseSettingsTask(task.input, runtime)\n : task.taskId === \"suggest-response-name\"\n ? await runSurveyAssistantSuggestResponseNameTask(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":";;;;;;;;;;;AAOA,MAAM,kBADU,EAAE,MAAM,EAAE,OAAO;CAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAAG,OAAO,EAAE,OAAO;AAAE,CAAC,CAAC,CAAC,OAAO,CACxD,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;AACpD,MAAM,iBAAiB,6BACpB,KAAK;CAAE,aAAa;CAAM,cAAc;AAAK,CAAC,CAAC,CAC/C,OAAO;CAAE,aAAa;CAAiB,cAAc;AAAgB,CAAC;AAEzE,MAAa,0CAA0C,UAAU,UAAU;CACzE,MAAM,OAAO,UACT,EACG,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,CAAC,CAAC,CACN,MAAM,sBAAsB,IAC/B,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACpB,MAAM,aAAa,EAChB,MAAM,EAAE,OAAO;EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EAAG,OAAO;CAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAChE,SAAS,CAAC,CACV,SAAS;CACZ,OAAO,EACJ,OAAO;EACN,QAAQ,EACL,MACC,EAAE,MAAM,CACN,EAAE,OAAO;GAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;GAAG,cAAc;EAAK,CAAC,CAAC,CAAC,OAAO,GACnE,EACG,OAAO;GACN,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