@case-framework/survey-assistant 0.5.0 → 0.7.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/README.md +9 -4
- package/dist/attachments-B0hg3vpT.mjs +11 -0
- package/dist/attachments-B0hg3vpT.mjs.map +1 -0
- package/dist/authoring-references-BJQ_1nMX.mjs +115 -0
- package/dist/authoring-references-BJQ_1nMX.mjs.map +1 -0
- package/dist/capabilities-1KNnNO1_.mjs +73 -0
- package/dist/capabilities-1KNnNO1_.mjs.map +1 -0
- package/dist/{capabilities-CnsVuJ1k.d.mts → capabilities-DVTfogjv.d.mts} +1 -1
- package/dist/{capabilities-CnsVuJ1k.d.mts.map → capabilities-DVTfogjv.d.mts.map} +1 -1
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +47 -20
- package/dist/capabilities-default.mjs.map +1 -1
- package/dist/{constants-CFUWrRtl.mjs → constants-0UHGFcRJ.mjs} +1 -1
- package/dist/{constants-CFUWrRtl.mjs.map → constants-0UHGFcRJ.mjs.map} +1 -1
- package/dist/{constants-DbrJxxOh.d.mts → constants-Be91Gay9.d.mts} +4 -4
- package/dist/{constants-DbrJxxOh.d.mts.map → constants-Be91Gay9.d.mts.map} +1 -1
- package/dist/{controller-proxy-jWIPOZAv.mjs → controller-proxy-BH05e-C2.mjs} +21 -8
- package/dist/controller-proxy-BH05e-C2.mjs.map +1 -0
- package/dist/{controller-proxy-BdKF2yrq.d.mts → controller-proxy-Bd0ZHBPF.d.mts} +11 -11
- package/dist/controller-proxy-Bd0ZHBPF.d.mts.map +1 -0
- package/dist/{digest-Dyjch_sC.d.mts → digest-SJmoYVaK.d.mts} +2 -2
- package/dist/{digest-Dyjch_sC.d.mts.map → digest-SJmoYVaK.d.mts.map} +1 -1
- package/dist/digest.d.mts +1 -1
- package/dist/{engine-DcSdLRle.mjs → engine-Bo85Oyj0.mjs} +3129 -2435
- package/dist/engine-Bo85Oyj0.mjs.map +1 -0
- package/dist/engine.d.mts +3 -3
- package/dist/engine.mjs +3 -3
- package/dist/{fair-guidance-CEdJYccK.mjs → fair-guidance-CRYCRxQm.mjs} +1 -1
- package/dist/{fair-guidance-CEdJYccK.mjs.map → fair-guidance-CRYCRxQm.mjs.map} +1 -1
- package/dist/{index-Da_Hb9-1.d.mts → index-Tnqv-yKW.d.mts} +73 -67
- package/dist/index-Tnqv-yKW.d.mts.map +1 -0
- package/dist/index-l_EK4yK7.d.mts +404 -0
- package/dist/index-l_EK4yK7.d.mts.map +1 -0
- package/dist/{index-BApnIiCI.d.mts → index-nhrgbgO5.d.mts} +24 -5
- package/dist/index-nhrgbgO5.d.mts.map +1 -0
- package/dist/{index-DhNQKOwr.d.mts → index-x0qprHgK.d.mts} +19 -7
- package/dist/index-x0qprHgK.d.mts.map +1 -0
- package/dist/{lifecycle-DWv5CiSu.d.mts → lifecycle-Bx0aq_4S.d.mts} +8 -2
- package/dist/{lifecycle-DWv5CiSu.d.mts.map → lifecycle-Bx0aq_4S.d.mts.map} +1 -1
- package/dist/{memory-thread-repository-CvYZwni6.mjs → memory-thread-repository-KWHQWFEW.mjs} +45 -14
- package/dist/memory-thread-repository-KWHQWFEW.mjs.map +1 -0
- package/dist/{protocol-DJUP4gc0.mjs → protocol-BhzQbx81.mjs} +66 -16
- package/dist/protocol-BhzQbx81.mjs.map +1 -0
- package/dist/protocol.d.mts +4 -4
- package/dist/protocol.mjs +3 -2
- package/dist/react-B3ybjJ-X.mjs +1620 -0
- package/dist/react-B3ybjJ-X.mjs.map +1 -0
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +3 -3
- package/dist/react.mjs +3 -3
- package/dist/references/assistant-operations.md +45 -39
- package/dist/references/expressions.md +28 -0
- package/dist/references/item-types.md +1 -1
- package/dist/references/localization.md +5 -4
- package/dist/references/rich-text-content.md +60 -27
- package/dist/references/source-material-surveys.md +9 -2
- package/dist/references/survey-data-model.md +9 -1
- package/dist/{request-context-D1sC54ZA.mjs → request-context-CG4SWijt.mjs} +3 -3
- package/dist/{request-context-D1sC54ZA.mjs.map → request-context-CG4SWijt.mjs.map} +1 -1
- package/dist/{request-guardrails-h4t6u8mP.mjs → request-guardrails-TmgQtqp4.mjs} +5 -12
- package/dist/request-guardrails-TmgQtqp4.mjs.map +1 -0
- package/dist/server-agent.d.mts +19 -8
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +11 -13
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +12 -6
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +9 -4
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +5 -5
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +7 -7
- package/dist/server.mjs +6 -6
- package/dist/storage-postgres.d.mts +1 -1
- package/dist/storage-postgres.mjs +1 -1
- package/dist/{tasks-CCtxjhwh.d.mts → tasks-CYqrcaRO.d.mts} +16 -4
- package/dist/tasks-CYqrcaRO.d.mts.map +1 -0
- package/dist/{thread-documents-Dvo6XS7o.d.mts → thread-documents-rmd6nyX9.d.mts} +1 -1
- package/dist/{thread-documents-Dvo6XS7o.d.mts.map → thread-documents-rmd6nyX9.d.mts.map} +1 -1
- package/dist/{thread-handlers-Bt9cDo-F.d.mts → thread-handlers-DBAaU7BA.d.mts} +7 -5
- package/dist/thread-handlers-DBAaU7BA.d.mts.map +1 -0
- package/dist/{tools-3tq-XqI0.mjs → tools-BvSovehT.mjs} +433 -495
- package/dist/tools-BvSovehT.mjs.map +1 -0
- package/dist/ui.css +1 -1
- package/dist/ui.d.mts +5 -4
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +744 -131
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +43 -3
- package/package.json +21 -19
- package/dist/authoring-references-yyYC4Ydi.mjs +0 -98
- package/dist/authoring-references-yyYC4Ydi.mjs.map +0 -1
- package/dist/controller-proxy-BdKF2yrq.d.mts.map +0 -1
- package/dist/controller-proxy-jWIPOZAv.mjs.map +0 -1
- package/dist/engine-DcSdLRle.mjs.map +0 -1
- package/dist/form-authoring-BQh40yDb.mjs +0 -155
- package/dist/form-authoring-BQh40yDb.mjs.map +0 -1
- package/dist/index-BApnIiCI.d.mts.map +0 -1
- package/dist/index-Da_Hb9-1.d.mts.map +0 -1
- package/dist/index-DhNQKOwr.d.mts.map +0 -1
- package/dist/index-dV6df0W3.d.mts +0 -224
- package/dist/index-dV6df0W3.d.mts.map +0 -1
- package/dist/memory-thread-repository-CvYZwni6.mjs.map +0 -1
- package/dist/protocol-DJUP4gc0.mjs.map +0 -1
- package/dist/react-CY6N7lVi.mjs +0 -768
- package/dist/react-CY6N7lVi.mjs.map +0 -1
- package/dist/request-guardrails-h4t6u8mP.mjs.map +0 -1
- package/dist/tasks-CCtxjhwh.d.mts.map +0 -1
- package/dist/thread-handlers-Bt9cDo-F.d.mts.map +0 -1
- package/dist/tools-3tq-XqI0.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools-BvSovehT.mjs","names":["isRecord","TOOL_ID","inputSchema","outputSchema","TOOL_ID","inputSchema","TOOL_ID","inputSchema","outputSchema","outlineModeSchema","inputSchema","outputSchema","inputSchema","outputSchema","inputSchema","outputSchema","isRecord","inputSchema","outputSchema","TOOL_ID","inputSchema","outputSchema","TOOL_ID","inputSchema","outputSchema","TOOL_ID","inputSchema","INSPECT_TOOL_ID","CHANGE_TOOL_ID","EXPRESSION_TOOL_ID","AUTHORING_REFERENCE_TOOL_ID","ATTACHMENT_TOOL_ID","AUDIT_TOOL_ID","ASSET_TOOL_ID"],"sources":["../src/server/operation-contract-reference.ts","../src/server/canonical-name-suggestions.ts","../src/server/tools/tool-model-output.ts","../src/server/tools/survey-authoring-reference-tool.ts","../src/server/tools/mutation-recovery.ts","../src/server/tools/survey-change-tool.ts","../src/server/tools/survey-expression-tool.ts","../src/server/tools/parse-inspection-output.ts","../src/server/tools/inspect-current-context.ts","../src/server/tools/inspect-item-details.ts","../src/server/tools/inspect-raw-survey.ts","../src/server/tools/search-survey-items.ts","../src/server/tools/survey-inspect-tool.ts","../src/server/tools/survey-attachment-tool.ts","../src/server/tools/survey-audit-tool.ts","../src/server/tools/survey-asset-tool.ts","../src/server/tools/index.ts"],"sourcesContent":["import {\n SURVEY_OPERATION_KINDS,\n type AssistantItemTypeManifest,\n type SurveyOperationKind,\n} from \"../protocol\";\nimport { surveyOperationSchemasByKind } from \"../protocol/operations\";\nimport { z } from \"zod\";\n\nexport const isSurveyOperationKind = (value: string): value is SurveyOperationKind =>\n (SURVEY_OPERATION_KINDS as readonly string[]).includes(value);\n\nexport const SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS = [\"compact\", \"full\"] as const;\nexport type SurveyOperationContractDetail =\n (typeof SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS)[number];\n\ntype JsonSchemaRecord = Record<string, unknown>;\n\nconst isRecord = (value: unknown): value is JsonSchemaRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst summarizeLargeSchema = (\n schema: JsonSchemaRecord,\n propertyName?: string,\n): JsonSchemaRecord => {\n const description =\n typeof schema.description === \"string\"\n ? schema.description\n : propertyName\n ? `Canonical value for \"${propertyName}\".`\n : \"Canonical value.\";\n const type = typeof schema.type === \"string\" ? schema.type : undefined;\n\n return {\n ...(type ? { type } : {}),\n description: `${description} The deeply nested schema is omitted from this compact reference; load the dedicated authoring reference when this structured value is needed.`,\n };\n};\n\nconst compactJsonSchema = (value: unknown, propertyName?: string, depth = 0): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => compactJsonSchema(entry, propertyName, depth + 1));\n }\n if (!isRecord(value)) {\n return value;\n }\n\n if (typeof value.$ref === \"string\") {\n return {\n description:\n \"Recursive structured value omitted from this compact reference; request full detail only for protocol debugging.\",\n };\n }\n\n if (depth >= 3 && JSON.stringify(value).length > 12_000) {\n return summarizeLargeSchema(value, propertyName);\n }\n\n const compact: JsonSchemaRecord = {};\n for (const key of [\n \"type\",\n \"const\",\n \"enum\",\n \"description\",\n \"minimum\",\n \"maximum\",\n \"minLength\",\n \"maxLength\",\n \"minItems\",\n \"maxItems\",\n \"required\",\n \"additionalProperties\",\n ]) {\n if (value[key] !== undefined) {\n compact[key] = value[key];\n }\n }\n\n if (isRecord(value.properties)) {\n compact.properties = Object.fromEntries(\n Object.entries(value.properties).map(([key, schema]) => [\n key,\n compactJsonSchema(schema, key, depth + 1),\n ]),\n );\n }\n if (value.items !== undefined) {\n compact.items = compactJsonSchema(value.items, propertyName, depth + 1);\n }\n for (const unionKey of [\"oneOf\", \"anyOf\"] as const) {\n if (Array.isArray(value[unionKey])) {\n compact[unionKey] = value[unionKey].map((entry) =>\n compactJsonSchema(entry, propertyName, depth + 1),\n );\n }\n }\n\n return compact;\n};\n\nexport const formatItemCapabilityProfile = (\n manifest: AssistantItemTypeManifest,\n kind?: SurveyOperationKind,\n): string => {\n const fixedSurfaces = manifest.contentSurfaces.filter((surface) => !surface.pattern);\n const patternedSurfaces = manifest.contentSurfaces.filter((surface) => surface.pattern);\n const requiredSurfaces = fixedSurfaces.filter((surface) => surface.requiredOnCreate);\n const lines = [\n `## Item capability: \\`${manifest.itemType}\\``,\n \"\",\n `${manifest.displayName}: ${manifest.description ?? \"No additional description.\"}`,\n `Creation mode: ${manifest.create}.`,\n `Supported operations: ${manifest.supportedOperations.join(\", \")}.`,\n manifest.authoring?.compactHint,\n manifest.authoring?.configSummary\n ? `Configuration: ${manifest.authoring.configSummary}`\n : undefined,\n manifest.creationPresets?.length\n ? `Available creation preset ids: ${manifest.creationPresets\n .map((preset) => `\\`${preset.id}\\``)\n .join(\", \")}. Use the server-trusted configuration guidance above for their semantics.`\n : undefined,\n fixedSurfaces.length > 0\n ? `Fixed content surfaces: ${fixedSurfaces\n .map((surface) => `${surface.key} (format=${surface.format})`)\n .join(\", \")}.`\n : \"Fixed content surfaces: none.\",\n patternedSurfaces.length > 0\n ? `Dynamic content surfaces: ${patternedSurfaces\n .map((surface) => `${surface.key} (format=${surface.format})`)\n .join(\", \")}.`\n : undefined,\n (!kind || kind === \"create-item\") && requiredSurfaces.length > 0\n ? `Required on creation: ${requiredSurfaces.map((surface) => surface.key).join(\", \")}.`\n : undefined,\n manifest.referenceTopics?.length\n ? `Load dedicated guidance with survey_authoring_reference using these exact arguments: ${manifest.referenceTopics.map((topic) => JSON.stringify({ topic, itemType: manifest.itemType })).join(\"; \")}.`\n : undefined,\n ].filter((line): line is string => Boolean(line));\n\n if (kind === \"create-item\") {\n lines.push(\n \"\",\n \"Creation scope: include the initial structure, configuration, and visible translations that are already known. A later successful mutation call in the same turn may target the created id; the server adds that delta to the validated turn draft.\",\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const formatSurveyOperationContractReference = (\n kind: SurveyOperationKind,\n options: {\n detail?: SurveyOperationContractDetail;\n itemCapability?: AssistantItemTypeManifest;\n } = {},\n): string => {\n const { $schema: _schemaVersion, ...contract } = z.toJSONSchema(\n surveyOperationSchemasByKind[kind],\n {\n io: \"input\",\n reused: \"inline\",\n unrepresentable: \"any\",\n },\n );\n const detail = options.detail ?? \"compact\";\n const renderedContract = detail === \"full\" ? contract : compactJsonSchema(contract);\n const itemCapability = options.itemCapability;\n\n return [\n `# \\`${kind}\\` operation contract`,\n \"\",\n \"This JSON Schema is generated from the structural validator used by `survey_change`; it is\",\n \"the canonical post-normalization field shape. Cross-field and snapshot-dependent rules are\",\n \"enforced when the proposal is validated. Follow focused authoring guidance when it recommends\",\n \"a supported model-facing shorthand; otherwise use this canonical shape.\",\n detail === \"compact\"\n ? 'This compact view preserves the operation structure while omitting deeply nested value schemas. Request detail \"full\" only for protocol debugging; load a focused rich-text, expression, form, or item-type reference for authoring guidance.'\n : \"This full view is intended for protocol debugging and may be large.\",\n \"\",\n \"```json\",\n JSON.stringify(renderedContract, null, 2),\n \"```\",\n ...(itemCapability ? [\"\", formatItemCapabilityProfile(itemCapability, kind)] : []),\n ].join(\"\\n\");\n};\n","const CANONICAL_ACTION_TOKENS: Readonly<Record<string, string>> = {\n add: \"create\",\n append: \"create\",\n create: \"create\",\n delete: \"remove\",\n edit: \"update\",\n insert: \"create\",\n modify: \"update\",\n patch: \"update\",\n relocate: \"move\",\n remove: \"remove\",\n reorder: \"reorder\",\n replace: \"update\",\n set: \"update\",\n sort: \"reorder\",\n update: \"update\",\n};\n\nconst tokenizeCanonicalName = (value: string) =>\n value\n .normalize(\"NFKD\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean)\n .map((token) => CANONICAL_ACTION_TOKENS[token] ?? token);\n\nconst editDistance = (left: string, right: string) => {\n const previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {\n current[rightIndex] = Math.min(\n (current[rightIndex - 1] ?? 0) + 1,\n (previous[rightIndex] ?? 0) + 1,\n (previous[rightIndex - 1] ?? 0) +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length] ?? 0;\n};\n\nconst scoreCanonicalName = (input: string, candidate: string) => {\n const inputTokens = tokenizeCanonicalName(input);\n const candidateTokens = tokenizeCanonicalName(candidate);\n const normalizedInput = inputTokens.join(\"-\");\n const normalizedCandidate = candidateTokens.join(\"-\");\n if (!normalizedInput || !normalizedCandidate) return 0;\n if (normalizedInput === normalizedCandidate) return 4;\n\n const maximumLength = Math.max(normalizedInput.length, normalizedCandidate.length);\n const similarity = 1 - editDistance(normalizedInput, normalizedCandidate) / maximumLength;\n const candidateTokenSet = new Set(candidateTokens);\n const sharedTokenCount = inputTokens.filter((token) => candidateTokenSet.has(token)).length;\n const tokenCoverage = sharedTokenCount / Math.max(inputTokens.length, candidateTokens.length);\n const sameFinalToken = inputTokens.at(-1) === candidateTokens.at(-1) ? 0.5 : 0;\n const sameFirstToken = inputTokens[0] === candidateTokens[0] ? 0.2 : 0;\n\n return similarity + tokenCoverage + sameFinalToken + sameFirstToken;\n};\n\n/** Suggests registry-derived canonical names without silently accepting an alias. */\nexport const suggestCanonicalNames = (\n input: string,\n candidates: readonly string[],\n limit = 3,\n) =>\n [...new Set(candidates)]\n .filter((candidate) => candidate !== input)\n .map((candidate) => ({ candidate, score: scoreCanonicalName(input, candidate) }))\n .filter((entry) => entry.score >= 0.9)\n .sort(\n (left, right) =>\n right.score - left.score || left.candidate.localeCompare(right.candidate),\n )\n .slice(0, Math.max(0, limit))\n .map((entry) => entry.candidate);\n","import { isValidationError } from \"@mastra/core/tools\";\n\nconst FALLBACK_MODEL_TEXT =\n \"The tool returned no model-readable output. Review the tool arguments and retry with valid values.\";\n\nexport const unwrapToolOutput = (value: unknown): unknown =>\n value && typeof value === \"object\" && \"output\" in value && value.output !== undefined\n ? value.output\n : value;\n\nexport const createTextModelOutput = (text: unknown) => ({\n type: \"content\" as const,\n value: [\n {\n type: \"text\" as const,\n text: typeof text === \"string\" && text.trim().length > 0 ? text : FALLBACK_MODEL_TEXT,\n },\n ],\n});\n\nexport const toTextModelOutput = <T>(value: unknown, summarize: (output: T) => unknown) => {\n const output = unwrapToolOutput(value);\n if (isValidationError(output)) {\n return createTextModelOutput(output.message);\n }\n\n try {\n return createTextModelOutput(summarize(output as T));\n } catch {\n return createTextModelOutput(undefined);\n }\n};\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport {\n builtInSurveyAuthoringItemTypes,\n getBuiltInItemTypeAuthoringReference,\n surveyAuthoringReferences,\n surveyAuthoringReferenceTopics,\n} from \"../authoring-references\";\nimport {\n resolveAssistantCapabilityReference,\n type SurveyAssistantEngineContext,\n} from \"../../engine\";\nimport {\n formatSurveyOperationContractReference,\n formatItemCapabilityProfile,\n isSurveyOperationKind,\n SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS,\n} from \"../operation-contract-reference\";\nimport { SURVEY_OPERATION_KINDS } from \"../../protocol\";\nimport { suggestCanonicalNames } from \"../canonical-name-suggestions\";\nimport { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_authoring_reference\";\n\nconst topicSchema = z.string().min(1).max(120);\n\nconst inputSchema = z.object({\n topic: topicSchema.describe(\"The narrow authoring reference to load.\"),\n itemType: z\n .string()\n .min(1)\n .max(120)\n .optional()\n .describe(\n 'Installed item type to focus. With topic \"item-types\", returns only that item type section instead of the combined reference.',\n ),\n operationKind: z\n .string()\n .min(1)\n .max(120)\n .optional()\n .describe(\n \"For topic assistant-operations, return only this operation's generated canonical field contract.\",\n ),\n detail: z\n .enum(SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS)\n .optional()\n .describe(\n 'Contract detail for assistant-operations. Use \"compact\" for authoring and \"full\" only for protocol debugging.',\n ),\n reason: z.string().max(500).optional().describe(\"Short reason this reference is needed.\"),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n topic: topicSchema,\n itemType: z.string().optional(),\n operationKind: z.string().optional(),\n detail: z.enum(SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS).optional(),\n title: z.string(),\n content: z.string(),\n});\n\ntype SurveyAuthoringReferenceInput = z.infer<typeof inputSchema>;\n\nconst formatCanonicalNameRecovery = (\n input: string,\n candidates: readonly string[],\n noun: string,\n) => {\n const suggestions = suggestCanonicalNames(input, candidates);\n return suggestions.length > 0\n ? ` Closest canonical ${noun}${suggestions.length === 1 ? \"\" : \"s\"}: ${suggestions.map((value) => `\"${value}\"`).join(\", \")}. Retry with the intended canonical name.`\n : \" Retry without the focused name to load the available catalog.\";\n};\n\nexport const surveyAuthoringReferenceTool = createTool({\n id: TOOL_ID,\n description:\n 'Load one narrow CASE authoring reference. With topic \"item-types\", pass itemType to load only that type. For a survey_change operation, use topic \"assistant-operations\" with operationKind and optionally itemType to compose the structural contract with that installed item capability. Compact detail is the authoring default; full detail is only for protocol debugging.',\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Read authoring reference\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData: SurveyAuthoringReferenceInput, context) => {\n const contractDetail = inputData.detail ?? \"compact\";\n const engineContext = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantEngineContext | undefined;\n const itemCapability = inputData.itemType\n ? (engineContext?.trustedCapabilities?.byItemType.get(inputData.itemType)?.manifest ??\n engineContext?.capabilities.itemTypes.find(\n (entry) => entry.itemType === inputData.itemType,\n ))\n : undefined;\n const availableItemTypes = [\n ...builtInSurveyAuthoringItemTypes,\n ...(engineContext?.capabilities.itemTypes.map((entry) => entry.itemType) ?? []),\n ];\n\n if (inputData.operationKind && inputData.topic !== \"assistant-operations\") {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n title: \"Operation contract unavailable\",\n content: \"operationKind is supported only with topic assistant-operations.\",\n };\n }\n\n if (inputData.operationKind) {\n if (!isSurveyOperationKind(inputData.operationKind)) {\n return {\n ok: false,\n topic: inputData.topic,\n operationKind: inputData.operationKind,\n detail: contractDetail,\n title: \"Operation contract unavailable\",\n content:\n `No built-in survey_change operation named \"${inputData.operationKind}\" is available.` +\n formatCanonicalNameRecovery(\n inputData.operationKind,\n SURVEY_OPERATION_KINDS,\n \"operation\",\n ),\n };\n }\n\n if (\n inputData.itemType &&\n !itemCapability &&\n !getBuiltInItemTypeAuthoringReference(inputData.itemType)\n ) {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n detail: contractDetail,\n title: \"Item capability unavailable\",\n content:\n `No installed survey item capability named \"${inputData.itemType}\" is available.` +\n formatCanonicalNameRecovery(inputData.itemType, availableItemTypes, \"item type\"),\n };\n }\n if (itemCapability && !itemCapability.supportedOperations.includes(inputData.operationKind)) {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n detail: contractDetail,\n title: \"Operation unsupported for item type\",\n content: `Item type \"${itemCapability.itemType}\" does not support survey_change operation \"${inputData.operationKind}\".`,\n };\n }\n\n return {\n ok: true,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n detail: contractDetail,\n title: itemCapability\n ? `${inputData.operationKind} for ${itemCapability.displayName}`\n : `${inputData.operationKind} operation contract`,\n content: formatSurveyOperationContractReference(inputData.operationKind, {\n detail: contractDetail,\n itemCapability,\n }),\n };\n }\n\n const builtInEntry = surveyAuthoringReferenceTopics.includes(\n inputData.topic as (typeof surveyAuthoringReferenceTopics)[number],\n )\n ? surveyAuthoringReferences[\n inputData.topic as (typeof surveyAuthoringReferenceTopics)[number]\n ]\n : undefined;\n const capability = inputData.itemType\n ? engineContext?.trustedCapabilities?.byItemType.get(inputData.itemType)\n : undefined;\n const capabilityReference = inputData.itemType\n ? resolveAssistantCapabilityReference({\n capabilities: engineContext?.trustedCapabilities,\n itemType: inputData.itemType,\n topic: inputData.topic,\n })\n : undefined;\n const focusedBuiltInItemTypeReference =\n inputData.topic === \"item-types\" && inputData.itemType\n ? getBuiltInItemTypeAuthoringReference(inputData.itemType)\n : undefined;\n if (\n inputData.itemType &&\n !focusedBuiltInItemTypeReference &&\n !capability &&\n !capabilityReference\n ) {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\n title: \"Item capability unavailable\",\n content:\n `No installed survey item capability named \"${inputData.itemType}\" is available.` +\n formatCanonicalNameRecovery(inputData.itemType, availableItemTypes, \"item type\"),\n };\n }\n const capabilityEntry = capabilityReference\n ? {\n title: capabilityReference.title ?? `${capability?.manifest.displayName} authoring`,\n content: capabilityReference.markdown,\n }\n : undefined;\n const focusedCapabilityProfile =\n inputData.topic === \"item-types\" && itemCapability\n ? {\n title: itemCapability.displayName,\n content: formatItemCapabilityProfile(itemCapability),\n }\n : undefined;\n // Choose the shared/focused contract first, then append capability constraints.\n // A focused item-type lookup must never load the combined cross-type catalog.\n const baseEntry =\n inputData.topic === \"item-types\" && inputData.itemType\n ? (focusedBuiltInItemTypeReference ?? focusedCapabilityProfile)\n : builtInEntry;\n const entry =\n baseEntry && capabilityEntry\n ? {\n title: baseEntry.title,\n content:\n baseEntry.content === capabilityEntry.content\n ? baseEntry.content\n : [\n baseEntry.content,\n \"## Item-specific constraints\",\n \"Apply the following capability constraints when using the shared grammar above.\",\n capabilityEntry.content,\n ].join(\"\\n\\n\"),\n }\n : (baseEntry ?? capabilityEntry);\n\n if (!entry) {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n title: \"Reference unavailable\",\n content:\n (inputData.itemType\n ? `No reference named \"${inputData.topic}\" is installed for item type \"${inputData.itemType}\".`\n : `No built-in reference named \"${inputData.topic}\" is available.`) +\n formatCanonicalNameRecovery(\n inputData.topic,\n [...surveyAuthoringReferenceTopics, ...(itemCapability?.referenceTopics ?? [])],\n \"reference\",\n ),\n };\n }\n\n return {\n ok: true,\n topic: inputData.topic,\n itemType: inputData.itemType,\n operationKind: inputData.operationKind,\n title: entry.title,\n content: entry.content,\n };\n },\n toModelOutput: (value) =>\n toTextModelOutput<z.infer<typeof outputSchema>>(\n value,\n (output) => `# ${output.title}\\n\\n${output.content}`,\n ),\n});\n","import { z } from \"zod\";\nimport type { SurveyChangeSet } from \"../../protocol\";\n\nexport const retryOfChangeIdsSchema = z\n .array(z.string().min(1))\n .max(20)\n .optional()\n .describe(\n \"Rejected ids for required retries or intentional removal of pending targets. Retry the complete corrected scope with non-empty mutations. Only allowsAcknowledgment permits inspected no-ops via survey_change operations: []. Linkage never clears identifiable pending edits.\",\n );\n\nexport const summarizePendingRepairs = (event: SurveyChangeSet): string[] => {\n if (!event.pendingRepairs?.length) return [];\n const requiredIds = event.pendingRepairs\n .filter((repair) => repair.requiresExplicitRetry)\n .map((repair) => repair.changeId);\n return [\n ...(requiredIds.length > 0\n ? [\n `Required retry linkage (copy exactly): ${JSON.stringify({ retryOfChangeIds: requiredIds })}. This addresses linkage only; preserve the requested content and structure while correcting validation errors.`,\n ]\n : []),\n \"TURN APPLY STATE: BLOCKED. These rejected proposal obligations remain unapplied. Repair every target; successful partial retries accumulate but do not clear the remaining obligations.\",\n ...event.pendingRepairs.map(\n (repair) =>\n `Rejected change ${repair.changeId}: ${JSON.stringify(repair.targets)}.${\n repair.requiresExplicitRetry\n ? ` This repair requires explicit linkage. Include every id in the aggregate Required retry linkage above with the complete corrected scope. ${repair.allowsAcknowledgment ? \"Validator-confirmed no-op obligations may be acknowledged after inspection with survey_change operations: []; other obligations remain pending.\" : \"A non-empty corrected retry is required; an empty acknowledgment cannot resolve this rejection.\"} Identifiable targets still need repair. No further mutations are staged until required links are supplied.`\n : \" Retry these same operations and surfaces with corrected values. If intentionally removing a pending target, include its rejected change id in retryOfChangeIds.\"\n }`,\n ),\n ];\n};\n","import { createTool } from \"@mastra/core/tools\";\nimport { SURVEY_EDITOR_ITEM_COLORS } from \"@case-framework/survey-core\";\nimport {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n surveyChangeSetSchema,\n surveyOperationSchema,\n type SurveyChangeSet,\n type SurveyOperation,\n} from \"../../protocol\";\nimport {\n MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL,\n normalizeSurveyChangeOperations,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n requireSurveyAssistantTurnState,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { toTextModelOutput } from \"./tool-model-output\";\n\nimport { collectMalformedSurveyOperationRecoveryTargets } from \"../../engine/mutation-recovery\";\nimport { retryOfChangeIdsSchema, summarizePendingRepairs } from \"./mutation-recovery\";\n\nexport const TOOL_ID = \"survey_change\";\n\nconst ITEM_COLOR_PALETTE_DESCRIPTION = `Allowed editor item-color swatches: ${SURVEY_EDITOR_ITEM_COLORS.join(\n \", \",\n)}. Use one of these exact values for update-item-color; do not wait for validation feedback to choose a swatch.`;\n\n// The permissive array lets the normalizer repair predictable schema-near\n// authoring mistakes. Keep only high-frequency and safety-critical conventions\n// in recurring model context; canonical per-operation schemas are generated on\n// demand by survey_authoring_reference from the protocol validators.\nconst OPERATIONS_DESCRIPTION = [\n 'Typed survey operation objects to validate and package as one undoable change. Every object uses discriminator \"kind\", never \"type\".',\n 'For an unfamiliar canonical shape, load survey_authoring_reference with topic \"assistant-operations\" and operationKind; it returns only that operation schema, generated from the validator.',\n \"Any translations owned by an operation must be inside that same operation object. Never put translations beside the survey_change operations array.\",\n \"Every translation payload uses exactly one representation: plainText, canonical content, or the model-facing richTextBlocks shorthand. Shorthand is accepted wherever a typed translation accepts structured content and is normalized to canonical content before validation. Use it only for surfaces that focused guidance identifies as rendering rich text.\",\n \"Canonical create-item shape: put parentItemId and optional index in target; put the required key and itemType, plus optional id, config, and creation-time expressions, in item; put respondent-visible plainText or structured content in top-level translations. Put choice maxSelection and options inside item.config. For top-level creation, target the root group identified by the snapshot or inspection.\",\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary respondent-visible text. For a complete formatted replacement, prefer the richTextBlocks shorthand from rich-text-content; canonical content remains available when needed. Item title, subtitle, topContent, bottomContent, cardFooter, info content, option labels, and field labels are translations, not item labels.\",\n \"Use add-survey-locale only when the user explicitly requests an empty language registration. An ordinary localization request requires real translation operations, which introduce the locale themselves.\",\n \"Use remove-survey-locale with locale to destructively remove an existing survey language and all translations stored for it.\",\n \"Each call adds a delta to this turn's validated draft. Later calls may target ids created by earlier successful calls in the same turn.\",\n \"Use operations: [] only with retryOfChangeIds when pendingRepairs.allowsAcknowledgment is true, after inspecting the validator-confirmed no-op. This does not discharge identifiable pending edits or create an editor commit by itself.\",\n \"For an existing choice item, use add-choice-option with itemId, optional locale/index, and option: { id?, key?, label }; label is a plain string and creates its translation.\",\n \"Every reorder replaces the complete inspected list: reorder-choice-options uses optionIds, reorder-form-field-groups uses groupIds, and reorder-items uses itemIds for every direct child. Include every existing entry exactly once in desired order.\",\n `Use update-item-color only with a supported swatch. ${ITEM_COLOR_PALETTE_DESCRIPTION}`,\n \"Use patch-item-config with itemId and plural patches whose JSON Pointer paths are relative to that item config root.\",\n \"Use update-placed-image only for an image already embedded in rich text in the live survey or validated turn draft. It can switch the placement between a local asset and an external URL and update its rendered ALT text, caption, width, height, maximum dimensions, and alignment. For a new item, prefer putting the canonical image block inside create-item.translations[].richTextBlocks. Do not use image asset metadata when the user asked to change one placed image.\",\n \"When deleting referenced images and assets, include every reference-removal operation and remove-image-asset last in the same operations array.\",\n \"A survey-json-patch proposal contains exactly one operation with kind survey-json-patch and one plural patches array containing every related raw edit. It must be the only operation in that survey_change call. Paths are rooted at the survey document, such as /surveyItems/<index>/config or /translations/<locale>; never start at /config or modify /$schema. Patch translation leaves rather than replacing existing locale or item-translation containers.\",\n \"Keep each delta bounded; this is a per-call constraint, not a reason to end the turn. Successful chunks accumulate automatically, so substantial requests should continue with later deltas while capacity remains.\",\n].join(\" \");\n\nconst inputSchema = z\n .object({\n retryOfChangeIds: retryOfChangeIdsSchema,\n summary: z\n .string()\n .min(1)\n .max(500)\n .describe(\"Short user-facing summary of the intended survey change.\"),\n operations: z\n .array(z.unknown())\n .min(0)\n .max(MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL)\n .describe(OPERATIONS_DESCRIPTION),\n })\n .strict();\n\nconst rejectedOperationParseEvent = ({\n issueText,\n summary,\n turnId,\n}: {\n issueText: string;\n summary: string;\n turnId: string;\n}): SurveyChangeSet => ({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n id: randomUUID(),\n turnId,\n status: \"rejected\",\n summary,\n operations: [],\n validation: {\n valid: false,\n issues: [\n {\n severity: \"error\",\n code: \"invalid-operation-shape\",\n message: issueText,\n },\n ],\n warnings: [],\n normalizedOperations: [],\n },\n createdAt: new Date().toISOString(),\n});\n\nconst describeOperationTarget = (operation: SurveyOperation): string => {\n switch (operation.kind) {\n case \"update-item-translation\":\n return `${operation.kind} ${operation.locale}:${operation.itemId}:${operation.contentKey}`;\n case \"update-placed-image\":\n return `${operation.kind} ${operation.locale}:${operation.itemId}:${operation.contentKey}#${operation.imageIndex}`;\n case \"update-item-label\":\n case \"update-item-color\":\n case \"update-item-key\":\n case \"patch-item-config\":\n case \"remove-item\":\n case \"move-item\":\n return `${operation.kind} ${operation.itemId}`;\n case \"upsert-form-field-group\":\n return `${operation.kind} ${operation.target.itemId}:${operation.group.id}`;\n case \"remove-form-field-group\":\n return `${operation.kind} ${operation.target.itemId}:${operation.groupId}`;\n case \"reorder-form-field-groups\":\n return `${operation.kind} ${operation.target.itemId}`;\n case \"upsert-form-field\":\n return `${operation.kind} ${operation.target.itemId}:${operation.field.id}`;\n case \"remove-form-field\":\n case \"move-form-field\":\n return `${operation.kind} ${operation.target.itemId}:${operation.fieldId}`;\n case \"set-embedded-form\":\n case \"remove-embedded-form\":\n return `${operation.kind} ${operation.itemId}:${operation.optionId}`;\n case \"add-choice-option\":\n return `${operation.kind} ${operation.itemId}:${operation.option.id ?? operation.option.key ?? operation.option.label}`;\n case \"update-choice-option-label\":\n case \"remove-choice-option\":\n return `${operation.kind} ${operation.itemId}:${operation.optionId}`;\n case \"reorder-choice-options\":\n return `${operation.kind} ${operation.itemId}`;\n case \"reorder-items\":\n return `${operation.kind} ${operation.parentItemId}`;\n case \"update-survey-metadata\":\n case \"update-survey-pagination\":\n return operation.kind;\n case \"update-survey-translation\":\n return `${operation.kind} ${operation.locale}:${operation.surface}:${operation.contentKey}`;\n case \"add-survey-locale\":\n case \"remove-survey-locale\":\n return `${operation.kind} ${operation.locale}`;\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return `${operation.kind} ${operation.assetId}`;\n case \"create-item\":\n return `${operation.kind} ${operation.item.id ?? operation.item.key ?? operation.item.itemType}`;\n case \"survey-json-patch\":\n return `${operation.kind} ${operation.patches.map((patch) => patch.path).join(\", \")}`;\n }\n};\n\nconst summarizeValidation = (event: SurveyChangeSet) => {\n const lines = [\n `${event.status === \"validated\" ? \"Validated\" : \"Rejected\"} survey change: ${event.summary}`,\n ];\n\n if (event.status === \"rejected\") {\n lines.push(\n \"TURN APPLY STATE: BLOCKED. Draft unchanged. This rejection does not finalize the editor or end the active turn. Fix this same rejected target in another survey_change call; the previously validated request-local draft is retained only for that repair. An unrelated valid edit does not repair this rejection.\",\n \"If this response ends while the turn is blocked, no prepared change from this turn, including every previously validated change, will reach the live editor. Do not tell the user that request-local draft content exists in the editor; either repair the rejected target now or state that none of this turn's changes were applied.\",\n );\n if (event.operations.length > 0) {\n const checklist = event.operations.slice(0, 24).map(describeOperationTarget);\n lines.push(\n `Unapplied target sample (${checklist.length} of ${event.operations.length}):\\n${checklist.map((target) => `- ${target}`).join(\"\\n\")}`,\n );\n if (event.operations.length > checklist.length) {\n lines.push(\n `The sample omits ${event.operations.length - checklist.length} additional operation target(s). The original tool input is authoritative; preserve its complete requested scope when retrying.`,\n );\n }\n }\n }\n\n if (event.status === \"validated\") {\n lines.push(\n `Draft updated (${event.operations.length} total operation${event.operations.length === 1 ? \"\" : \"s\"}). Later tools can inspect and edit the resulting draft state. The live editor is unchanged until successful turn completion.`,\n );\n if (event.postChange) {\n const unavailableItemCount =\n event.postChange.touchedItemCount - event.postChange.availableTouchedItemCount;\n lines.push(\n `Canonical post-change preview (first occurrence in operation order; projected fields only): ${event.postChange.itemCount} survey item(s); locales ${event.postChange.locales.length}/${event.postChange.localeCount} shown; targets ${event.postChange.touchedTargets.length}/${event.postChange.targetCount} shown; available touched-item snapshots ${event.postChange.touchedItems.length}/${event.postChange.availableTouchedItemCount} shown${unavailableItemCount > 0 ? `; ${unavailableItemCount} touched item target(s) are absent after the change` : \"\"}.`,\n );\n lines.push(\n `Target preview: ${event.postChange.touchedTargets.join(\", \") || \"none\"}. Absence from this bounded projection does not prove that a field or target is absent from the canonical draft.`,\n );\n for (const item of event.postChange.touchedItems) {\n const translations = item.translations\n .map(({ contentKey, locale, textLength, textPreview, truncated }) =>\n truncated\n ? `${locale}:${contentKey}=${JSON.stringify(`${textPreview}…`)} [truncated preview; ${textLength} characters total]`\n : `${locale}:${contentKey}=${JSON.stringify(textPreview)}`,\n )\n .join(\"; \");\n lines.push(\n `- ${item.fullKey} (${item.itemType}, id ${item.itemId}); response slots ${item.responseSlots.length}/${item.responseSlotCount}: ${item.responseSlots.join(\", \") || \"none\"}; translations ${item.translations.length}/${item.translationCount}: ${translations || \"none\"}`,\n );\n }\n if (event.postChange.truncated) {\n lines.push(\n \"The post-change preview is truncated. The validated draft still contains the complete change; inspect any relevant omitted target or field before claiming its exact post-change value.\",\n );\n }\n }\n }\n\n if (event.verification) {\n lines.push(\n `Verification required before claiming completion (${event.verification.reasons.join(\", \")}). Inspect the exact affected targets in the current draft; validation alone does not prove source fidelity or every omitted preview value.`,\n );\n if (event.verification.newAuditFindingCount > 0) {\n lines.push(\n `New deterministic audit findings: ${event.verification.auditFindings.length}/${event.verification.newAuditFindingCount} shown.`,\n );\n for (const finding of event.verification.auditFindings) {\n const location = [finding.itemId, finding.locale, finding.contentKey]\n .filter(Boolean)\n .join(\":\");\n lines.push(\n `- ${finding.severity} ${finding.code}${location ? ` (${location})` : \"\"}: ${finding.messagePreview}${finding.truncated ? `… [truncated preview; ${finding.messageLength} characters total]` : \"\"}`,\n );\n }\n if (event.verification.truncated) {\n lines.push(\n \"Verification diagnostics are bounded. Use survey_audit or focused survey_inspect calls for the complete relevant state.\",\n );\n }\n }\n }\n\n if (event.validation.issues.length > 0) {\n lines.push(\"Issues:\");\n for (const issue of event.validation.issues) {\n lines.push(`- ${issue.code}: ${issue.message}`);\n }\n\n const issueCodes = new Set(event.validation.issues.map((issue) => issue.code));\n if (\n issueCodes.has(\"missing-create-content\") ||\n issueCodes.has(\"missing-field-groups-wrapper\") ||\n issueCodes.has(\"missing-choice-options\") ||\n issueCodes.has(\"missing-choice-option-labels\") ||\n issueCodes.has(\"missing-form-field-content\") ||\n issueCodes.has(\"missing-form-select-option-labels\") ||\n issueCodes.has(\"missing-form-field-labels\") ||\n issueCodes.has(\"missing-embedded-form-field-labels\")\n ) {\n lines.push(\n \"Recovery hint: load the assistant-operations reference, then retry only the rejected delta. Put visible text in top-level translations[] beside item, config inside item.config, choice options in item.config.options, and form fields inside item.config.fieldGroups[].fields. Every choice option id needs a matching top-level translation whose contentKey is options.<optionId>.label.\",\n );\n }\n\n if (issueCodes.has(\"too-many-operations\")) {\n lines.push(\n \"Recovery hint: keep the same inspected survey context and split this rejected delta into smaller survey_change calls. Each successful call extends the same turn draft.\",\n );\n }\n\n if (issueCodes.has(\"item-already-in-target-parent\")) {\n lines.push(\n \"Recovery hint: remove unchanged same-parent move-item operations. To change sibling order within one parent, inspect its complete current children and use reorder-items instead.\",\n );\n }\n }\n\n if (event.validation.warnings.length > 0) {\n lines.push(\"Warnings:\");\n for (const warning of event.validation.warnings) {\n lines.push(`- ${warning.code}: ${warning.message}`);\n }\n }\n\n lines.push(...summarizePendingRepairs(event));\n return lines.join(\"\\n\");\n};\n\nexport const surveyChangeTool = createTool({\n id: TOOL_ID,\n description:\n 'Add one bounded typed-operation delta to the request-scoped survey draft. Successful calls are immediately visible to every later tool in this turn. Rejected calls leave the draft unchanged; retry the failed target. The live editor changes once after successful completion. Every operation uses \"kind\".',\n inputSchema,\n outputSchema: surveyChangeSetSchema,\n mcp: {\n annotations: {\n title: \"Prepare survey change\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveyChangeSet> => {\n const { turnDraft, turnId } = requireSurveyAssistantTurnState(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n );\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | undefined;\n const defaultLocale = snapshot?.ui.selectedLocale ?? snapshot?.inspection.locales[0] ?? \"en\";\n const normalized = normalizeSurveyChangeOperations(inputData.operations, defaultLocale);\n if (normalized.issues.length > 0) {\n return turnDraft.reject(\n rejectedOperationParseEvent({\n summary: inputData.summary,\n turnId,\n issueText: normalized.issues\n .slice(0, 8)\n .map((issue) => `${issue.path}: ${issue.message}`)\n .join(\"; \"),\n }),\n collectMalformedSurveyOperationRecoveryTargets(\n normalized.operations,\n snapshot,\n normalized.issues,\n ),\n );\n }\n const operationsParse = z.array(surveyOperationSchema).safeParse(normalized.operations);\n\n if (!operationsParse.success) {\n return turnDraft.reject(\n rejectedOperationParseEvent({\n summary: inputData.summary,\n turnId,\n issueText: operationsParse.error.issues\n .slice(0, 8)\n .map((issue) => `${issue.path.join(\".\") || \"operation\"}: ${issue.message}`)\n .join(\"; \"),\n }),\n collectMalformedSurveyOperationRecoveryTargets(\n normalized.operations,\n snapshot,\n normalized.issues,\n ),\n );\n }\n\n return turnDraft.stage({\n retryOfChangeIds: inputData.retryOfChangeIds,\n operations: operationsParse.data as SurveyOperation[],\n snapshot,\n summary: inputData.summary,\n });\n },\n toModelOutput: (value) => toTextModelOutput<SurveyChangeSet>(value, summarizeValidation),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n surveyChangeSetSchema,\n type SurveyChangeSet,\n type SurveyOperation,\n type SurveyValidationIssue,\n} from \"../../protocol\";\nimport {\n buildExpressionMutationBatch,\n expressionMutationSchema,\n getRawSurveyItems,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n requireSurveyAssistantTurnState,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { toTextModelOutput } from \"./tool-model-output\";\n\nimport {\n collectExpressionMutationRecoveryTargets,\n collectExpressionMutationRecoveryRefinements,\n type RecoveryTargetRefinement,\n} from \"../../engine/mutation-recovery\";\nimport { retryOfChangeIdsSchema, summarizePendingRepairs } from \"./mutation-recovery\";\n\nexport const TOOL_ID = \"survey_expression\";\n\nconst MAX_EXPRESSION_MUTATIONS_PER_PROPOSAL = 40;\n\nconst expressionMutationListSchema = z\n .array(expressionMutationSchema)\n .min(1)\n .max(MAX_EXPRESSION_MUTATIONS_PER_PROPOSAL);\n\nconst prepareActionSchema = z.object({\n action: z.literal(\"prepare\"),\n summary: z.string().min(1).max(500),\n mutations: expressionMutationListSchema,\n});\n\nconst inputSchema = z\n .object({\n retryOfChangeIds: retryOfChangeIdsSchema,\n action: z\n .enum([\"context\", \"prepare\"])\n .describe(\n 'Choose exactly one envelope. Inspect with action=\"context\" and optional reason, itemIds, or includeRawLocations. Create edits with action=\"prepare\", summary, and mutations.',\n ),\n reason: z\n .string()\n .max(500)\n .optional()\n .describe(\"Context action only: optional inspection reason.\"),\n itemIds: z\n .array(z.string().min(1).max(240))\n .max(12)\n .optional()\n .describe(\n \"Context action only: filter response slots and expression locations by item ids, keys, or fullKeys. Omit to inspect survey-wide references, including controlling questions outside the conditioned item.\",\n ),\n cursor: z\n .string()\n .regex(/^\\d+$/)\n .max(12)\n .optional()\n .describe(\n \"Context action only: nextCursor from the preceding page, with the same itemIds and includeRawLocations. Restart after a draft mutation.\",\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(80)\n .optional()\n .describe(\"Context action only: rows per catalog page; defaults to 80.\"),\n includeRawLocations: z\n .boolean()\n .optional()\n .describe(\"Context action only: include existing expression locations by raw item.\"),\n summary: z\n .string()\n .max(500)\n .optional()\n .describe(\"Prepare action only: required user-facing summary.\"),\n // Keep the canonical mutation union out of the provider-facing schema: Mastra normalized the\n // previous record-based item schema to objects that allowed no mutation properties. Execute\n // validates this compact opaque transport against the canonical application schema instead.\n mutations: z\n .array(z.unknown())\n .min(1)\n .max(MAX_EXPRESSION_MUTATIONS_PER_PROPOSAL)\n .optional()\n .describe(\n `Prepare action only: an array of 1-${MAX_EXPRESSION_MUTATIONS_PER_PROPOSAL} canonical expression mutation objects from the loaded expressions reference. Example entry: {\"kind\":\"set-item-display-condition\",\"itemId\":\"<existing-item-id>\",\"expression\":{\"type\":\"function\",\"functionName\":\"eq\",\"arguments\":[...]}}. expression is CASE expression JSON, never an expression-language snippet.`,\n ),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.action === \"context\") {\n if (value.summary?.trim()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"summary\"],\n message: \"Omit summary for context; use action=prepare to stage mutations.\",\n });\n }\n if (value.mutations !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"mutations\"],\n message: \"Omit mutations for context; use action=prepare to stage mutations.\",\n });\n }\n return;\n }\n if (!value.summary?.trim()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"summary\"],\n message: \"Required for prepare.\",\n });\n }\n if (!value.mutations?.length) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"mutations\"],\n message: \"A non-empty mutation array is required for prepare.\",\n });\n }\n });\n\nconst contextOutputSchema = z.object({\n ok: z.boolean(),\n action: z.literal(\"context\"),\n modelSummary: z.string(),\n listOrdering: z\n .record(z.string(), z.string())\n .describe(\"Meaning of each returned list. Expression references are not positional.\"),\n nextCursor: z.string().optional(),\n totalResponseSlots: z.number().int().nonnegative().optional(),\n surveyResponseSlotCount: z.number().int().nonnegative().optional(),\n totalExpressionLocations: z.number().int().nonnegative().optional(),\n unresolvedItemIds: z.array(z.string()).optional(),\n responseSlots: z.array(z.object({ ref: z.string(), valueType: z.string().optional() })),\n expressionLocations: z\n .array(\n z.object({\n itemId: z.string(),\n key: z.string(),\n itemType: z.string(),\n rawIndex: z.number().int().nonnegative(),\n locations: z.array(z.string()),\n }),\n )\n .optional(),\n});\n\nconst outputSchema = z.union([contextOutputSchema, surveyChangeSetSchema]);\n\ntype SurveyExpressionInput = z.infer<typeof inputSchema>;\ntype PrepareExpressionInput = z.infer<typeof prepareActionSchema>;\ntype ContextOutput = z.infer<typeof contextOutputSchema>;\n\ntype IssueInput = Omit<SurveyValidationIssue, \"severity\"> & {\n severity?: SurveyValidationIssue[\"severity\"];\n};\n\nconst createIssue = ({ severity = \"error\", ...input }: IssueInput): SurveyValidationIssue => ({\n severity,\n ...input,\n});\n\nconst buildResponseSlotTypes = (snapshot: SurveyAssistantSnapshot) => snapshot.responseSlotTypes;\n\nconst rejectedEvent = ({\n issues,\n summary,\n turnId,\n warnings = [],\n}: {\n issues: SurveyValidationIssue[];\n summary: string;\n turnId: string;\n warnings?: SurveyValidationIssue[];\n}): SurveyChangeSet => ({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n id: randomUUID(),\n turnId,\n status: \"rejected\",\n summary,\n operations: [],\n validation: {\n valid: false,\n issues,\n warnings,\n normalizedOperations: [],\n },\n createdAt: new Date().toISOString(),\n});\n\nconst summarizeDraftEvent = (event: SurveyChangeSet) => {\n const lines = [\n `${event.status === \"validated\" ? \"Validated\" : \"Rejected\"} expression change: ${event.summary}`,\n ];\n\n if (event.status === \"validated\") {\n lines.push(\n `Draft updated (${event.operations.length} total operation${event.operations.length === 1 ? \"\" : \"s\"}). The expression is immediately visible to later tools in this turn.`,\n );\n }\n\n if (event.status === \"rejected\") {\n lines.push(\n \"TURN APPLY STATE: BLOCKED. Draft unchanged. Fix this same expression target; the previously validated request-local draft is retained only for that repair. An unrelated valid edit does not repair this rejection.\",\n \"If this response ends while the turn is blocked, no prepared change from this turn, including every previously validated change, will reach the live editor. Do not tell the user that request-local draft content exists in the editor; either repair the rejected target now or state that none of this turn's changes were applied.\",\n );\n }\n\n if (event.validation.issues.length > 0) {\n lines.push(\"Issues:\");\n for (const issue of event.validation.issues) {\n lines.push(`- ${issue.code}: ${issue.message}`);\n }\n }\n\n if (event.validation.warnings.length > 0) {\n lines.push(\"Warnings:\");\n for (const warning of event.validation.warnings) {\n lines.push(`- ${warning.code}: ${warning.message}`);\n }\n }\n\n lines.push(...summarizePendingRepairs(event));\n return lines.join(\"\\n\");\n};\n\nconst buildContextOutput = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveyExpressionInput,\n): ContextOutput => {\n const rawItems = getRawSurveyItems(snapshot);\n const resolvedItems = input.itemIds?.map((identifier) => ({\n identifier,\n itemId: snapshot.inspection.keyIndex.find(\n (entry) =>\n entry.itemId === identifier || entry.key === identifier || entry.fullKey === identifier,\n )?.itemId,\n }));\n const itemFilter = resolvedItems?.length\n ? new Set(resolvedItems.flatMap((entry) => (entry.itemId ? [entry.itemId] : [])))\n : undefined;\n const unresolvedItemIds =\n resolvedItems?.filter((entry) => !entry.itemId).map((entry) => entry.identifier) ?? [];\n const surveyResponseSlots = Object.entries(buildResponseSlotTypes(snapshot));\n const allResponseSlots = surveyResponseSlots\n .filter(([ref]) => !itemFilter || [...itemFilter].some((id) => ref.startsWith(`${id}...`)))\n .map(([ref, valueType]) => ({ ref, ...(valueType ? { valueType } : {}) }));\n const offset = Number(input.cursor ?? 0);\n const limit = input.limit ?? 80;\n const responseSlots = allResponseSlots.slice(offset, offset + limit);\n const includeRawLocations = input.action === \"context\" && input.includeRawLocations === true;\n const allExpressionLocations = includeRawLocations\n ? rawItems\n .map((item, rawIndex) => {\n if (itemFilter && !itemFilter.has(item.id) && !itemFilter.has(item.key)) {\n return undefined;\n }\n const locations = [\n item.displayConditions?.root ? \"displayConditions.root\" : undefined,\n ...Object.keys(item.displayConditions?.components ?? {}).map(\n (componentId) => `displayConditions.components.${componentId}`,\n ),\n ...Object.keys(item.disabledConditions?.components ?? {}).map(\n (componentId) => `disabledConditions.components.${componentId}`,\n ),\n ...Object.keys(item.validations ?? {}).map(\n (validationKey) => `validations.${validationKey}`,\n ),\n ...(item.prefills ?? []).map((prefill) => `prefills.${prefill.id}`),\n ].filter((location): location is string => Boolean(location));\n\n return {\n itemId: item.id,\n key: item.key,\n itemType: item.itemType,\n rawIndex,\n locations,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))\n : undefined;\n\n const expressionLocations = allExpressionLocations?.slice(offset, offset + limit);\n const totalAvailable = Math.max(allResponseSlots.length, allExpressionLocations?.length ?? 0);\n const nextCursor = offset + limit < totalAvailable ? String(offset + limit) : undefined;\n const modelSummary = [\n \"Expression capability loaded.\",\n \"Use prepare mutations for display conditions, disabled conditions, validations, prefills, and template values.\",\n \"Display, disabled, validation, and prefill.when expressions must return boolean.\",\n \"Use response refs exactly as listed and check their value types before choosing functions.\",\n \"An isDefined ref means only that the respondent answered; it never means a particular answer such as Yes, selected, eligible, or has children.\",\n \"When the condition names or implies a choice, inspect the source choice item for the exact option id, then compare its get ref with that reference using eq or list_contains.\",\n \"Avoid accidental item display-condition response cycles, including self-reference or A-to-B-to-A chains. Shared analysis reports them as advisory because prefills can make them intentional; prefer an acyclic controlling source item unless the dependency is deliberate.\",\n \"For choice options: use eq(response reference, reference const) when the slot type is reference; use list_contains(response reference[], reference const) only when the slot type is reference[].\",\n \"Response-slot order: set-like deterministic snapshot construction order; it has no survey or respondent-visible meaning.\",\n itemFilter\n ? `Response-slot scope: filtered to itemIds=${JSON.stringify(input.itemIds)}; ${allResponseSlots.length} matching of ${surveyResponseSlots.length} survey-wide slots. References outside this filter are omitted, not absent. To find controlling questions elsewhere, call survey_expression action=context without itemIds or cursor.`\n : `Response-slot scope: survey-wide (${surveyResponseSlots.length} slots).`,\n `Response slots (${responseSlots.length}/${allResponseSlots.length}, offset ${offset}): ${responseSlots\n .map((slot) => `${slot.ref}${slot.valueType ? `:${slot.valueType}` : \"\"}`)\n .join(\", \")}`,\n nextCursor\n ? `More expression context is available. Call survey_expression action=context with cursor=\"${nextCursor}\" and the same itemIds, includeRawLocations, and limit. Restart without a cursor after a draft mutation.`\n : \"Expression context pagination complete for this scope.\",\n unresolvedItemIds.length > 0\n ? `Unresolved item identifiers: ${JSON.stringify(unresolvedItemIds)}. Inspect current context or search-items to resolve them; no references for these targets are implied.`\n : undefined,\n \"Functions: and, or, not, eq, gt, gte, lt, lte, in_range, list_contains, sum, min, max, str_eq, date_eq.\",\n expressionLocations\n ? `Existing expression locations: ${\n expressionLocations\n .filter((entry) => entry.locations.length > 0)\n .map((entry) => `${entry.key}(${entry.itemId}) -> ${entry.locations.join(\"|\")}`)\n .join(\"; \") || \"none\"\n }`\n : undefined,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n\n return {\n ok: true,\n action: \"context\",\n modelSummary,\n totalResponseSlots: allResponseSlots.length,\n surveyResponseSlotCount: surveyResponseSlots.length,\n ...(allExpressionLocations ? { totalExpressionLocations: allExpressionLocations.length } : {}),\n ...(nextCursor ? { nextCursor } : {}),\n ...(unresolvedItemIds.length ? { unresolvedItemIds } : {}),\n listOrdering: {\n responseSlots:\n \"Set-like deterministic snapshot construction order; position has no survey or respondent-visible meaning.\",\n expressionLocations:\n \"Stored surveyItems array order; locations within an item are grouped by expression surface, not ranked or respondent-visible order.\",\n \"expressionLocations[].locations\":\n \"Grouped by expression surface (root, components, validations, prefills); position has no semantic meaning.\",\n },\n responseSlots,\n ...(expressionLocations ? { expressionLocations } : {}),\n };\n};\n\nexport const surveyExpressionTool = createTool({\n id: TOOL_ID,\n description:\n \"Inspect response refs or add general expression edits to the request-scoped survey draft. Successful mutation calls are immediately visible to later tools; rejected calls leave the draft unchanged. Covers display and disabled conditions, validations, prefills, and template values.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Work with expressions\",\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<ContextOutput | SurveyChangeSet> => {\n const input = inputData as SurveyExpressionInput;\n const requestContext = context?.requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n if (input.action === \"context\") {\n return {\n ok: false,\n action: \"context\",\n modelSummary: \"No live editor snapshot is available for expression work.\",\n listOrdering: {\n responseSlots: \"Set-like; unavailable because no live snapshot was provided.\",\n },\n responseSlots: [],\n };\n }\n\n const { turnDraft, turnId } = requireSurveyAssistantTurnState(requestContext);\n return turnDraft.reject(\n rejectedEvent({\n summary: input.summary ?? \"Expression change\",\n turnId,\n issues: [\n createIssue({\n code: \"missing-snapshot\",\n message: \"No live editor snapshot is available for expression work.\",\n }),\n ],\n }),\n );\n }\n\n if (input.action === \"context\") {\n return buildContextOutput(snapshot, input);\n }\n\n const { turnDraft, turnId } = requireSurveyAssistantTurnState(requestContext);\n\n const reject = (\n event: SurveyChangeSet,\n addressedTargets: string[] = [],\n refinements: RecoveryTargetRefinement[] = [],\n ) => turnDraft.reject(event, addressedTargets, refinements);\n\n if (!Array.isArray(input.mutations)) {\n return reject(\n rejectedEvent({\n summary: input.summary ?? \"Expression change\",\n turnId,\n issues: [\n createIssue({\n code: \"invalid-expression-mutation-shape\",\n message: \"mutations is required for prepare and must be a canonical mutation array.\",\n }),\n ],\n }),\n );\n }\n\n const prepareParse = prepareActionSchema.safeParse({\n action: input.action,\n summary: input.summary,\n mutations: input.mutations,\n });\n if (!prepareParse.success) {\n return reject(\n rejectedEvent({\n summary: input.summary ?? \"Expression change\",\n turnId,\n issues: [\n createIssue({\n code: \"invalid-expression-mutation-shape\",\n message: prepareParse.error.issues\n .slice(0, 8)\n .map((issue) => `${issue.path.join(\".\") || \"input\"}: ${issue.message}`)\n .join(\"; \"),\n }),\n ],\n }),\n collectExpressionMutationRecoveryTargets(input.mutations, snapshot),\n );\n }\n const prepareInput = prepareParse.data;\n const addressedTargets = collectExpressionMutationRecoveryTargets(\n prepareInput.mutations,\n snapshot,\n );\n\n const { issues, patches } = buildExpressionMutationBatch(prepareInput.mutations, snapshot);\n\n const errors = issues.filter((issue) => issue.severity === \"error\");\n const warnings = issues.filter((issue) => issue.severity === \"warning\");\n if (errors.length > 0) {\n return reject(\n rejectedEvent({ summary: prepareInput.summary, turnId, issues: errors, warnings }),\n collectExpressionMutationRecoveryTargets(prepareInput.mutations, snapshot, errors),\n collectExpressionMutationRecoveryRefinements(prepareInput.mutations, snapshot, errors),\n );\n }\n\n if (patches.length === 0) {\n const noPatchIssues = prepareInput.mutations.map((_, operationIndex) =>\n createIssue({\n code: \"no-expression-patches\",\n operationIndex,\n message:\n \"No expression patches were produced. Inspect whether the requested locations already match the target state; acknowledge already-satisfied work through a linked survey_change with operations: [].\",\n }),\n );\n return reject(\n rejectedEvent({\n summary: prepareInput.summary,\n turnId,\n issues: noPatchIssues,\n warnings,\n }),\n collectExpressionMutationRecoveryTargets(prepareInput.mutations, snapshot, noPatchIssues),\n collectExpressionMutationRecoveryRefinements(\n prepareInput.mutations,\n snapshot,\n noPatchIssues,\n ),\n );\n }\n\n const operation: SurveyOperation = {\n kind: \"survey-json-patch\",\n patches,\n };\n\n const event = turnDraft.stage({\n retryOfChangeIds: input.retryOfChangeIds,\n addressedTargets,\n allowExpressionJsonPatches: true,\n handledMutationRoutes: [\"expression\"],\n operations: [operation],\n snapshot,\n summary: prepareInput.summary,\n });\n\n return {\n ...event,\n validation: {\n ...event.validation,\n warnings: [...event.validation.warnings, ...warnings],\n },\n };\n },\n toModelOutput: (value) =>\n toTextModelOutput<ContextOutput | SurveyChangeSet>(value, (output) =>\n \"action\" in output && output.action === \"context\"\n ? output.modelSummary\n : summarizeDraftEvent(output as SurveyChangeSet),\n ),\n});\n","import { z } from \"zod\";\n\nexport const parseInspectionOutput = <Schema extends z.ZodType>(\n schema: Schema,\n value: unknown,\n backend: string,\n): z.output<Schema> => {\n const parsed = schema.safeParse(value);\n if (!parsed.success) {\n throw new Error(`${backend} produced invalid inspection output.`, { cause: parsed.error });\n }\n\n return parsed.data;\n};\n","import type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n DEFAULT_LIMIT,\n MAX_LIMIT,\n clampLimit,\n itemMatchesQuery,\n itemSummarySchema,\n mapKeyIndexById,\n mapOutlineById,\n normalizeText,\n resolveItemSummary,\n sliceWithCursor,\n findDirectChildrenByFullKey,\n getKeyIndexEntries,\n getDeterministicCreateItemTypes,\n summarizeFocusItemNode,\n summarizeItemById,\n summarizeKeyIndexEntries,\n summarizeOutlineNode,\n unique,\n type ItemSummary,\n type SurveyFocusItemNode,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { assistantItemTypeManifestSchema } from \"../../protocol\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { parseInspectionOutput } from \"./parse-inspection-output\";\n\nconst contextScopeSchema = z.enum([\n \"summary\",\n \"selected-item\",\n \"outline\",\n \"response-slots\",\n \"ui-context\",\n \"history\",\n]);\nconst outlineModeSchema = z.enum([\"full\", \"focused\", \"children\"]);\n\nconst translationSnippetSchema = z.object({\n locale: z.string(),\n contentKey: z.string(),\n text: z.string(),\n});\n\nconst inputSchema = z.object({\n scopes: z\n .array(contextScopeSchema)\n .min(1)\n .default([\"summary\"])\n .describe(\"Which current editor context sections to inspect.\"),\n itemId: z\n .string()\n .optional()\n .describe(\"Optional item id to inspect. Defaults to the selected/focused item.\"),\n query: z\n .string()\n .max(180)\n .optional()\n .describe(\"Optional text used to find matching item ids, keys, labels, or response slots.\"),\n cursor: z\n .string()\n .optional()\n .describe(\"Optional numeric cursor returned by a previous outline or response slot request.\"),\n outlineMode: outlineModeSchema\n .default(\"full\")\n .optional()\n .describe(\n 'For outline scope: \"full\" pages the complete survey key index, \"focused\" returns the selected/focused neighborhood, and \"children\" returns direct children of itemId.',\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(MAX_LIMIT)\n .default(DEFAULT_LIMIT)\n .describe(\"Maximum number of rows to return for list-like scopes.\"),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n reason: z.string().optional(),\n revision: z.number().int().nonnegative().optional(),\n contentHash: z.string().optional(),\n scopes: z.array(contextScopeSchema).optional(),\n listOrdering: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Meaning of each returned list. A list is positional only when its entry says so.\"),\n summary: z\n .object({\n sessionId: z.string().nullable(),\n view: z.string(),\n selectedItemId: z.string().optional(),\n focusItemId: z.string().optional(),\n selectedLocale: z.string(),\n recentItemIds: z.array(z.string()),\n surveyKey: z.string().optional(),\n locales: z.array(z.string()),\n itemCount: z.number().int().nonnegative(),\n historyIndex: z.number().int(),\n outlineItemCount: z.number().int().nonnegative(),\n responseSlotCount: z.number().int().nonnegative(),\n rootItem: itemSummarySchema.optional(),\n availableItemTypes: z.array(z.string()),\n deterministicCreateItemTypes: z.array(z.string()),\n itemTypeDetails: z.array(assistantItemTypeManifestSchema),\n })\n .optional(),\n selectedItem: z\n .object({\n available: z.boolean(),\n reason: z.string().optional(),\n requestedItemId: z.string().optional(),\n item: itemSummarySchema.optional(),\n relationSource: z.string().optional(),\n pathItems: z.array(itemSummarySchema).optional(),\n siblingItems: z.array(itemSummarySchema).optional(),\n childItems: z.array(itemSummarySchema).optional(),\n translationSnippets: z.array(translationSnippetSchema).optional(),\n descendantItems: z.array(itemSummarySchema).optional(),\n descendantCount: z.number().int().nonnegative().optional(),\n descendantsTruncated: z.boolean().optional(),\n })\n .optional(),\n outline: z\n .object({\n strategy: z.string(),\n mode: outlineModeSchema.optional(),\n query: z.string().optional(),\n requestedItemId: z.string().optional(),\n totalAvailable: z.number().int().nonnegative(),\n returned: z.number().int().nonnegative(),\n nextCursor: z.string().optional(),\n truncated: z.boolean(),\n ordering: z.string(),\n items: z.array(itemSummarySchema),\n note: z.string().optional(),\n })\n .optional(),\n responseSlots: z\n .object({\n available: z.boolean(),\n query: z.string().optional(),\n totalAvailable: z.number().int().nonnegative(),\n returned: z.number().int().nonnegative(),\n nextCursor: z.string().optional(),\n truncated: z.boolean(),\n ordering: z.string(),\n slots: z.array(z.string()),\n note: z.string().optional(),\n })\n .optional(),\n uiContext: z\n .object({\n activeSurface: z.string().optional(),\n openPanels: z.array(z.string()),\n highlights: z.array(\n z.object({\n kind: z.string(),\n itemId: z.string().optional(),\n componentId: z.string().optional(),\n label: z.string().optional(),\n details: z.string().optional(),\n }),\n ),\n })\n .optional(),\n history: z\n .object({\n currentIndex: z.number().int(),\n totalEntries: z.number().int().nonnegative(),\n canUndo: z.boolean(),\n canRedo: z.boolean(),\n recent: z.array(\n z.object({\n index: z.number().int(),\n kind: z.enum([\"survey-snapshot\", \"asset-change\"]),\n label: z.string(),\n source: z.enum([\"user\", \"system\", \"assistant\"]).optional(),\n timestamp: z.number(),\n isCurrent: z.boolean(),\n }),\n ),\n })\n .optional(),\n});\n\ntype SurveyContextScope = z.infer<typeof contextScopeSchema>;\ntype SurveyGetCurrentContextInput = z.output<typeof inputSchema>;\ntype SurveyGetCurrentContextInputData = z.input<typeof inputSchema>;\ntype SurveyGetCurrentContextOutput = z.infer<typeof outputSchema>;\n\nconst findFocusItemNode = (\n node: SurveyFocusItemNode | undefined,\n itemId: string,\n): SurveyFocusItemNode | undefined => {\n if (!node) {\n return undefined;\n }\n\n if (node.itemId === itemId) {\n return node;\n }\n\n for (const descendant of node.descendants) {\n const match = findFocusItemNode(descendant, itemId);\n if (match) {\n return match;\n }\n }\n\n return undefined;\n};\n\nconst flattenFocusDescendants = (node: SurveyFocusItemNode): SurveyFocusItemNode[] => {\n const descendants: SurveyFocusItemNode[] = [];\n const visit = (current: SurveyFocusItemNode) => {\n for (const descendant of current.descendants) {\n descendants.push(descendant);\n visit(descendant);\n }\n };\n visit(node);\n return descendants;\n};\n\nconst getCandidateItems = (snapshot: SurveyAssistantSnapshot): ItemSummary[] => {\n const outlineById = mapOutlineById(snapshot);\n return summarizeKeyIndexEntries(getKeyIndexEntries(snapshot), outlineById);\n};\n\nconst buildSummary = (\n snapshot: SurveyAssistantSnapshot,\n): SurveyGetCurrentContextOutput[\"summary\"] => ({\n rootItem: snapshot.inspection.outline\n .filter((item) => item.depth === 0)\n .map(summarizeOutlineNode)[0],\n sessionId: snapshot.version.sessionId,\n view: snapshot.ui.view,\n selectedItemId: snapshot.ui.selectedItemId,\n focusItemId: snapshot.ui.focusItemId,\n selectedLocale: snapshot.ui.selectedLocale,\n recentItemIds: snapshot.ui.recentItemIds ?? [],\n surveyKey: snapshot.inspection.surveyKey,\n locales: snapshot.inspection.locales,\n itemCount: snapshot.inspection.itemCount,\n historyIndex: snapshot.version.historyIndex,\n outlineItemCount: snapshot.inspection.keyIndex.length,\n responseSlotCount: snapshot.inspection.responseSlots.length,\n availableItemTypes: snapshot.capabilities.itemTypes.map((entry) => entry.itemType),\n deterministicCreateItemTypes: getDeterministicCreateItemTypes(snapshot.capabilities),\n itemTypeDetails: snapshot.capabilities.itemTypes,\n});\n\nconst buildSelectedItem = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveyGetCurrentContextInput,\n): SurveyGetCurrentContextOutput[\"selectedItem\"] => {\n const outlineById = mapOutlineById(snapshot);\n const indexById = mapKeyIndexById(snapshot);\n const resolvedInputItem = input.itemId\n ? resolveItemSummary(input.itemId, indexById, outlineById)\n : undefined;\n const requestedItemId =\n resolvedInputItem?.itemId ??\n input.itemId ??\n snapshot.ui.selectedItemId ??\n snapshot.ui.focusItemId;\n\n if (!requestedItemId) {\n return {\n available: false,\n reason: \"No item is currently selected or focused in the editor.\",\n };\n }\n\n const focusNode = findFocusItemNode(snapshot.inspection.focusItem, requestedItemId);\n const item = focusNode\n ? summarizeFocusItemNode(focusNode, outlineById)\n : (resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById));\n\n if (!item) {\n return {\n available: false,\n requestedItemId,\n reason: \"The requested item is not present in the current context snapshot.\",\n };\n }\n\n const limit = clampLimit(input.limit);\n const descendants = focusNode ? flattenFocusDescendants(focusNode) : [];\n const relationSource =\n snapshot.inspection.focus?.focusItemId === requestedItemId\n ? \"selected-focus\"\n : focusNode\n ? \"focused-subtree\"\n : \"key-index\";\n\n return {\n available: true,\n requestedItemId,\n item,\n relationSource,\n pathItems: snapshot.inspection.focus?.pathItemIds\n ?.map((itemId) => summarizeItemById(itemId, indexById, outlineById))\n .filter((entry): entry is ItemSummary => Boolean(entry)),\n siblingItems: snapshot.inspection.focus?.siblingItemIds\n ?.map((itemId) => summarizeItemById(itemId, indexById, outlineById))\n .filter((entry): entry is ItemSummary => Boolean(entry)),\n childItems: snapshot.inspection.focus?.childItemIds\n ?.map((itemId) => summarizeItemById(itemId, indexById, outlineById))\n .filter((entry): entry is ItemSummary => Boolean(entry)),\n translationSnippets: focusNode?.translations.slice(0, limit),\n descendantItems: descendants\n .slice(0, limit)\n .map((descendant) => summarizeFocusItemNode(descendant, outlineById)),\n descendantCount: descendants.length,\n descendantsTruncated: descendants.length > limit || snapshot.inspection.focusItemTreeTruncated,\n };\n};\n\nconst buildOutline = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveyGetCurrentContextInput,\n): SurveyGetCurrentContextOutput[\"outline\"] => {\n const query = normalizeText(input.query);\n const outlineById = mapOutlineById(snapshot);\n const indexById = mapKeyIndexById(snapshot);\n const resolvedInputItem = input.itemId\n ? resolveItemSummary(input.itemId, indexById, outlineById)\n : undefined;\n const requestedItemId =\n resolvedInputItem?.itemId ??\n input.itemId ??\n snapshot.ui.focusItemId ??\n snapshot.ui.selectedItemId;\n const outlineMode = input.outlineMode ?? \"full\";\n\n let strategy = \"focused-snapshot-outline\";\n let items: ItemSummary[];\n let note: string | undefined;\n\n if (query) {\n strategy = \"query-match\";\n items = getCandidateItems(snapshot).filter((item) => itemMatchesQuery(item, query));\n } else if (outlineMode === \"children\" && requestedItemId) {\n strategy = \"direct-children\";\n const parent = resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById);\n items = parent\n ? findDirectChildrenByFullKey(getKeyIndexEntries(snapshot), outlineById, parent.fullKey)\n : [];\n if (!parent) {\n note = \"The requested item could not be resolved by item id, key, or fullKey.\";\n }\n } else if (\n outlineMode === \"focused\" &&\n requestedItemId &&\n snapshot.inspection.focus?.focusItemId === requestedItemId\n ) {\n const focus = snapshot.inspection.focus;\n const descendantIds = snapshot.inspection.focusItem\n ? flattenFocusDescendants(snapshot.inspection.focusItem).map((item) => item.itemId)\n : [];\n const relationIds = unique([\n ...focus.pathItemIds,\n requestedItemId,\n ...focus.childItemIds,\n ...focus.siblingItemIds,\n ...descendantIds,\n ]);\n items = relationIds\n .map((itemId) => summarizeItemById(itemId, indexById, outlineById))\n .filter((entry): entry is ItemSummary => Boolean(entry));\n } else if (outlineMode === \"focused\" && requestedItemId) {\n strategy = \"item-match\";\n const item = resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById);\n items = item ? [item] : [];\n note = \"The requested item is outside the selected focus tree in this snapshot.\";\n } else {\n strategy = \"full-key-index\";\n items = getCandidateItems(snapshot);\n }\n\n const page = sliceWithCursor(items, input);\n\n return {\n strategy,\n mode: outlineMode,\n query: input.query,\n requestedItemId,\n totalAvailable: items.length,\n returned: page.items.length,\n nextCursor: page.nextCursor,\n truncated: page.truncated,\n ordering:\n strategy === \"focused-snapshot-outline\"\n ? \"Survey-tree preorder: configured group-child order is preserved; unparented items are appended by item id.\"\n : strategy === \"direct-children\"\n ? \"Stored group-child order; this is not a stable respondent-visible order if that group shuffles children.\"\n : strategy === \"query-match\"\n ? \"Survey-tree preorder after filtering by the query; this is not relevance-ranked.\"\n : \"Relationship grouping for the focused item, not a single positional survey order.\",\n items: page.items,\n note,\n };\n};\n\nconst buildResponseSlots = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveyGetCurrentContextInput,\n): SurveyGetCurrentContextOutput[\"responseSlots\"] => {\n const responseSlots = snapshot.inspection.responseSlots;\n\n const query = normalizeText(input.query);\n const filtered = query\n ? responseSlots.filter((slot) => slot.toLowerCase().includes(query))\n : responseSlots;\n const page = sliceWithCursor(filtered, input);\n\n return {\n available: true,\n query: input.query,\n totalAvailable: filtered.length,\n returned: page.items.length,\n nextCursor: page.nextCursor,\n truncated: page.truncated,\n ordering:\n \"Set-like response references in deterministic snapshot construction order; do not interpret their position as survey or respondent order.\",\n slots: page.items,\n };\n};\n\nexport const inspectSurveyCurrentContext = (\n inputData: SurveyGetCurrentContextInputData,\n requestContext?: RequestContext<SurveyAssistantRequestContext>,\n): SurveyGetCurrentContextOutput => {\n const input = inputSchema.parse({\n ...inputData,\n outlineMode: inputData.outlineMode ?? \"full\",\n });\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n scopes: input.scopes,\n };\n }\n\n const scopes = unique<SurveyContextScope>(input.scopes);\n const listOrdering: Record<string, string> = {};\n if (scopes.includes(\"summary\")) {\n Object.assign(listOrdering, {\n \"summary.recentItemIds\": \"Most-recent-first UI history; not survey structure.\",\n \"summary.locales\":\n \"Selected locale first, then remaining source locale order; locale position has no survey meaning.\",\n \"summary.availableItemTypes\": \"Capability registry order; treat as a set of available types.\",\n \"summary.deterministicCreateItemTypes\":\n \"Capability registry order; treat as a set of available types.\",\n \"summary.itemTypeDetails\":\n \"Capability registry order; treat as a set of available type definitions.\",\n });\n }\n if (scopes.includes(\"selected-item\")) {\n Object.assign(listOrdering, {\n \"selectedItem.pathItems\": \"Root-to-selected survey-tree path.\",\n \"selectedItem.siblingItems\":\n \"Source survey item storage order; not necessarily respondent-visible order.\",\n \"selectedItem.childItems\": \"Stored group-child order when the focused item is a group.\",\n \"selectedItem.translationSnippets\":\n \"Grouped by locale and then source translation-key order; not positional survey content.\",\n \"selectedItem.descendantItems\": \"Depth-first survey-tree traversal from the selected item.\",\n });\n }\n if (scopes.includes(\"ui-context\")) {\n Object.assign(listOrdering, {\n \"uiContext.openPanels\": \"UI-provided set-like list; position has no meaning.\",\n \"uiContext.highlights\": \"UI-provided set-like list; position has no meaning.\",\n });\n }\n if (scopes.includes(\"history\")) {\n listOrdering[\"history.recent\"] =\n \"Chronological editor history, oldest to newest within this returned window.\";\n }\n const output: SurveyGetCurrentContextOutput = {\n ok: true,\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\n scopes,\n ...(Object.keys(listOrdering).length > 0 ? { listOrdering } : {}),\n };\n\n if (scopes.includes(\"summary\")) {\n output.summary = buildSummary(snapshot);\n }\n\n if (scopes.includes(\"selected-item\")) {\n output.selectedItem = buildSelectedItem(snapshot, input);\n }\n\n if (scopes.includes(\"outline\")) {\n output.outline = buildOutline(snapshot, input);\n }\n\n if (scopes.includes(\"response-slots\")) {\n output.responseSlots = buildResponseSlots(snapshot, input);\n }\n\n if (scopes.includes(\"ui-context\")) {\n output.uiContext = {\n activeSurface: snapshot.ui.activeSurface,\n openPanels: snapshot.ui.openPanels ?? [],\n highlights: snapshot.ui.highlights ?? [],\n };\n }\n\n if (scopes.includes(\"history\") && snapshot.ui.history) {\n output.history = snapshot.ui.history;\n }\n\n return parseInspectionOutput(outputSchema, output, \"Current-context inspection\");\n};\n","import type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n MAX_LIMIT,\n buildEmbeddedFormDetails,\n buildItemConfigDetails,\n buildItemTranslationEntries,\n clampLimit,\n findDirectChildrenByFullKey,\n getKeyIndexEntries,\n itemConfigDetailsSchema,\n itemSummarySchema,\n mapKeyIndexById,\n mapOutlineById,\n mapRawItemsById,\n resolveItemSummary,\n translationEntrySchema,\n inspectAssistantItem,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { parseInspectionOutput } from \"./parse-inspection-output\";\n\nconst DEFAULT_TEXT_LIMIT = 400;\nconst MAX_TEXT_LIMIT = 2000;\nconst DEFAULT_CHILDREN_LIMIT = 20;\n\nconst inputSchema = z.object({\n itemId: z\n .string()\n .describe(\n 'Identifier of the item to inspect: its itemId, key (e.g. \"info_1\"), or fullKey (e.g. \"survey.info_1\"). Discover candidates first via survey_inspect search or current context.',\n ),\n locales: z\n .array(z.string())\n .optional()\n .describe(\n \"Optional locale codes to restrict returned translations to. Defaults to all locales.\",\n ),\n textLimit: z\n .number()\n .int()\n .min(20)\n .max(MAX_TEXT_LIMIT)\n .default(DEFAULT_TEXT_LIMIT)\n .describe(\"Maximum characters returned per translation snippet.\"),\n includeChildren: z\n .boolean()\n .optional()\n .describe(\n \"Deprecated alias for includeSurveyChildren. This means survey-tree children only, not choice options or form fields.\",\n ),\n includeSurveyChildren: z\n .boolean()\n .default(false)\n .describe(\n \"Whether to include a shallow list of this item's direct survey-tree children, such as group members.\",\n ),\n includeItemConfig: z\n .boolean()\n .default(true)\n .describe(\n \"Whether to include item-internal config details such as choice options and form field groups.\",\n ),\n childrenLimit: z\n .number()\n .int()\n .min(1)\n .max(MAX_LIMIT)\n .default(DEFAULT_CHILDREN_LIMIT)\n .describe(\"Maximum number of direct survey-tree children to return.\"),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n reason: z.string().optional(),\n item: itemSummarySchema.optional(),\n translations: z.array(translationEntrySchema).optional(),\n surveyChildren: z.array(itemSummarySchema).optional(),\n surveyChildrenTruncated: z.boolean().optional(),\n listOrdering: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Meaning of each returned list. A list is positional only when its entry says so.\"),\n configDetails: itemConfigDetailsSchema.optional(),\n capabilityDetails: z.object({ summary: z.string(), details: z.unknown().optional() }).optional(),\n});\n\ntype SurveyGetItemDetailsInputData = z.input<typeof inputSchema>;\ntype SurveyGetItemDetailsOutput = z.infer<typeof outputSchema>;\nexport const inspectSurveyItemDetails = (\n inputData: SurveyGetItemDetailsInputData,\n requestContext?: RequestContext<SurveyAssistantRequestContext>,\n): SurveyGetItemDetailsOutput => {\n const input = inputSchema.parse({\n ...inputData,\n includeSurveyChildren: inputData.includeSurveyChildren ?? inputData.includeChildren,\n });\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n };\n }\n\n const outlineById = mapOutlineById(snapshot);\n const indexById = mapKeyIndexById(snapshot);\n const rawItemsById = mapRawItemsById(snapshot);\n const item = resolveItemSummary(input.itemId, indexById, outlineById);\n\n if (!item) {\n return {\n ok: false,\n reason: `No item matching \"${input.itemId}\" (by itemId, key, or fullKey) was found in the current context snapshot.`,\n };\n }\n\n const rawItem = rawItemsById.get(item.itemId);\n const rawConfig =\n rawItem?.config && typeof rawItem.config === \"object\" && !Array.isArray(rawItem.config)\n ? (rawItem.config as { shuffleItems?: unknown })\n : undefined;\n const output: SurveyGetItemDetailsOutput = {\n ok: true,\n item,\n translations: buildItemTranslationEntries(snapshot, item.itemId, input),\n listOrdering: {\n translations:\n \"Grouped by locale and then source translation-key order; this list is not positional survey content.\",\n surveyChildren:\n rawConfig?.shuffleItems === true\n ? \"Stored group-child order; respondents see shuffled children, so this is not a stable respondent-visible order.\"\n : \"Stored group-child order; this is the respondent-visible order when the parent is a group.\",\n },\n };\n\n if (input.includeSurveyChildren) {\n const entries = getKeyIndexEntries(snapshot);\n const allChildren = findDirectChildrenByFullKey(entries, outlineById, item.fullKey);\n const limit = clampLimit(input.childrenLimit);\n output.surveyChildren = allChildren.slice(0, limit);\n output.surveyChildrenTruncated = allChildren.length > limit;\n }\n\n if (input.includeItemConfig) {\n output.configDetails = rawItem ? buildItemConfigDetails(rawItem) : undefined;\n output.capabilityDetails = rawItem\n ? inspectAssistantItem({ capabilities: snapshot.trustedCapabilities, item: rawItem })\n : undefined;\n\n if (rawItem?.itemType === \"choiceItem\" && output.configDetails?.choiceOptions) {\n const rawChoiceConfig =\n rawItem.config && typeof rawItem.config === \"object\" && !Array.isArray(rawItem.config)\n ? (rawItem.config as { options?: unknown[] })\n : undefined;\n const rawOptions = Array.isArray(rawChoiceConfig?.options) ? rawChoiceConfig.options : [];\n\n for (const option of output.configDetails.choiceOptions) {\n const rawOption = rawOptions.find(\n (candidate) =>\n candidate &&\n typeof candidate === \"object\" &&\n \"id\" in candidate &&\n candidate.id === option.id,\n );\n const embeddedForm =\n rawOption && typeof rawOption === \"object\" && \"embeddedForm\" in rawOption\n ? rawOption.embeddedForm\n : undefined;\n const embeddedFormDetails = buildEmbeddedFormDetails(option, embeddedForm);\n if (embeddedFormDetails?.formFieldGroups?.length) {\n output.configDetails.formFieldGroups = [\n ...(output.configDetails.formFieldGroups ?? []),\n ...embeddedFormDetails.formFieldGroups,\n ];\n }\n }\n }\n }\n\n return parseInspectionOutput(outputSchema, output, \"Item-details inspection\");\n};\n","import type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n JsonPatchError,\n encodeJsonPointerSegment,\n getValueAtJsonPointer,\n type RawSurvey,\n type RawSurveyItem,\n} from \"@case-framework/survey-core\";\nimport {\n getRawSurvey,\n getRawSurveyItems,\n mapKeyIndexById,\n mapOutlineById,\n resolveItemSummary,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { parseInspectionOutput } from \"./parse-inspection-output\";\n\nconst DEFAULT_VALUE_CHARACTER_LIMIT = 12_000;\nconst MAX_VALUE_CHARACTER_LIMIT = 60_000;\n\nconst jsonPointerPathSchema = z\n .string()\n .max(500)\n .describe(\n 'JSON Pointer path into the survey document. Examples: \"/surveyItems/0/config/items\", \"/metadata\", \"/translations/en/itemTranslations/<itemId>/title\".',\n );\n\nconst inputSchema = z.object({\n paths: z\n .array(jsonPointerPathSchema)\n .min(1)\n .max(20)\n .optional()\n .describe(\n \"Optional exact JSON Pointer paths to inspect. Omit paths and itemIdentifiers for a top-level raw survey overview.\",\n ),\n itemIdentifiers: z\n .array(z.string().min(1).max(240))\n .min(1)\n .max(20)\n .optional()\n .describe(\n \"Optional item ids, keys, or fullKeys to inspect. Returns exact /surveyItems/<index> paths plus item translation paths for each item.\",\n ),\n textOffset: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),\n valueCharacterLimit: z\n .number()\n .int()\n .min(1000)\n .max(MAX_VALUE_CHARACTER_LIMIT)\n .default(DEFAULT_VALUE_CHARACTER_LIMIT)\n .describe(\"Maximum serialized characters returned per requested value.\"),\n});\n\nconst rawSurveyItemPathSchema = z.object({\n path: z.string(),\n id: z.string(),\n key: z.string(),\n itemType: z.string(),\n parentId: z.string().optional(),\n childCount: z.number().int().nonnegative().optional(),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n reason: z.string().optional(),\n revision: z.number().int().nonnegative().optional(),\n contentHash: z.string().optional(),\n listOrdering: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Meaning of each returned list. Raw JSON arrays retain their stored order.\"),\n overview: z\n .object({\n topLevelKeys: z.array(z.string()),\n surveyItemCount: z.number().int().nonnegative(),\n locales: z.array(z.string()),\n itemPaths: z.array(rawSurveyItemPathSchema),\n note: z.string().optional(),\n })\n .optional(),\n values: z\n .array(\n z.object({\n path: z.string(),\n found: z.boolean(),\n value: z.unknown().optional(),\n preview: z.string().optional(),\n text: z.string().optional(),\n textOffset: z.number().int().nonnegative().optional(),\n textLength: z.number().int().nonnegative().optional(),\n nextTextOffset: z.number().int().nonnegative().optional(),\n recovery: z.string().optional(),\n truncated: z.boolean().optional(),\n error: z.string().optional(),\n }),\n )\n .optional(),\n items: z\n .array(\n z.object({\n identifier: z.string(),\n found: z.boolean(),\n itemId: z.string().optional(),\n itemPath: z.string().optional(),\n rawItem: z.unknown().optional(),\n rawItemPreview: z.string().optional(),\n rawItemTruncated: z.boolean().optional(),\n translationPaths: z.array(z.string()).optional(),\n translationsByLocale: z.record(z.string(), z.unknown()).optional(),\n translationsPreview: z.string().optional(),\n translationsTruncated: z.boolean().optional(),\n error: z.string().optional(),\n }),\n )\n .optional(),\n});\n\ntype SurveyGetRawSurveyInputData = z.input<typeof inputSchema>;\ntype SurveyGetRawSurveyOutput = z.infer<typeof outputSchema>;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getGroupChildren = (item: unknown): string[] => {\n if (!isRecord(item) || !isRecord(item.config) || !Array.isArray(item.config.items)) {\n return [];\n }\n\n return item.config.items.filter((entry): entry is string => typeof entry === \"string\");\n};\n\nconst buildParentByChildId = (rawSurvey: Partial<RawSurvey>) => {\n const parentByChildId = new Map<string, string>();\n const rawItems = Array.isArray(rawSurvey.surveyItems) ? rawSurvey.surveyItems : [];\n\n for (const item of rawItems) {\n for (const childId of getGroupChildren(item)) {\n parentByChildId.set(childId, item.id);\n }\n }\n\n return parentByChildId;\n};\n\nconst buildOverview = (snapshot: SurveyAssistantSnapshot): SurveyGetRawSurveyOutput[\"overview\"] => {\n const rawSurvey = getRawSurvey(snapshot);\n const rawItems = getRawSurveyItems(snapshot);\n const parentByChildId = buildParentByChildId(rawSurvey);\n\n return {\n topLevelKeys: Object.keys(rawSurvey).sort(),\n surveyItemCount: rawItems.length,\n locales: snapshot.inspection.locales,\n itemPaths: rawItems.map((item, index) => ({\n path: `/surveyItems/${index}`,\n id: item.id,\n key: item.key,\n itemType: item.itemType,\n parentId: parentByChildId.get(item.id),\n childCount: getGroupChildren(item).length || undefined,\n })),\n note: 'Use paths with JSON Pointer syntax. Patch operations are applied relative to the survey document root, so do not prefix paths with \"/survey\".',\n };\n};\n\nconst toOutputValue = (value: unknown, characterLimit: number) => {\n const serialized = JSON.stringify(value, null, 2) ?? \"undefined\";\n if (serialized.length <= characterLimit) {\n return {\n value,\n truncated: false,\n };\n }\n\n return {\n preview: serialized.slice(0, characterLimit),\n truncated: true,\n };\n};\n\nconst buildValues = (\n snapshot: SurveyAssistantSnapshot,\n input: { paths: string[]; valueCharacterLimit: number; textOffset?: number },\n): NonNullable<SurveyGetRawSurveyOutput[\"values\"]> => {\n const rawSurvey = getRawSurvey(snapshot);\n\n return input.paths.map((path) => {\n try {\n const value = getValueAtJsonPointer(rawSurvey, path);\n if (\n typeof value === \"string\" &&\n (input.textOffset !== undefined || JSON.stringify(value).length > input.valueCharacterLimit)\n ) {\n const characters = [...value];\n const textOffset = input.textOffset ?? 0;\n const text = characters.slice(textOffset, textOffset + input.valueCharacterLimit).join(\"\");\n const nextTextOffset = textOffset + [...text].length;\n return {\n path,\n found: true,\n text,\n textOffset,\n textLength: characters.length,\n truncated: textOffset > 0 || nextTextOffset < characters.length,\n ...(nextTextOffset < characters.length ? { nextTextOffset } : {}),\n recovery:\n \"This is a string segment, not the complete value. Concatenate segments in offset order. Continue with survey_inspect action=raw-json, this same path, and textOffset=nextTextOffset until nextTextOffset is absent. Restart after a draft mutation.\",\n };\n }\n return {\n path,\n found: true,\n ...toOutputValue(value, input.valueCharacterLimit),\n };\n } catch (error) {\n const patchError = error instanceof JsonPatchError ? error : undefined;\n return {\n path,\n found: false,\n error:\n patchError?.message ??\n (error instanceof Error\n ? error.message\n : \"The requested JSON Pointer path was not found.\"),\n };\n }\n });\n};\n\nconst findRawItemByIdentifier = (\n snapshot: SurveyAssistantSnapshot,\n identifier: string,\n): { item: RawSurveyItem; index: number } | undefined => {\n const rawItems = getRawSurveyItems(snapshot);\n const directIndex = rawItems.findIndex((item) => item.id === identifier);\n if (directIndex >= 0) {\n return {\n item: rawItems[directIndex],\n index: directIndex,\n };\n }\n\n const resolved = resolveItemSummary(\n identifier,\n mapKeyIndexById(snapshot),\n mapOutlineById(snapshot),\n );\n if (!resolved) {\n return undefined;\n }\n\n const resolvedIndex = rawItems.findIndex((item) => item.id === resolved.itemId);\n if (resolvedIndex < 0) {\n return undefined;\n }\n\n return {\n item: rawItems[resolvedIndex],\n index: resolvedIndex,\n };\n};\n\nconst getTranslationsByLocaleForItem = (rawSurvey: Partial<RawSurvey>, itemId: string) => {\n const entries: Record<string, unknown> = {};\n\n for (const [locale, localeTranslations] of Object.entries(rawSurvey.translations ?? {})) {\n const itemTranslations = localeTranslations?.itemTranslations?.[itemId];\n if (itemTranslations) {\n entries[locale] = itemTranslations;\n }\n }\n\n return entries;\n};\n\nconst buildItemValues = (\n snapshot: SurveyAssistantSnapshot,\n input: { itemIdentifiers: string[]; valueCharacterLimit: number },\n): NonNullable<SurveyGetRawSurveyOutput[\"items\"]> => {\n const rawSurvey = getRawSurvey(snapshot);\n\n return input.itemIdentifiers.map((identifier) => {\n const resolved = findRawItemByIdentifier(snapshot, identifier);\n if (!resolved) {\n return {\n identifier,\n found: false,\n error: `No item matching \"${identifier}\" was found by item id, key, or fullKey.`,\n };\n }\n\n const itemId = resolved.item.id;\n const rawItemOutput = toOutputValue(resolved.item, input.valueCharacterLimit);\n const translationsByLocale = getTranslationsByLocaleForItem(rawSurvey, itemId);\n const translationsOutput = toOutputValue(translationsByLocale, input.valueCharacterLimit);\n const translationsValue =\n \"value\" in translationsOutput && isRecord(translationsOutput.value)\n ? translationsOutput.value\n : undefined;\n\n return {\n identifier,\n found: true,\n itemId,\n itemPath: `/surveyItems/${resolved.index}`,\n rawItem: \"value\" in rawItemOutput ? rawItemOutput.value : undefined,\n rawItemPreview: \"preview\" in rawItemOutput ? rawItemOutput.preview : undefined,\n rawItemTruncated: rawItemOutput.truncated,\n translationPaths: snapshot.inspection.locales.map(\n (locale) =>\n `/translations/${encodeJsonPointerSegment(locale)}/itemTranslations/${encodeJsonPointerSegment(itemId)}`,\n ),\n translationsByLocale: translationsValue,\n translationsPreview: \"preview\" in translationsOutput ? translationsOutput.preview : undefined,\n translationsTruncated: translationsOutput.truncated,\n };\n });\n};\n\nexport const inspectRawSurvey = (\n inputData: SurveyGetRawSurveyInputData,\n requestContext?: RequestContext<SurveyAssistantRequestContext>,\n): SurveyGetRawSurveyOutput => {\n const input = inputSchema.parse(inputData);\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n };\n }\n\n return parseInspectionOutput(\n outputSchema,\n {\n ok: true,\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\n listOrdering: {\n \"overview.topLevelKeys\": \"Alphabetical key order; not survey content order.\",\n \"overview.locales\":\n \"Selected locale first, then remaining source locale order; locale position has no survey meaning.\",\n \"overview.itemPaths\":\n \"Stored surveyItems array order. The numeric segment in each JSON Pointer path is its zero-based stored position; this differs from group-child display order.\",\n values: \"Same order as the requested JSON Pointer paths.\",\n items: \"Same order as the requested itemIdentifiers.\",\n },\n overview: input.paths || input.itemIdentifiers ? undefined : buildOverview(snapshot),\n items: input.itemIdentifiers\n ? buildItemValues(snapshot, {\n itemIdentifiers: input.itemIdentifiers,\n valueCharacterLimit: input.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT,\n })\n : undefined,\n values: input.paths\n ? buildValues(snapshot, {\n paths: input.paths,\n textOffset: input.textOffset,\n valueCharacterLimit: input.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT,\n })\n : undefined,\n },\n \"Raw-survey inspection\",\n );\n};\n","import type { RequestContext } from \"@mastra/core/request-context\";\nimport type { RawSurveyItem } from \"@case-framework/survey-core\";\nimport {\n DEFAULT_LIMIT,\n MAX_LIMIT,\n buildConfigSearchText,\n buildItemTranslationEntries,\n itemSummarySchema,\n mapOutlineById,\n mapRawItemsById,\n sliceWithCursor,\n summarizeKeyIndexEntries,\n summarizeRawItem,\n type ItemSummary,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { z } from \"zod\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { parseInspectionOutput } from \"./parse-inspection-output\";\n\nconst MAX_QUERY_LENGTH = 180;\nconst MAX_MATCHES_PER_ITEM = 6;\nconst DEFAULT_TEXT_LIMIT = 220;\n\nconst searchMatchSchema = z.object({\n source: z.enum([\"structure\", \"translation\", \"config\"]),\n field: z.string().optional(),\n locale: z.string().optional(),\n contentKey: z.string().optional(),\n text: z.string(),\n score: z.number(),\n});\n\nconst searchResultSchema = z.object({\n item: itemSummarySchema,\n score: z.number(),\n matches: z.array(searchMatchSchema),\n});\n\nconst inputSchema = z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_QUERY_LENGTH)\n .describe(\n 'Text to search for across all survey items, including visible translated content such as titles, option labels, and form field labels. Examples: \"age\", \"consent\", \"blood pressure\".',\n ),\n itemTypes: z\n .array(z.string())\n .optional()\n .describe(\"Optional item types to restrict results to, such as choiceItem or formItem.\"),\n locales: z\n .array(z.string())\n .optional()\n .describe(\"Optional locale codes to restrict translation-content matches to.\"),\n cursor: z.string().optional().describe(\"Optional numeric cursor returned by a previous search.\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(MAX_LIMIT)\n .default(DEFAULT_LIMIT)\n .describe(\"Maximum number of matching items to return.\"),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n reason: z.string().optional(),\n query: z.string().optional(),\n totalAvailable: z.number().int().nonnegative().optional(),\n returned: z.number().int().nonnegative().optional(),\n nextCursor: z.string().optional(),\n truncated: z.boolean().optional(),\n ordering: z\n .string()\n .optional()\n .describe(\"How results and their matches are ordered; this search output is not survey order.\"),\n results: z.array(searchResultSchema).optional(),\n});\n\ntype SurveySearchItemsInputData = z.input<typeof inputSchema>;\ntype SurveySearchItemsInput = z.output<typeof inputSchema>;\ntype SurveySearchItemsOutput = z.infer<typeof outputSchema>;\ntype SearchMatch = z.infer<typeof searchMatchSchema>;\ntype SearchResult = z.infer<typeof searchResultSchema>;\n\nconst STOP_WORDS = new Set([\n \"a\",\n \"about\",\n \"an\",\n \"and\",\n \"called\",\n \"choice\",\n \"field\",\n \"form\",\n \"for\",\n \"in\",\n \"item\",\n \"label\",\n \"named\",\n \"of\",\n \"option\",\n \"question\",\n \"survey\",\n \"the\",\n \"this\",\n \"title\",\n \"titled\",\n \"with\",\n]);\n\nconst normalizeSearchText = (value: string) => value.trim().toLowerCase().replace(/\\s+/g, \" \");\n\nconst queryTerms = (query: string) => {\n const terms = normalizeSearchText(query)\n .split(/[\\s.,;:!?()[\\]{}\"'`/\\\\]+/)\n .map((term) => term.trim())\n .filter((term) => term.length > 1 && !STOP_WORDS.has(term));\n\n if (terms.length > 0) {\n return terms;\n }\n\n return normalizeSearchText(query)\n .split(/[\\s.,;:!?()[\\]{}\"'`/\\\\]+/)\n .map((term) => term.trim())\n .filter((term) => term.length > 1);\n};\n\nconst scoreText = (\n value: string,\n query: string,\n terms: string[],\n baseScore: number,\n): number | null => {\n const normalizedValue = normalizeSearchText(value);\n const normalizedQuery = normalizeSearchText(query);\n\n if (!normalizedValue || !normalizedQuery) {\n return null;\n }\n\n if (normalizedValue === normalizedQuery) {\n return baseScore + 80;\n }\n\n if (normalizedValue.includes(normalizedQuery)) {\n return baseScore + 50;\n }\n\n const hitCount = terms.filter((term) => normalizedValue.includes(term)).length;\n if (terms.length > 0 && hitCount === terms.length) {\n return baseScore + hitCount * 12;\n }\n\n return null;\n};\n\nconst addMatch = (matches: SearchMatch[], match: Omit<SearchMatch, \"text\"> & { text?: string }) => {\n const text = match.text?.trim();\n if (!text) {\n return;\n }\n\n const duplicate = matches.some(\n (existing) =>\n existing.source === match.source &&\n existing.field === match.field &&\n existing.locale === match.locale &&\n existing.contentKey === match.contentKey &&\n existing.text === text,\n );\n\n if (!duplicate) {\n matches.push({ ...match, text });\n }\n};\n\nconst candidateItems = (\n snapshot: SurveyAssistantSnapshot,\n): Array<{\n item: ItemSummary;\n rawItem?: RawSurveyItem;\n}> => {\n const outlineById = mapOutlineById(snapshot);\n const rawItemsById = mapRawItemsById(snapshot);\n const seen = new Set<string>();\n const candidates: Array<{\n item: ItemSummary;\n rawItem?: RawSurveyItem;\n }> = [];\n\n for (const entry of summarizeKeyIndexEntries(snapshot.inspection.keyIndex, outlineById)) {\n seen.add(entry.itemId);\n candidates.push({\n item: entry,\n rawItem: rawItemsById.get(entry.itemId),\n });\n }\n\n for (const rawItem of rawItemsById.values()) {\n if (seen.has(rawItem.id)) {\n continue;\n }\n\n candidates.push({\n item: summarizeRawItem(rawItem),\n rawItem,\n });\n }\n\n return candidates;\n};\n\nconst searchItems = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveySearchItemsInput,\n): SearchResult[] => {\n const terms = queryTerms(input.query);\n const itemTypeFilter = input.itemTypes?.length ? new Set(input.itemTypes) : undefined;\n\n return candidateItems(snapshot)\n .filter(({ item }) => !itemTypeFilter || itemTypeFilter.has(item.itemType))\n .map(({ item, rawItem }) => {\n const matches: SearchMatch[] = [];\n\n const structuralFields: Array<[field: string, text: string | undefined]> = [\n [\"itemId\", item.itemId],\n [\"itemType\", item.itemType],\n [\"key\", item.key],\n [\"fullKey\", item.fullKey],\n [\"itemLabel\", item.itemLabel],\n [\"path\", item.path?.join(\" \")],\n ];\n\n for (const [field, text] of structuralFields) {\n if (!text) {\n continue;\n }\n\n const score = scoreText(text, input.query, terms, 50);\n if (score !== null) {\n addMatch(matches, { source: \"structure\", field, text, score });\n }\n }\n\n for (const translation of buildItemTranslationEntries(snapshot, item.itemId, {\n locales: input.locales,\n textLimit: DEFAULT_TEXT_LIMIT,\n })) {\n const score = scoreText(\n `${translation.contentKey} ${translation.text}`,\n input.query,\n terms,\n 100,\n );\n if (score !== null) {\n addMatch(matches, {\n source: \"translation\",\n locale: translation.locale,\n contentKey: translation.contentKey,\n text: translation.text,\n score,\n });\n }\n }\n\n if (rawItem) {\n for (const text of buildConfigSearchText(rawItem)) {\n const score = scoreText(text, input.query, terms, 60);\n if (score !== null) {\n addMatch(matches, { source: \"config\", text, score });\n }\n }\n }\n\n if (matches.length === 0) {\n return undefined;\n }\n\n matches.sort((a, b) => b.score - a.score);\n return {\n item,\n matches: matches.slice(0, MAX_MATCHES_PER_ITEM),\n score: matches.reduce((sum, match) => sum + match.score, 0),\n };\n })\n .filter((result): result is SearchResult => Boolean(result))\n .sort((a, b) => b.score - a.score || a.item.fullKey.localeCompare(b.item.fullKey));\n};\n\nexport const searchSurveyItems = (\n inputData: SurveySearchItemsInputData,\n requestContext?: RequestContext<SurveyAssistantRequestContext>,\n): SurveySearchItemsOutput => {\n const input = inputSchema.parse(inputData);\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n query: input.query,\n };\n }\n\n const results = searchItems(snapshot, input);\n const page = sliceWithCursor(results, input);\n\n return parseInspectionOutput(\n outputSchema,\n {\n ok: true,\n query: input.query,\n totalAvailable: results.length,\n returned: page.items.length,\n nextCursor: page.nextCursor,\n truncated: page.truncated,\n ordering:\n \"Results are ranked by descending text-match score, then item full key. Matches within each result are ranked by descending score. Neither order is survey or respondent-visible order.\",\n results: page.items,\n },\n \"Survey-item search\",\n );\n};\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n analyzeSurveyAssistantExpressionReferences,\n getSurveyAssistantExpressionDiagnosticGuidance,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport {\n getAssetUsagesFromContent,\n encodeJsonPointerSegment,\n getContentPlainText,\n isBlockingSurveyExpressionReferenceDiagnostic,\n type Content,\n type RawSurvey,\n type RawSurveyAsset,\n type SurveyExpressionReferenceDiagnosticCategory,\n type SurveyExpressionReferenceDiagnosticDisposition,\n} from \"@case-framework/survey-core\";\nimport { z } from \"zod\";\nimport { inspectSurveyCurrentContext } from \"./inspect-current-context\";\nimport { inspectSurveyItemDetails } from \"./inspect-item-details\";\nimport { inspectRawSurvey } from \"./inspect-raw-survey\";\nimport { searchSurveyItems } from \"./search-survey-items\";\nimport { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_inspect\";\n\ntype ExpressionDiagnosticGuidanceCatalog = Partial<\n Record<\n SurveyExpressionReferenceDiagnosticDisposition,\n Partial<Record<SurveyExpressionReferenceDiagnosticCategory, string>>\n >\n>;\n\nconst inspectActionSchema = z.enum([\n \"current-context\",\n \"search-items\",\n \"item-details\",\n \"localization\",\n \"assets\",\n \"expression-diagnostics\",\n \"raw-json\",\n]);\nconst outlineModeSchema = z.enum([\"full\", \"focused\", \"children\"]);\nconst MAX_RAW_JSON_PATHS_PER_RESULT = 20;\nconst MAX_RAW_JSON_PATHS_PER_REQUEST = 100;\nconst optionalInput = <T extends z.ZodType>(schema: T) =>\n z.preprocess((value) => (value === null ? undefined : value), schema.optional());\nconst optionalArrayInput = <T extends z.ZodType>(schema: T) =>\n z.preprocess(\n (value) => (value === null || (Array.isArray(value) && value.length === 0) ? undefined : value),\n schema.optional(),\n );\nconst optionalNonBlankString = (maxLength: number) =>\n z.preprocess(\n (value) =>\n value === null || (typeof value === \"string\" && value.trim().length === 0)\n ? undefined\n : value,\n z.string().min(1).max(maxLength).optional(),\n );\n\nconst inputSchema = z.object({\n action: inspectActionSchema.describe(\"The survey information to inspect.\"),\n reason: optionalInput(z.string().max(500)).describe(\"Short reason this inspection is needed.\"),\n scopes: optionalArrayInput(\n z\n .array(\n z.enum([\"summary\", \"selected-item\", \"outline\", \"response-slots\", \"ui-context\", \"history\"]),\n )\n .min(1)\n .max(6),\n ).describe(\"For current-context: context sections to inspect. Empty means omitted.\"),\n query: optionalNonBlankString(180).describe(\n \"For search-items: text to search across survey content. For assets: optional asset id, filename, name, ALT text, or media type filter. For current-context outline: optional key/fullKey/label filter.\",\n ),\n sourceLocale: optionalNonBlankString(40).describe(\n \"For localization: source locale to translate. Defaults to the selected editor locale.\",\n ),\n targetLocale: optionalNonBlankString(40).describe(\n \"For localization: required target locale whose coverage should be inspected.\",\n ),\n missingOnly: optionalInput(z.boolean()).describe(\n \"For localization: return only source surfaces that do not yet exist in the target locale.\",\n ),\n itemRef: optionalNonBlankString(240).describe(\n 'For current-context outline, item-details, or raw-json: item id, key, fullKey, visible label, or \"selected\".',\n ),\n cursor: optionalNonBlankString(240).describe(\n \"For current-context, search-items, or localization pagination: numeric cursor from a previous result.\",\n ),\n outlineMode: optionalInput(outlineModeSchema).describe(\n 'For current-context outline: \"full\" pages all survey items, \"focused\" returns the selected/focused neighborhood, and \"children\" returns direct children of itemRef.',\n ),\n paths: optionalArrayInput(\n z.array(z.string().min(1).max(500)).min(1).max(MAX_RAW_JSON_PATHS_PER_REQUEST),\n ).describe(\n `For raw-json: exact JSON Pointer paths to inspect in request order. itemRef takes precedence when both are supplied. Up to ${MAX_RAW_JSON_PATHS_PER_RESULT} paths are returned per call; larger valid requests receive explicit coverage and retry guidance instead of failing input validation. Empty means omitted.`,\n ),\n textOffset: optionalInput(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)).describe(\n \"For raw-json exact string paths: nextTextOffset from a partial result. Continue with the same single path until nextTextOffset is absent; restart after mutations.\",\n ),\n includeChildren: optionalInput(z.boolean()).describe(\n \"For item-details: include direct survey-tree children.\",\n ),\n includeItemConfig: optionalInput(z.boolean()).describe(\n \"For item-details: include choice/form/internal item config details.\",\n ),\n limit: optionalInput(z.number().int().min(1).max(50)).describe(\"Maximum list rows to return.\"),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n action: inspectActionSchema,\n reason: z.string().optional(),\n modelSummary: z.string(),\n result: z.unknown().optional(),\n});\n\ntype SurveyInspectInput = z.infer<typeof inputSchema>;\ntype SurveyInspectOutput = z.infer<typeof outputSchema>;\n\nconst stringifyForModel = (value: unknown) => {\n if (typeof value === \"string\") {\n return value;\n }\n\n return JSON.stringify(value, null, 2);\n};\n\n// An async backend would reject outside this synchronous validation boundary.\ntype SynchronousResult<T> = T extends PromiseLike<unknown> ? never : T;\n\nconst runInspectionBackend = <T>(inspect: () => T & SynchronousResult<T>) => {\n try {\n return { ok: true as const, value: inspect() };\n } catch (error) {\n if (!(error instanceof z.ZodError)) {\n throw error;\n }\n\n const firstIssue = error.issues[0];\n const issuePath = firstIssue?.path?.length\n ? ` at ${firstIssue.path.join(\".\").slice(0, 120)}`\n : \"\";\n const issueMessage = (firstIssue?.message ?? \"Invalid internal inspection data.\").slice(0, 400);\n return {\n ok: false as const,\n reason: `Survey inspection validation failed${issuePath}: ${issueMessage}`,\n };\n }\n};\n\nconst inspectionBackendFailure = (\n action: SurveyInspectInput[\"action\"],\n reason: string,\n): SurveyInspectOutput => ({ ok: false, action, reason, modelSummary: reason });\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst MAX_LOCALIZATION_TEXT_CHARS = 2000;\nconst SURVEY_TRANSLATION_SURFACES = [\n \"surveyCardContent\",\n \"navigationContent\",\n \"validationMessages\",\n] as const;\n\nconst truncateLocalizationText = (content: Content) => {\n const text = getContentPlainText(content).trim();\n return text.length > MAX_LOCALIZATION_TEXT_CHARS\n ? `${text.slice(0, MAX_LOCALIZATION_TEXT_CHARS)}...`\n : text;\n};\n\nconst listLocalizationSurfaces = (\n input: SurveyInspectInput,\n snapshot: SurveyAssistantSnapshot,\n targetLocale: string,\n) => {\n const survey = snapshot.survey as RawSurvey;\n const sourceLocale = input.sourceLocale ?? snapshot.ui.selectedLocale;\n const sourceTranslations = survey.translations?.[sourceLocale];\n const targetTranslations = survey.translations?.[targetLocale];\n\n if (!sourceTranslations) {\n return {\n ok: false as const,\n reason: `Source locale \"${sourceLocale}\" is not present in the current survey draft.`,\n };\n }\n\n const surfaces: Array<{\n scope: \"survey\" | \"item\";\n surface?: (typeof SURVEY_TRANSLATION_SURFACES)[number];\n itemId?: string;\n itemKey?: string;\n itemType?: string;\n contentKey: string;\n sourceType: Content[\"type\"];\n sourceText: string;\n sourceTextLength: number;\n sourceTruncated: boolean;\n sourcePath: string;\n sourceTextPath?: string;\n sourceContent?: Content;\n targetPresent: boolean;\n targetType?: Content[\"type\"];\n targetText?: string;\n targetTextLength?: number;\n targetTruncated?: boolean;\n }> = [];\n\n const addSurface = ({\n contentKey,\n itemId,\n itemKey,\n itemType,\n sourceContent,\n surface,\n targetContent,\n }: {\n contentKey: string;\n itemId?: string;\n itemKey?: string;\n itemType?: string;\n sourceContent: Content;\n surface?: (typeof SURVEY_TRANSLATION_SURFACES)[number];\n targetContent?: Content;\n }) => {\n const sourceText = truncateLocalizationText(sourceContent);\n if (!sourceText) return;\n const sourcePath = `/translations/${encodeJsonPointerSegment(sourceLocale)}/${\n itemId ? `itemTranslations/${encodeJsonPointerSegment(itemId)}` : surface\n }/${encodeJsonPointerSegment(contentKey)}`;\n surfaces.push({\n scope: itemId ? \"item\" : \"survey\",\n ...(surface ? { surface } : {}),\n ...(itemId ? { itemId, itemKey, itemType } : {}),\n contentKey,\n sourceType: sourceContent.type,\n sourceText,\n sourceTextLength: getContentPlainText(sourceContent).trim().length,\n sourceTruncated:\n getContentPlainText(sourceContent).trim().length > MAX_LOCALIZATION_TEXT_CHARS,\n sourcePath,\n ...(sourceContent.type !== \"richText\" ? { sourceTextPath: `${sourcePath}/content` } : {}),\n ...(sourceContent.type === \"richText\" ? { sourceContent } : {}),\n targetPresent: Boolean(targetContent && truncateLocalizationText(targetContent)),\n ...(targetContent\n ? {\n targetType: targetContent.type,\n targetText: truncateLocalizationText(targetContent),\n targetTextLength: getContentPlainText(targetContent).trim().length,\n targetTruncated:\n getContentPlainText(targetContent).trim().length > MAX_LOCALIZATION_TEXT_CHARS,\n }\n : {}),\n });\n };\n\n for (const surface of SURVEY_TRANSLATION_SURFACES) {\n const targetSurface = targetTranslations?.[surface] as Record<string, Content> | undefined;\n for (const [contentKey, sourceContent] of Object.entries(sourceTranslations[surface] ?? {})) {\n addSurface({\n surface,\n contentKey,\n sourceContent,\n targetContent: targetSurface?.[contentKey],\n });\n }\n }\n\n for (const item of survey.surveyItems) {\n for (const [contentKey, sourceContent] of Object.entries(\n sourceTranslations.itemTranslations?.[item.id] ?? {},\n )) {\n addSurface({\n itemId: item.id,\n itemKey: item.key,\n itemType: item.itemType,\n contentKey,\n sourceContent,\n targetContent: targetTranslations?.itemTranslations?.[item.id]?.[contentKey],\n });\n }\n }\n\n const missingCount = surfaces.filter((surface) => !surface.targetPresent).length;\n const filteredSurfaces = input.missingOnly\n ? surfaces.filter((surface) => !surface.targetPresent)\n : surfaces;\n const parsedCursor = Number.parseInt(input.cursor ?? \"0\", 10);\n const offset = Number.isFinite(parsedCursor) && parsedCursor >= 0 ? parsedCursor : 0;\n const limit = input.limit ?? 20;\n const page = filteredSurfaces.slice(offset, offset + limit);\n const nextOffset = offset + page.length;\n\n return {\n ok: true as const,\n result: {\n sourceLocale,\n targetLocale,\n missingOnly: input.missingOnly ?? false,\n contentCoverage:\n \"sourceText and targetText are previews. For sourceTruncated plain text, inspect raw-json paths: [sourceTextPath] and follow nextTextOffset with textOffset until complete before translating. Rich-text sourceContent is the complete canonical value. Never translate only a truncated preview or treat targetPresent as proof of translation completeness.\",\n totalSourceSurfaces: surfaces.length,\n totalAvailable: filteredSurfaces.length,\n missingCount,\n returned: page.length,\n ...(nextOffset < filteredSurfaces.length ? { nextCursor: String(nextOffset) } : {}),\n listOrdering: {\n surfaces:\n \"Survey-level translation surfaces first, then item translations in stored survey-item and source content-key order. Cursor pagination preserves this order only while the draft is unchanged; restart without a cursor after mutations.\",\n },\n surfaces: page,\n },\n };\n};\n\nconst resolveItemRef = (\n input: SurveyInspectInput,\n snapshot: SurveyAssistantSnapshot | undefined,\n) => {\n if (input.itemRef && input.itemRef !== \"selected\") {\n return input.itemRef;\n }\n\n return snapshot?.ui.selectedItemId;\n};\n\ntype AssetUsageSummary = {\n locale: string;\n scope: \"surveyCardContent\" | \"navigationContent\" | \"validationMessages\" | \"itemTranslation\";\n contentKey: string;\n blockIndex: number;\n itemId?: string;\n};\n\nconst listAssetUsageSummaries = (survey: RawSurvey) => {\n const usagesByAssetId = new Map<string, AssetUsageSummary[]>();\n const addContent = (\n content: Content | undefined,\n usage: Omit<AssetUsageSummary, \"blockIndex\">,\n ) => {\n for (const assetUsage of getAssetUsagesFromContent(content)) {\n const usages = usagesByAssetId.get(assetUsage.assetId) ?? [];\n usages.push({ ...usage, blockIndex: assetUsage.blockIndex });\n usagesByAssetId.set(assetUsage.assetId, usages);\n }\n };\n\n for (const [locale, localeTranslations] of Object.entries(survey.translations ?? {})) {\n for (const scope of [\"surveyCardContent\", \"navigationContent\", \"validationMessages\"] as const) {\n for (const [contentKey, content] of Object.entries(localeTranslations[scope] ?? {})) {\n addContent(content, { locale, scope, contentKey });\n }\n }\n for (const [itemId, itemTranslations] of Object.entries(\n localeTranslations.itemTranslations ?? {},\n )) {\n for (const [contentKey, content] of Object.entries(itemTranslations ?? {})) {\n addContent(content, {\n locale,\n scope: \"itemTranslation\",\n itemId,\n contentKey,\n });\n }\n }\n }\n\n return usagesByAssetId;\n};\n\nconst summarizeAssetSource = (asset: RawSurveyAsset) => ({\n type: asset.source.type,\n mediaType: asset.source.mediaType,\n});\n\nconst listAssets = (input: SurveyInspectInput, snapshot: SurveyAssistantSnapshot) => {\n const survey = snapshot.survey as RawSurvey;\n const usagesByAssetId = listAssetUsageSummaries(survey);\n const query = input.query?.trim().toLowerCase();\n const allAssets = Object.entries(survey.assets ?? {})\n .map(([assetId, asset]) => {\n const usages = usagesByAssetId.get(assetId) ?? [];\n return {\n assetId,\n kind: asset.kind,\n source: summarizeAssetSource(asset),\n ...(asset.metadata ? { metadata: asset.metadata } : {}),\n usageCount: usages.length,\n usages,\n };\n })\n .filter((asset) => {\n if (!query) return true;\n return [\n asset.assetId,\n asset.source.mediaType,\n asset.metadata?.name,\n asset.metadata?.filename,\n asset.metadata?.alt,\n ].some((value) => value?.toLowerCase().includes(query));\n })\n .sort((left, right) => left.assetId.localeCompare(right.assetId));\n\n const parsedCursor = Number.parseInt(input.cursor ?? \"0\", 10);\n const offset = Number.isFinite(parsedCursor) && parsedCursor >= 0 ? parsedCursor : 0;\n const limit = input.limit ?? 20;\n const assets = allAssets.slice(offset, offset + limit);\n const nextOffset = offset + assets.length;\n\n return {\n totalAvailable: allAssets.length,\n returned: assets.length,\n ...(nextOffset < allAssets.length ? { nextCursor: String(nextOffset) } : {}),\n listOrdering: {\n assets: \"Alphabetical by assetId; position has no survey meaning.\",\n \"assets[].usages\":\n \"Deterministic survey translation traversal order; position has no semantic meaning.\",\n },\n assets,\n };\n};\n\nexport const surveyInspectTool = createTool({\n id: TOOL_ID,\n description:\n \"Inspect the current request-scoped survey draft through one compact interface: current context, item search, item details, paged source/target localization surfaces, image assets with explicit asset IDs and usages, expression-reference diagnostics, or focused raw JSON. For expression diagnostics, valid means there are no blocking diagnostics; advisories remain counted. At turn start the draft equals the live snapshot; successful same-turn edits appear immediately.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Inspect survey\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveyInspectOutput> => {\n const input = inputData as SurveyInspectInput;\n const requestContext = context?.requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n action: input.action,\n reason: \"No editor snapshot was provided with this assistant turn.\",\n modelSummary: \"No survey draft is available for this turn.\",\n };\n }\n\n if (input.action === \"current-context\") {\n const inspection = runInspectionBackend(() =>\n inspectSurveyCurrentContext(\n {\n scopes: input.scopes ?? [\"summary\", \"selected-item\"],\n limit: input.limit,\n cursor: input.cursor,\n itemId: resolveItemRef(input, snapshot),\n query: input.query,\n outlineMode: input.outlineMode,\n },\n requestContext,\n ),\n );\n if (!inspection.ok) return inspectionBackendFailure(input.action, inspection.reason);\n const result = inspection.value;\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\n result,\n };\n }\n\n if (input.action === \"search-items\") {\n if (!input.query) {\n return {\n ok: false,\n action: input.action,\n reason: \"Search requires a query.\",\n modelSummary: \"Search requires a query.\",\n };\n }\n const query = input.query;\n\n const inspection = runInspectionBackend(() =>\n searchSurveyItems({ query, limit: input.limit, cursor: input.cursor }, requestContext),\n );\n if (!inspection.ok) return inspectionBackendFailure(input.action, inspection.reason);\n const result = inspection.value;\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\n result,\n };\n }\n\n if (input.action === \"item-details\") {\n const itemId = resolveItemRef(input, snapshot);\n if (!itemId) {\n return {\n ok: false,\n action: input.action,\n reason: \"No item reference was provided and no item is selected.\",\n modelSummary: \"No item reference was provided and no item is selected.\",\n };\n }\n\n const inspection = runInspectionBackend(() =>\n inspectSurveyItemDetails(\n {\n itemId,\n includeSurveyChildren: input.includeChildren ?? false,\n includeItemConfig: input.includeItemConfig ?? true,\n childrenLimit: input.limit,\n },\n requestContext,\n ),\n );\n if (!inspection.ok) return inspectionBackendFailure(input.action, inspection.reason);\n const result = inspection.value;\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\n result,\n };\n }\n\n if (input.action === \"expression-diagnostics\") {\n const allDiagnostics = analyzeSurveyAssistantExpressionReferences(\n snapshot.survey,\n snapshot.trustedCapabilities,\n );\n const itemId = input.itemRef ? resolveItemRef(input, snapshot) : undefined;\n const diagnostics = itemId\n ? allDiagnostics.filter((diagnostic) => diagnostic.ownerItemId === itemId)\n : allDiagnostics;\n const orderedDiagnostics = [...diagnostics].sort(\n (left, right) =>\n Number(isBlockingSurveyExpressionReferenceDiagnostic(right)) -\n Number(isBlockingSurveyExpressionReferenceDiagnostic(left)),\n );\n const blockingCount = diagnostics.filter(\n isBlockingSurveyExpressionReferenceDiagnostic,\n ).length;\n const advisoryCount = diagnostics.length - blockingCount;\n const limit = input.limit ?? 50;\n const limitedDiagnostics = orderedDiagnostics.slice(0, limit);\n const guidanceByDispositionAndCategory: ExpressionDiagnosticGuidanceCatalog = {};\n for (const diagnostic of orderedDiagnostics) {\n const byCategory = (guidanceByDispositionAndCategory[diagnostic.disposition] ??= {});\n byCategory[diagnostic.category] =\n getSurveyAssistantExpressionDiagnosticGuidance(diagnostic);\n }\n const result = {\n valid: blockingCount === 0,\n count: diagnostics.length,\n blockingCount,\n advisoryCount,\n diagnostics: limitedDiagnostics,\n guidanceByDispositionAndCategory,\n truncated: diagnostics.length > limit,\n };\n return {\n ok: true,\n action: input.action,\n modelSummary:\n diagnostics.length === 0\n ? \"No expression reference diagnostics were found in the current survey draft.\"\n : blockingCount === 0\n ? `${advisoryCount} advisory expression diagnostic${advisoryCount === 1 ? \" was\" : \"s were\"} found. Review each listed diagnostic according to its category-specific guidance.\\n${stringifyForModel(result)}`\n : `${blockingCount} blocking expression reference diagnostic${blockingCount === 1 ? \" was\" : \"s were\"} found${advisoryCount > 0 ? ` alongside ${advisoryCount} advisory expression diagnostic${advisoryCount === 1 ? \"\" : \"s\"}` : \"\"}. Repair every blocking location, preserve advisories unless their category-specific guidance or the user requires a change, then run expression-diagnostics again before claiming the blocking repair is complete.\\n${stringifyForModel(result)}`,\n result,\n };\n }\n\n if (input.action === \"localization\") {\n if (!input.targetLocale) {\n return {\n ok: false,\n action: input.action,\n reason: \"Localization inspection requires a targetLocale.\",\n modelSummary: \"Localization inspection requires a targetLocale.\",\n };\n }\n\n const localization = listLocalizationSurfaces(input, snapshot, input.targetLocale);\n if (!localization.ok) {\n return {\n ok: false,\n action: input.action,\n reason: localization.reason,\n modelSummary: localization.reason,\n };\n }\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(localization.result),\n result: localization.result,\n };\n }\n\n if (input.action === \"assets\") {\n const result = listAssets(input, snapshot);\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\n result,\n };\n }\n\n const itemId = input.itemRef ? resolveItemRef(input, snapshot) : undefined;\n const itemIdentifiers = itemId ? [itemId] : undefined;\n const requestedPaths = itemIdentifiers ? undefined : input.paths;\n const boundedPaths = requestedPaths?.slice(0, MAX_RAW_JSON_PATHS_PER_RESULT);\n const rawInspection = runInspectionBackend(() =>\n inspectRawSurvey(\n { paths: boundedPaths, itemIdentifiers, textOffset: input.textOffset },\n requestContext,\n ),\n );\n if (!rawInspection.ok) return inspectionBackendFailure(input.action, rawInspection.reason);\n const rawResult = rawInspection.value;\n const ignoredPathCount = itemIdentifiers ? (input.paths?.length ?? 0) : 0;\n const omittedPathCount = Math.max(\n 0,\n (requestedPaths?.length ?? 0) - (boundedPaths?.length ?? 0),\n );\n const requestCoverage =\n ignoredPathCount > 0 || omittedPathCount > 0\n ? {\n precedence: itemIdentifiers\n ? \"itemRef was resolved and inspected; explicit paths were ignored.\"\n : \"Explicit paths were inspected in request order.\",\n requestedPathCount: input.paths?.length ?? 0,\n inspectedPathCount: boundedPaths?.length ?? 0,\n ignoredPathCount,\n omittedPathCount,\n ...(omittedPathCount > 0\n ? {\n nextPaths: requestedPaths?.slice(\n MAX_RAW_JSON_PATHS_PER_RESULT,\n MAX_RAW_JSON_PATHS_PER_RESULT * 2,\n ),\n }\n : {}),\n recovery: itemIdentifiers\n ? \"Use a separate raw-json call without itemRef if the explicit paths are still needed.\"\n : \"Retry the returned nextPaths in a separate raw-json call if they are still needed.\",\n }\n : undefined;\n const result =\n requestCoverage && isRecord(rawResult) ? { ...rawResult, requestCoverage } : rawResult;\n const modelSummary = [\n requestCoverage\n ? `Raw JSON request normalized instead of rejected: ${JSON.stringify(requestCoverage)}`\n : undefined,\n stringifyForModel(result),\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"\\n\");\n\n return {\n ok: true,\n action: input.action,\n modelSummary,\n result,\n };\n },\n toModelOutput: (value) =>\n toTextModelOutput<SurveyInspectOutput>(value, (output) => output.modelSummary),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport type { SurveyAssistantRequestContext } from \"../request-context\";\nimport { toTextModelOutput } from \"./tool-model-output\";\n\nexport const TOOL_ID = \"survey_attachment\";\n\nconst inputSchema = z.object({\n documentIds: z\n .array(z.string().min(1))\n .min(1)\n .max(4)\n .optional()\n .describe(\"Stored attachment IDs to load completely when no page/section focus is needed.\"),\n documentRequests: z\n .array(\n z.object({\n documentId: z.string().min(1),\n pages: z\n .object({\n start: z.number().int().min(1).max(100_000),\n end: z.number().int().min(1).max(100_000),\n })\n .optional()\n .describe(\"One-based inclusive PDF page range to prioritize.\"),\n focus: z\n .string()\n .min(1)\n .max(300)\n .optional()\n .describe(\"Short section, question range, or fact to prioritize in the original file.\"),\n }),\n )\n .min(1)\n .max(4)\n .optional()\n .describe(\"Stored attachments with an optional bounded reading focus.\"),\n});\n\nconst outputSchema = z.object({\n loaded: z.array(\n z.object({\n id: z.string(),\n filename: z.string(),\n mediaType: z.string(),\n pages: z.object({ start: z.number().int(), end: z.number().int() }).optional(),\n focus: z.string().optional(),\n }),\n ),\n warnings: z.array(z.string()).optional(),\n});\n\nexport const surveyAttachmentTool = createTool({\n id: TOOL_ID,\n description:\n \"Attach only the stored PDFs or images needed for the current task to the next native model request. For source continuation, use this before conversational recall and provide a page or section focus when known. The original file remains authoritative.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Load chat attachment\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context) => {\n const requestContext = context?.requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const access = requestContext?.get(\"attachmentAccess\");\n if (!access) return { loaded: [] };\n\n const warnings: string[] = [];\n const requests = new Map<\n string,\n { pages?: { start: number; end: number }; focus?: string }\n >();\n for (const documentId of inputData.documentIds ?? []) requests.set(documentId, {});\n for (const request of inputData.documentRequests ?? []) {\n if (request.pages && request.pages.end < request.pages.start) {\n warnings.push(\n `Ignored invalid page range ${request.pages.start}-${request.pages.end} for ${request.documentId}.`,\n );\n requests.set(request.documentId, {\n ...(request.focus ? { focus: request.focus } : {}),\n });\n continue;\n }\n requests.set(request.documentId, {\n ...(request.pages ? { pages: request.pages } : {}),\n ...(request.focus ? { focus: request.focus } : {}),\n });\n }\n const requestedIds = [...requests.keys()];\n const authorized = access.documents.filter((document) => requestedIds.includes(document.id));\n const attachments = await access.load(authorized.map((document) => document.id));\n access.selectedAttachments.splice(0, access.selectedAttachments.length, ...attachments);\n\n return {\n loaded: authorized.map((document) => {\n const request = requests.get(document.id);\n const pages = document.mediaType === \"application/pdf\" ? request?.pages : undefined;\n if (request?.pages && !pages) {\n warnings.push(`Ignored a PDF page focus for non-PDF attachment ${document.name}.`);\n }\n return {\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n ...(pages ? { pages } : {}),\n ...(request?.focus ? { focus: request.focus } : {}),\n };\n }),\n ...(warnings.length > 0 ? { warnings } : {}),\n };\n },\n toModelOutput: (value) =>\n toTextModelOutput(\n value,\n (output: z.infer<typeof outputSchema>) => {\n if (output.loaded.length === 0) {\n return [\n \"No authorized stored attachment was loaded. Do not infer source content from conversation memory.\",\n ...(output.warnings ?? []).map((warning) => `Warning: ${warning}`),\n \"Inspect the available attachment ids and retry with only the source documents needed for this task.\",\n ].join(\"\\n\");\n }\n const focuses = output.loaded\n .map((document) => {\n const details = [\n document.pages\n ? `prioritize one-based pages ${document.pages.start}-${document.pages.end}`\n : undefined,\n document.focus ? `focus: ${document.focus}` : undefined,\n ].filter(Boolean);\n return details.length > 0 ? `- ${document.filename}: ${details.join(\"; \")}` : undefined;\n })\n .filter((line): line is string => Boolean(line));\n return [\n \"The selected complete original attachments are included in this model input. Read them directly now and continue the user's task. Conversation memory is not a lossless source.\",\n focuses.length > 0\n ? `Requested reading focus (the complete original remains authoritative):\\n${focuses.join(\"\\n\")}`\n : undefined,\n ...(output.warnings ?? []).map((warning) => `Warning: ${warning}`),\n \"Do not claim that successfully loaded content is unavailable or ask the user to paste extracted text.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n },\n ),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport {\n auditSurvey,\n type SurveyAssistantEngineContext,\n type SurveyAuditReport,\n} from \"../../engine\";\nimport { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_audit\";\n\nconst inputSchema = z.object({\n sourceLocale: z\n .string()\n .min(1)\n .optional()\n .describe(\"Locale treated as the source when checking translation completeness.\"),\n targetLocales: z.array(z.string().min(1)).max(20).optional(),\n maxFindings: z.number().int().min(1).max(300).default(120).optional(),\n keyReviewOffset: z\n .number()\n .int()\n .nonnegative()\n .default(0)\n .optional()\n .describe(\"Zero-based offset for the qualitative key/content review evidence.\"),\n keyReviewLimit: z\n .number()\n .int()\n .min(1)\n .max(50)\n .default(30)\n .optional()\n .describe(\"Number of item, choice-option, and form-field key/content pairs to return.\"),\n reason: z.string().max(500).optional(),\n});\n\nconst outputSchema = z.object({\n ok: z.boolean(),\n reason: z.string().optional(),\n report: z.unknown().optional(),\n});\n\nconst MAX_AUDIT_MODEL_GROUPS = 16;\nconst MAX_AUDIT_MODEL_EXAMPLES = 12;\nconst MAX_AUDIT_MESSAGE_CHARACTERS = 300;\n\nconst previewAuditMessage = (message: string) => {\n const characters = [...message];\n if (characters.length <= MAX_AUDIT_MESSAGE_CHARACTERS) return message;\n return `${characters.slice(0, MAX_AUDIT_MESSAGE_CHARACTERS).join(\"\")}… [${characters.length} characters total]`;\n};\n\nconst formatAuditForModel = (output: z.infer<typeof outputSchema>) => {\n if (!output.ok || !output.report || typeof output.report !== \"object\") {\n return output.reason ?? \"The deterministic survey audit could not be completed.\";\n }\n\n const report = output.report as SurveyAuditReport;\n const groups = new Map<\n string,\n { category: string; code: string; count: number; severity: string }\n >();\n for (const finding of report.findings) {\n const key = `${finding.severity}\\u0000${finding.category}\\u0000${finding.code}`;\n const group = groups.get(key) ?? {\n category: finding.category,\n code: finding.code,\n count: 0,\n severity: finding.severity,\n };\n group.count += 1;\n groups.set(key, group);\n }\n\n const groupedFindings = [...groups.values()].sort(\n (left, right) =>\n right.count - left.count ||\n left.severity.localeCompare(right.severity) ||\n left.code.localeCompare(right.code),\n );\n const shownGroups = groupedFindings.slice(0, MAX_AUDIT_MODEL_GROUPS);\n const examples = report.findings.slice(0, MAX_AUDIT_MODEL_EXAMPLES);\n\n return [\n `Deterministic survey audit: ${report.findingCount} finding${report.findingCount === 1 ? \"\" : \"s\"} (errors=${report.summary.error}, warnings=${report.summary.warning}, info=${report.summary.info}).`,\n `Finding coverage returned by the audit: ${report.findings.length}/${report.findingCount}${report.truncated ? \" (bounded)\" : \"\"}.`,\n `Metrics: ${JSON.stringify(report.metrics)}.`,\n shownGroups.length > 0\n ? `Finding groups (${shownGroups.length}/${groupedFindings.length} shown):\\n${shownGroups\n .map(\n (group) =>\n `- ${group.severity}/${group.category}/${group.code}: ${group.count} returned finding${group.count === 1 ? \"\" : \"s\"}`,\n )\n .join(\"\\n\")}`\n : \"Finding groups: none.\",\n examples.length > 0\n ? `Ordered examples (${examples.length}/${report.findings.length} returned findings shown):\\n${examples\n .map((finding) => {\n const location = [finding.itemId, finding.locale, finding.contentKey]\n .filter(Boolean)\n .join(\":\");\n return `- [${finding.severity}] ${finding.code}${location ? ` (${location})` : \"\"}: ${previewAuditMessage(finding.message)}${finding.suggestion ? ` Guidance: ${previewAuditMessage(finding.suggestion)}` : \"\"}`;\n })\n .join(\"\\n\")}`\n : undefined,\n report.qualityReviewPrinciples.length > 0\n ? `Qualitative review rubric:\\n${report.qualityReviewPrinciples\n .map((principle) => `- ${principle.id}: ${principle.prompt}`)\n .join(\"\\n\")}`\n : undefined,\n report.keyReview.entries.length > 0\n ? `Key/content review evidence (${report.keyReview.offset + 1}-${report.keyReview.offset + report.keyReview.returnedEntryCount} of ${report.keyReview.entryCount}, source locale ${report.keyReview.sourceLocale ?? \"unavailable\"}${report.keyReview.truncated ? \"; more pages available\" : \"\"}):\\n${report.keyReview.entries\n .map((entry) => {\n const content = entry.content\n ? `; current content=${JSON.stringify(previewAuditMessage(entry.content))}`\n : \"; current content unavailable\";\n return `- ${entry.kind} item=${entry.itemId} itemKey=${JSON.stringify(entry.itemKey)} key=${JSON.stringify(entry.key)} (${entry.keySource})${entry.contentKey ? ` contentKey=${entry.contentKey}` : \"\"}${content}`;\n })\n .join(\"\\n\")}\\n${report.keyReview.note}`\n : `Key/content review evidence: none returned (${report.keyReview.entryCount} total entries).`,\n report.note,\n \"This audit checks the current survey deterministically. It does not compare the draft with an attached source document, so a clean audit does not establish source fidelity or completeness.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\\n\");\n};\n\nexport const surveyAuditTool = createTool({\n id: TOOL_ID,\n description:\n \"Audit the current survey for deterministic structural, content, localization, expression-reference, response, and asset issues, and return a questionnaire-quality rubric plus paged key/content evidence for qualitative consistency review. This is read-only and is not psychometric validation.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Audit survey\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (input, context) => {\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantEngineContext | undefined;\n if (!snapshot)\n return { ok: false, reason: \"No live editor snapshot is available for this turn.\" };\n return { ok: true, report: auditSurvey(snapshot, input) };\n },\n toModelOutput: (value) => toTextModelOutput(value, formatAuditForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport {\n getAssetUsagesFromContent,\n type Content,\n type RawSurvey,\n} from \"@case-framework/survey-core\";\nimport { z } from \"zod\";\nimport { surveyChangeSetSchema, type SurveyChangeSet, type SurveyOperation } from \"../../protocol\";\nimport { createSurveyChangeSet, type SurveyAssistantEngineContext } from \"../../engine\";\nimport {\n getSurveyAssistantEngineContext,\n requireSurveyAssistantTurnState,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { toTextModelOutput } from \"./tool-model-output\";\n\nimport { collectSurveyOperationRecoveryTargets } from \"../../engine/mutation-recovery\";\nimport { retryOfChangeIdsSchema, summarizePendingRepairs } from \"./mutation-recovery\";\n\nexport const TOOL_ID = \"survey_asset\";\n\nconst inputSchema = z\n .object({\n retryOfChangeIds: retryOfChangeIdsSchema,\n action: z.enum([\"import-attachment\", \"update-metadata\", \"remove\"]),\n documentId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Stored attachment id for import-attachment.\"),\n assetId: z.string().min(1).max(240).optional(),\n name: z.string().max(500).nullable().optional(),\n filename: z.string().max(500).nullable().optional(),\n alt: z.string().max(2000).nullable().optional(),\n summary: z.string().min(1).max(500),\n })\n .strict();\n\nconst slug = (value: string) =>\n value\n .toLowerCase()\n .replace(/\\.[^.]+$/, \"\")\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 100) || \"image\";\n\nconst OMITTED_EMBEDDED_IMAGE_DATA = \"[embedded image data omitted from transcript]\";\n\nconst getAssetReferenceLabels = (\n snapshot: SurveyAssistantEngineContext | undefined,\n assetId: string,\n): string[] => {\n const translations = (snapshot?.survey as RawSurvey | undefined)?.translations;\n if (!translations) return [];\n\n const references: string[] = [];\n const inspectContent = (content: Content | undefined, label: string) => {\n if (getAssetUsagesFromContent(content).some((usage) => usage.assetId === assetId)) {\n references.push(label);\n }\n };\n\n for (const [locale, localeTranslations] of Object.entries(translations)) {\n for (const surface of [\n \"surveyCardContent\",\n \"navigationContent\",\n \"validationMessages\",\n ] as const) {\n for (const [contentKey, content] of Object.entries(localeTranslations[surface] ?? {})) {\n inspectContent(content, `${locale}:${surface}:${contentKey}`);\n }\n }\n for (const [itemId, itemTranslations] of Object.entries(\n localeTranslations.itemTranslations ?? {},\n )) {\n for (const [contentKey, content] of Object.entries(itemTranslations ?? {})) {\n inspectContent(content, `${locale}:item:${itemId}:${contentKey}`);\n }\n }\n }\n\n return references;\n};\n\nconst getToolOutput = (value: unknown): SurveyChangeSet =>\n value && typeof value === \"object\" && \"output\" in value && value.output !== undefined\n ? (value.output as SurveyChangeSet)\n : (value as SurveyChangeSet);\n\nconst describeAssetOperation = (operation: SurveyOperation) => {\n switch (operation.kind) {\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return `${operation.kind} ${operation.assetId}`;\n default:\n return operation.kind;\n }\n};\n\nconst summarizeAssetChange = (event: SurveyChangeSet) => {\n const lines = [\n `${event.status === \"validated\" ? \"Validated\" : \"Rejected\"} survey asset change: ${event.summary}`,\n ];\n\n if (event.status === \"validated\") {\n lines.push(\n `Draft updated (${event.operations.length} total operation${event.operations.length === 1 ? \"\" : \"s\"}); the live editor remains unchanged until turn completion. Embedded image bytes remain available to the application and were omitted from model context.`,\n );\n const importedAssetIds = event.operations\n .filter((operation) => operation.kind === \"set-image-asset\")\n .map((operation) => operation.assetId);\n if (importedAssetIds.length > 0) {\n lines.push(\n `Imported: ${event.operations\n .filter((operation) => operation.kind === \"set-image-asset\")\n .map(describeAssetOperation)\n .join(\", \")}`,\n );\n lines.push(`Asset id to reference: ${importedAssetIds.join(\", \")}`);\n lines.push(\n \"The asset is now available to later mutation calls in this turn. To use it in a new item, reference it from that item's create-item translation. If a later delta is rejected, fix only that delta; this import remains in the draft.\",\n );\n lines.push(\n `New info-item image source: { \"type\": \"asset\", \"assetId\": \"${importedAssetIds[0]}\" }. Embed the canonical image block inside the create-item translation richTextBlocks array.`,\n );\n lines.push(\n `New info-item translation example: { \"locale\": \"<selected-locale>\", \"contentKey\": \"content\", \"richTextBlocks\": [{ \"type\": \"image\", \"source\": { \"type\": \"asset\", \"assetId\": \"${importedAssetIds[0]}\" }, \"alt\": \"<meaningful description>\" }] }.`,\n );\n }\n }\n if (event.validation.issues.length > 0) {\n lines.push(\n `Issues:\\n${event.validation.issues.map((issue) => `- ${issue.code}: ${issue.message}`).join(\"\\n\")}`,\n );\n }\n if (event.validation.warnings.length > 0) {\n lines.push(\n `Warnings:\\n${event.validation.warnings.map((warning) => `- ${warning.code}: ${warning.message}`).join(\"\\n\")}`,\n );\n }\n\n lines.push(...summarizePendingRepairs(event));\n return lines.join(\"\\n\");\n};\n\nconst redactEmbeddedImageOperation = (operation: SurveyOperation): SurveyOperation =>\n operation.kind === \"set-image-asset\"\n ? {\n ...operation,\n asset: {\n ...operation.asset,\n source: {\n ...operation.asset.source,\n data: OMITTED_EMBEDDED_IMAGE_DATA,\n },\n },\n }\n : operation;\n\nconst redactAssetChangeForTranscript = (event: SurveyChangeSet): SurveyChangeSet => ({\n ...event,\n operations: event.operations.map(redactEmbeddedImageOperation),\n validation: {\n ...event.validation,\n normalizedOperations: event.validation.normalizedOperations.map(redactEmbeddedImageOperation),\n },\n});\n\nexport const surveyAssetTool = createTool({\n id: TOOL_ID,\n description:\n \"Import an attached image into the request-scoped survey draft, or update/remove an image asset. Successful calls accumulate automatically. Later mutations may reference an imported asset id. To delete references and an asset atomically, use one survey_change delta with reference removals first and remove-image-asset last.\",\n inputSchema,\n outputSchema: surveyChangeSetSchema,\n mcp: {\n annotations: {\n title: \"Prepare survey asset change\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n execute: async (input, context) => {\n const requestContext = context?.requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const { turnDraft, turnId } = requireSurveyAssistantTurnState(requestContext);\n const snapshot = getSurveyAssistantEngineContext(requestContext) as\n | SurveyAssistantEngineContext\n | undefined;\n let operation: SurveyOperation;\n\n if (input.action === \"import-attachment\") {\n if (!input.documentId) throw new Error(\"import-attachment requires documentId.\");\n const access = requestContext?.get(\"attachmentAccess\");\n const manifest = access?.documents.find((entry) => entry.id === input.documentId);\n if (!access || !manifest)\n throw new Error(`Attachment \"${input.documentId}\" is not available for this turn.`);\n if (!manifest.mediaType.startsWith(\"image/\"))\n throw new Error(`Attachment \"${manifest.name}\" is not an image.`);\n const [loaded] = await access.load([input.documentId]);\n if (!loaded) throw new Error(`Attachment \"${manifest.name}\" could not be loaded.`);\n const base = input.assetId ?? slug(manifest.name);\n let assetId = base;\n let suffix = 2;\n const stagedAssetIds = new Set(\n turnDraft.draftOperations.flatMap((draftOperation) =>\n draftOperation.kind === \"set-image-asset\" ? [draftOperation.assetId] : [],\n ),\n );\n while (snapshot?.survey.assets?.[assetId] || stagedAssetIds.has(assetId)) {\n assetId = `${base}-${suffix++}`;\n }\n operation = {\n kind: \"set-image-asset\",\n assetId,\n asset: {\n kind: \"image\",\n source: {\n type: \"embedded\",\n mediaType: loaded.mediaType,\n encoding: \"base64\",\n data: loaded.data,\n },\n metadata: {\n filename: input.filename ?? loaded.filename,\n name: input.name ?? undefined,\n alt: input.alt ?? undefined,\n },\n },\n };\n } else if (input.action === \"update-metadata\") {\n if (!input.assetId) throw new Error(\"update-metadata requires assetId.\");\n operation = {\n kind: \"update-image-asset-metadata\",\n assetId: input.assetId,\n metadata: { name: input.name, filename: input.filename, alt: input.alt },\n };\n } else {\n if (!input.assetId) throw new Error(\"remove requires assetId.\");\n operation = { kind: \"remove-image-asset\", assetId: input.assetId };\n }\n\n let event = createSurveyChangeSet({\n operations: [operation],\n snapshot,\n summary: input.summary,\n turnId,\n });\n\n if (operation.kind === \"remove-image-asset\") {\n const referenceLabels = getAssetReferenceLabels(snapshot, operation.assetId);\n if (referenceLabels.length > 0) {\n event = surveyChangeSetSchema.parse({\n ...event,\n status: \"rejected\",\n validation: {\n ...event.validation,\n valid: false,\n issues: [\n ...event.validation.issues,\n {\n severity: \"error\",\n code: \"image-asset-still-referenced\",\n message:\n `Image asset \"${operation.assetId}\" is still referenced by ${referenceLabels.slice(0, 3).join(\", \")}. ` +\n \"Prepare one survey_change delta containing every reference-removal operation first and remove-image-asset last.\",\n operationIndex: 0,\n },\n ],\n normalizedOperations: [],\n },\n });\n }\n if (event.status === \"rejected\") {\n return turnDraft.reject(\n event,\n collectSurveyOperationRecoveryTargets([operation], snapshot),\n );\n }\n }\n\n return turnDraft.stage({\n retryOfChangeIds: input.retryOfChangeIds,\n operations: [operation],\n snapshot,\n summary: input.summary,\n });\n },\n transform: {\n transcript: {\n output: ({ output }) =>\n output ? redactAssetChangeForTranscript(getToolOutput(output)) : output,\n },\n },\n toModelOutput: (value) => toTextModelOutput(value, summarizeAssetChange),\n});\n","import {\n surveyAuthoringReferenceTool,\n TOOL_ID as AUTHORING_REFERENCE_TOOL_ID,\n} from \"./survey-authoring-reference-tool\";\nimport { surveyChangeTool, TOOL_ID as CHANGE_TOOL_ID } from \"./survey-change-tool\";\nimport { surveyExpressionTool, TOOL_ID as EXPRESSION_TOOL_ID } from \"./survey-expression-tool\";\nimport { surveyInspectTool, TOOL_ID as INSPECT_TOOL_ID } from \"./survey-inspect-tool\";\nimport { surveyAttachmentTool, TOOL_ID as ATTACHMENT_TOOL_ID } from \"./survey-attachment-tool\";\nimport { surveyAuditTool, TOOL_ID as AUDIT_TOOL_ID } from \"./survey-audit-tool\";\nimport { surveyAssetTool, TOOL_ID as ASSET_TOOL_ID } from \"./survey-asset-tool\";\n\nexport const SURVEY_ASSISTANT_TOOL_IDS = [\n INSPECT_TOOL_ID,\n CHANGE_TOOL_ID,\n EXPRESSION_TOOL_ID,\n AUTHORING_REFERENCE_TOOL_ID,\n ATTACHMENT_TOOL_ID,\n AUDIT_TOOL_ID,\n ASSET_TOOL_ID,\n] as const;\n\n// Mastra 1.61 promotes `strict: true` on any V2 tool to request-wide OpenAI strict mode.\n// Keep this registry non-strict: mutation tools intentionally use compact opaque arrays that their\n// executors validate canonically, rather than exposing full mutation unions as provider schemas.\nexport const surveyAssistantTools = Object.freeze({\n [INSPECT_TOOL_ID]: surveyInspectTool,\n [CHANGE_TOOL_ID]: surveyChangeTool,\n [AUTHORING_REFERENCE_TOOL_ID]: surveyAuthoringReferenceTool,\n [EXPRESSION_TOOL_ID]: surveyExpressionTool,\n [ATTACHMENT_TOOL_ID]: surveyAttachmentTool,\n [AUDIT_TOOL_ID]: surveyAuditTool,\n [ASSET_TOOL_ID]: surveyAssetTool,\n});\n\nexport { surveyAuditTool } from \"./survey-audit-tool\";\nexport { surveyAssetTool } from \"./survey-asset-tool\";\n"],"mappings":";;;;;;;;;;AAQA,MAAa,yBAAyB,UACnC,uBAA6C,SAAS,MAAM;AAE/D,MAAa,0CAA0C,CAAC,WAAW,OAAO;AAM1E,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;AAEtE,MAAM,wBACJ,QACA,iBACqB;CACrB,MAAM,cACJ,OAAO,OAAO,gBAAgB,WAC1B,OAAO,cACP,eACE,wBAAwB,aAAa,MACrC;CACR,MAAM,OAAO,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO,KAAA;AAE7D,QAAO;EACL,GAAI,OAAO,EAAE,MAAM,GAAG,EAAE;EACxB,aAAa,GAAG,YAAY;EAC7B;;AAGH,MAAM,qBAAqB,OAAgB,cAAuB,QAAQ,MAAe;AACvF,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,KAAK,UAAU,kBAAkB,OAAO,cAAc,QAAQ,EAAE,CAAC;AAEhF,KAAI,CAACA,WAAS,MAAM,CAClB,QAAO;AAGT,KAAI,OAAO,MAAM,SAAS,SACxB,QAAO,EACL,aACE,oHACH;AAGH,KAAI,SAAS,KAAK,KAAK,UAAU,MAAM,CAAC,SAAS,KAC/C,QAAO,qBAAqB,OAAO,aAAa;CAGlD,MAAM,UAA4B,EAAE;AACpC,MAAK,MAAM,OAAO;EAChB;EACA;EAC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