@case-framework/survey-assistant 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{authoring-references-DYuOAdVx.mjs → authoring-references-yyYC4Ydi.mjs} +9 -3
- package/dist/authoring-references-yyYC4Ydi.mjs.map +1 -0
- package/dist/{capabilities-DlC1l6qy.d.mts → capabilities-CnsVuJ1k.d.mts} +12 -4
- package/dist/capabilities-CnsVuJ1k.d.mts.map +1 -0
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +38 -4
- package/dist/capabilities-default.mjs.map +1 -1
- package/dist/{constants-D-5m_KGB.d.mts → constants-DrGZXtQf.d.mts} +12 -7
- package/dist/constants-DrGZXtQf.d.mts.map +1 -0
- package/dist/{controller-proxy-0WJZUZYx.mjs → controller-proxy-CpkQRezb.mjs} +3 -2
- package/dist/controller-proxy-CpkQRezb.mjs.map +1 -0
- package/dist/{controller-proxy-Hkuub9dt.d.mts → controller-proxy-DmBdzqKs.d.mts} +5 -2
- package/dist/controller-proxy-DmBdzqKs.d.mts.map +1 -0
- package/dist/{digest-BvXpeWcR.d.mts → digest-Dyjch_sC.d.mts} +2 -2
- package/dist/{digest-BvXpeWcR.d.mts.map → digest-Dyjch_sC.d.mts.map} +1 -1
- package/dist/digest.d.mts +1 -1
- package/dist/{engine-0AJrv0hI.mjs → engine-CWTuN3o2.mjs} +866 -663
- package/dist/engine-CWTuN3o2.mjs.map +1 -0
- package/dist/engine.d.mts +3 -3
- package/dist/engine.mjs +3 -3
- package/dist/fair-guidance-CEdJYccK.mjs +21 -0
- package/dist/fair-guidance-CEdJYccK.mjs.map +1 -0
- package/dist/form-authoring-DCd9XfXf.mjs +155 -0
- package/dist/form-authoring-DCd9XfXf.mjs.map +1 -0
- package/dist/{index-JXH-t2EJ.d.mts → index-Bo4dHAo8.d.mts} +68 -6
- package/dist/index-Bo4dHAo8.d.mts.map +1 -0
- package/dist/{index-MEOL9_Gr.d.mts → index-D4OitUg4.d.mts} +5 -430
- package/dist/index-D4OitUg4.d.mts.map +1 -0
- package/dist/{index-BcyfBeDj.d.mts → index-DZk20e3k.d.mts} +44 -22
- package/dist/index-DZk20e3k.d.mts.map +1 -0
- package/dist/{index-CneD8ibB.d.mts → index-Dxgg0-D_.d.mts} +12 -3
- package/dist/index-Dxgg0-D_.d.mts.map +1 -0
- package/dist/lifecycle-DWv5CiSu.d.mts +523 -0
- package/dist/lifecycle-DWv5CiSu.d.mts.map +1 -0
- package/dist/{memory-thread-repository-1ocPOda8.mjs → memory-thread-repository-acbz6HZJ.mjs} +181 -26
- package/dist/memory-thread-repository-acbz6HZJ.mjs.map +1 -0
- package/dist/{protocol-DpCYmCjr.mjs → protocol-DATvkr1S.mjs} +125 -6
- package/dist/protocol-DATvkr1S.mjs.map +1 -0
- package/dist/protocol.d.mts +4 -3
- package/dist/protocol.mjs +2 -2
- package/dist/{react-DXK5zWNo.mjs → react-Br5YE8H-.mjs} +132 -12
- package/dist/react-Br5YE8H-.mjs.map +1 -0
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.mjs +2 -2
- package/dist/references/assistant-operations.md +13 -18
- package/dist/references/embedded-forms.md +41 -2
- package/dist/references/expressions.md +17 -9
- package/dist/references/fair-by-design.md +80 -0
- package/dist/references/item-types.md +19 -3
- package/dist/references/localization.md +7 -4
- package/dist/references/source-material-surveys.md +6 -4
- package/dist/{request-context-BBzU3VdG.mjs → request-context-BEjnaaFr.mjs} +10 -5
- package/dist/request-context-BEjnaaFr.mjs.map +1 -0
- package/dist/server-agent.d.mts +44 -22
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +71 -14
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +22 -11
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +47 -19
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +6 -4
- package/dist/server-tasks.mjs.map +1 -1
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +16 -7
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -4
- package/dist/storage-postgres.d.mts +1 -1
- package/dist/{tasks-DcfQNJwO.d.mts → tasks-DQgL449A.d.mts} +8 -4
- package/dist/tasks-DQgL449A.d.mts.map +1 -0
- package/dist/{thread-documents-BlxNjc7S.d.mts → thread-documents-Dvo6XS7o.d.mts} +1 -1
- package/dist/{thread-documents-BlxNjc7S.d.mts.map → thread-documents-Dvo6XS7o.d.mts.map} +1 -1
- package/dist/{thread-handlers-uddXwQjp.d.mts → thread-handlers-CeYl45xG.d.mts} +9 -4
- package/dist/thread-handlers-CeYl45xG.d.mts.map +1 -0
- package/dist/{tools-wgLen05n.mjs → tools-Dg9HZrYU.mjs} +404 -78
- package/dist/tools-Dg9HZrYU.mjs.map +1 -0
- package/dist/ui.css +2 -2
- package/dist/ui.d.mts +94 -10
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +343 -112
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +74 -6
- package/package.json +25 -19
- package/dist/authoring-references-DYuOAdVx.mjs.map +0 -1
- package/dist/capabilities-DKbNCnBf.mjs +0 -66
- package/dist/capabilities-DKbNCnBf.mjs.map +0 -1
- package/dist/capabilities-DlC1l6qy.d.mts.map +0 -1
- package/dist/constants-D-5m_KGB.d.mts.map +0 -1
- package/dist/controller-proxy-0WJZUZYx.mjs.map +0 -1
- package/dist/controller-proxy-Hkuub9dt.d.mts.map +0 -1
- package/dist/engine-0AJrv0hI.mjs.map +0 -1
- package/dist/index-BcyfBeDj.d.mts.map +0 -1
- package/dist/index-CneD8ibB.d.mts.map +0 -1
- package/dist/index-JXH-t2EJ.d.mts.map +0 -1
- package/dist/index-MEOL9_Gr.d.mts.map +0 -1
- package/dist/memory-thread-repository-1ocPOda8.mjs.map +0 -1
- package/dist/protocol-DpCYmCjr.mjs.map +0 -1
- package/dist/react-DXK5zWNo.mjs.map +0 -1
- package/dist/request-context-BBzU3VdG.mjs.map +0 -1
- package/dist/tasks-DcfQNJwO.d.mts.map +0 -1
- package/dist/thread-handlers-uddXwQjp.d.mts.map +0 -1
- package/dist/tools-wgLen05n.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"request-context-BBzU3VdG.mjs","names":[],"sources":["../src/server/request-context.ts"],"sourcesContent":["import {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_THREAD_ID_KEY,\n RequestContext,\n} from \"@mastra/core/request-context\";\nimport {\n surveyAssistantSnapshotPayloadSchema,\n surveyDocumentVersionSchema,\n type SurveyDocumentSnapshot,\n type SurveyDocumentVersion,\n} from \"../protocol\";\nimport {\n createSurveyAssistantEngineContext,\n TurnSurveyDraft,\n type SurveyAssistantCapabilitySet,\n type SurveyAssistantEngineContext,\n} from \"../engine\";\nimport { defaultSurveyAssistantCapabilitySet } from \"../capabilities/default\";\nimport type {\n SurveyAssistantAttachmentAccess,\n SurveyAssistantModelAttachment,\n} from \"./thread-documents\";\n\nexport interface SurveyAssistantInvocationContext {\n kind: \"chat\";\n}\n\nexport interface SurveyAssistantIdentityContext {\n authority: \"experimental-client-request\" | \"authenticated-host\";\n resourceId: string;\n surveyId?: string;\n threadId: string;\n}\n\nexport interface SurveyAssistantModelSelection {\n id: string;\n model: string;\n}\n\nexport type SurveyAssistantDocumentTransition =\n | { status: \"no-baseline\" }\n | {\n status: \"session-changed\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n }\n | {\n status: \"unchanged\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n capabilitiesChanged: boolean;\n }\n | {\n status: \"changed\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n historyDirection: \"backward\" | \"forward\" | \"same-index\";\n recordedSources: Array<\"user\" | \"system\" | \"assistant\">;\n capabilitiesChanged: boolean;\n };\n\nexport interface SurveyAssistantRequestContext {\n invocation: SurveyAssistantInvocationContext;\n turnId: string;\n turnDraft: TurnSurveyDraft;\n identity: SurveyAssistantIdentityContext;\n authenticatedResourceId?: string;\n authorizedThreadId?: string;\n applyPolicy?: \"auto\" | \"review\" | \"deny\";\n mastra__resourceId?: string;\n mastra__threadId?: string;\n documentTransition?: SurveyAssistantDocumentTransition;\n engineContext?: SurveyAssistantEngineContext;\n documentSnapshot?: SurveyDocumentSnapshot;\n modelAttachments?: SurveyAssistantModelAttachment[];\n attachmentAccess?: SurveyAssistantAttachmentAccess;\n modelSelection?: SurveyAssistantModelSelection;\n}\n\nexport const parseSurveyAssistantSnapshot = (value: unknown): SurveyDocumentSnapshot | null => {\n if (value === undefined || value === null) {\n return null;\n }\n\n return surveyAssistantSnapshotPayloadSchema.parse(value);\n};\n\nexport const parseSurveyAssistantPreviousSettledVersion = (\n value: unknown,\n): SurveyDocumentVersion | null => {\n if (value === undefined || value === null) {\n return null;\n }\n\n return surveyDocumentVersionSchema.parse(value);\n};\n\nexport const deriveSurveyAssistantDocumentTransition = ({\n current,\n previous,\n}: {\n current: SurveyDocumentSnapshot | null;\n previous: SurveyDocumentVersion | null;\n}): SurveyAssistantDocumentTransition | undefined => {\n if (!current) return undefined;\n if (!previous) return { status: \"no-baseline\" };\n\n const previousHistoryIndex = previous.historyIndex;\n const currentHistoryIndex = current.version.historyIndex;\n if (previous.sessionId !== current.version.sessionId) {\n return {\n status: \"session-changed\",\n previousHistoryIndex,\n currentHistoryIndex,\n };\n }\n\n const capabilitiesChanged = previous.capabilityDigest !== current.version.capabilityDigest;\n if (previous.contentHash === current.version.contentHash) {\n return {\n status: \"unchanged\",\n previousHistoryIndex,\n currentHistoryIndex,\n capabilitiesChanged,\n };\n }\n\n const historyDirection =\n currentHistoryIndex > previousHistoryIndex\n ? \"forward\"\n : currentHistoryIndex < previousHistoryIndex\n ? \"backward\"\n : \"same-index\";\n const recordedSources =\n historyDirection === \"forward\"\n ? [\n ...new Set(\n (current.ui.history?.recent ?? [])\n .filter(\n (entry) => entry.index > previousHistoryIndex && entry.index <= currentHistoryIndex,\n )\n .flatMap((entry) => (entry.source ? [entry.source] : [])),\n ),\n ]\n : [];\n\n return {\n status: \"changed\",\n previousHistoryIndex,\n currentHistoryIndex,\n historyDirection,\n recordedSources,\n capabilitiesChanged,\n };\n};\n\nexport const buildSurveyAssistantRequestContext = ({\n turnDraft,\n identity,\n snapshot,\n previousSettledVersion = null,\n trustedCapabilities = defaultSurveyAssistantCapabilitySet,\n attachmentAccess,\n modelAttachments = [],\n modelSelection,\n}: {\n turnDraft: TurnSurveyDraft;\n identity: SurveyAssistantIdentityContext;\n snapshot: SurveyDocumentSnapshot | null;\n previousSettledVersion?: SurveyDocumentVersion | null;\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n attachmentAccess?: SurveyAssistantAttachmentAccess;\n modelAttachments?: SurveyAssistantModelAttachment[];\n modelSelection?: SurveyAssistantModelSelection;\n}): RequestContext<SurveyAssistantRequestContext> => {\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n\n requestContext.set(\"invocation\", { kind: \"chat\" });\n requestContext.set(\"turnId\", turnDraft.turnId);\n requestContext.set(\"turnDraft\", turnDraft);\n requestContext.set(\"identity\", identity);\n if (identity.authority === \"authenticated-host\") {\n requestContext.set(\"authenticatedResourceId\", identity.resourceId);\n requestContext.set(\"authorizedThreadId\", identity.threadId);\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, identity.resourceId);\n requestContext.set(MASTRA_THREAD_ID_KEY, identity.threadId);\n const documentTransition = deriveSurveyAssistantDocumentTransition({\n current: snapshot,\n previous: previousSettledVersion,\n });\n if (documentTransition) {\n requestContext.set(\"documentTransition\", documentTransition);\n }\n if (attachmentAccess && attachmentAccess.documents.length > 0) {\n requestContext.set(\"attachmentAccess\", attachmentAccess);\n }\n if (modelAttachments.length > 0) {\n requestContext.set(\"modelAttachments\", modelAttachments);\n }\n if (modelSelection) {\n requestContext.set(\"modelSelection\", modelSelection);\n }\n\n if (!snapshot) {\n return requestContext;\n }\n\n const engineContext = createSurveyAssistantEngineContext(snapshot, trustedCapabilities);\n turnDraft.initialize(engineContext);\n requestContext.set(\"documentSnapshot\", snapshot);\n requestContext.set(\"engineContext\", engineContext);\n\n return requestContext;\n};\n\n/**\n * Returns the materialized request-local survey state. The immutable\n * engineContext remains available as the turn baseline, while every tool uses\n * this accessor so successful same-turn mutations are immediately visible.\n */\nexport const getSurveyAssistantEngineContext = (\n requestContext: RequestContext<SurveyAssistantRequestContext> | undefined,\n): SurveyAssistantEngineContext | undefined =>\n requestContext?.get(\"turnDraft\")?.context ?? requestContext?.get(\"engineContext\");\n\nexport const requireSurveyAssistantTurnState = (\n requestContext: RequestContext<SurveyAssistantRequestContext> | undefined,\n) => {\n const turnId = requestContext?.get(\"turnId\");\n const turnDraft = requestContext?.get(\"turnDraft\");\n if (!turnId || !turnDraft || turnDraft.turnId !== turnId) {\n throw new Error(\"Survey assistant turn context is unavailable or inconsistent.\");\n }\n\n return { turnId, turnDraft };\n};\n"],"mappings":";;;;;AA+EA,MAAa,gCAAgC,UAAkD;AAC7F,KAAI,UAAU,KAAA,KAAa,UAAU,KACnC,QAAO;AAGT,QAAO,qCAAqC,MAAM,MAAM;;AAG1D,MAAa,8CACX,UACiC;AACjC,KAAI,UAAU,KAAA,KAAa,UAAU,KACnC,QAAO;AAGT,QAAO,4BAA4B,MAAM,MAAM;;AAGjD,MAAa,2CAA2C,EACtD,SACA,eAImD;AACnD,KAAI,CAAC,QAAS,QAAO,KAAA;AACrB,KAAI,CAAC,SAAU,QAAO,EAAE,QAAQ,eAAe;CAE/C,MAAM,uBAAuB,SAAS;CACtC,MAAM,sBAAsB,QAAQ,QAAQ;AAC5C,KAAI,SAAS,cAAc,QAAQ,QAAQ,UACzC,QAAO;EACL,QAAQ;EACR;EACA;EACD;CAGH,M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A,EAAW,OAAA,EAAS,OAAA,aAAoB,OAAA;EACxC,qBAAA;EACA,aAAA;EACA,aAAA,EAAe,KAAA;IACb,UAAA;IACA,QAAA,EAAU,qCAAA;IACV,MAAA;IACA,MAAA;EAAA;EAEF,eAAA,GAAkB,qBAAA;EAClB,YAAA,EACE,KAAA,EAAO,uCAAA,GAEL,6BAAA,sBAGA,OAAA,CAAQ,6BAAA;AAAA;AAAA,cAmCD,gCAAA;EAAoC,KAAA;EAAA,SAAA;EAAA,iBAAA;EAAA,SAAA;EAAA,qBAAA;EAAA,aAAA;EAAA,aAAA;EAAA,eAAA;EAAA;AAAA,GAU9C,uCAAA,MAWa,OAAA,EAAS,OAAA,KAAU,OAAA,CAAQ,QAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"thread-handlers-uddXwQjp.d.mts","names":[],"sources":["../src/server/request-guardrails.ts","../src/server/handler.ts","../src/server/thread-handlers.ts"],"mappings":";;;;;;;;cAEa,kCAAA;AAAA,cACA,6BAAA;AAAA,cACA,gCAAA;AAAA,cACA,qCAAA;AAAA,cACA,2CAAA;AAAA,cACA,oCAAA;AAAA,cACA,0CAAA;AAAA,cAEA,0CAAA,EAA0C,GAAA;AAAA,UAQtC,4BAAA;EACf,uBAAA,EAAyB,WAAA;EACzB,kBAAA;EACA,sBAAA;EACA,cAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,uBAAA;AAAA;AAAA,cAGW,uCAAA,EAAyC,4BAAA;AAAA,cAWzC,2BAAA,SAAoC,KAAA;EAAA,SACtC,MAAA;cAEG,OAAA,UAAiB,MAAA;AAAA;AAAA,cAoDlB,+BAAA,GACX,KAAA,WACA,MAAA,GAAQ,4BAAA,KACP,SAAA;AAAA,cAmFU,8BAAA,GACX,OAAA,EAAS,OAAA,EACT,eAAA,cACC,OAAA;;;KCzIE,eAAA,GAAkB,qBAAA;AAAA,UAEN,iCAAA;EACf,OAAA,EAAS,OAAA;EACT,mBAAA;EACA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@@
|
|
|
1
|
-
{"version":3,"file":"tools-wgLen05n.mjs","names":["isRecord","unwrapToolOutput","TOOL_ID","inputSchema","outputSchema","TOOL_ID","inputSchema","TOOL_ID","inputSchema","outputSchema","TOOL_ID","outlineModeSchema","inputSchema","outputSchema","summarizeForModel","TOOL_ID","DEFAULT_TEXT_LIMIT","inputSchema","outputSchema","summarizeForModel","TOOL_ID","inputSchema","outputSchema","summarizeForModel","TOOL_ID","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/tools/tool-model-output.ts","../src/server/tools/survey-authoring-reference-tool.ts","../src/server/tools/survey-change-tool.ts","../src/server/tools/survey-expression-tool.ts","../src/server/tools/survey-get-current-context-tool.ts","../src/server/tools/survey-get-item-details-tool.ts","../src/server/tools/survey-get-raw-survey-tool.ts","../src/server/tools/survey-search-items-tool.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\nconst 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 manifest.authoring?.configSummary\n ? `Configuration: ${manifest.authoring.configSummary}`\n : undefined,\n fixedSurfaces.length > 0\n ? `Fixed content surfaces: ${fixedSurfaces.map((surface) => surface.key).join(\", \")}.`\n : \"Fixed content surfaces: none.\",\n patternedSurfaces.length > 0\n ? `Dynamic content surfaces: ${patternedSurfaces.map((surface) => surface.key).join(\", \")}.`\n : undefined,\n kind === \"create-item\" && requiredSurfaces.length > 0\n ? `Required on creation: ${requiredSurfaces.map((surface) => surface.key).join(\", \")}.`\n : undefined,\n manifest.referenceTopics?.length\n ? `Load a dedicated reference only when needed: ${manifest.referenceTopics.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 field shape. Cross-field and snapshot-dependent rules are enforced when the\",\n \"proposal is validated. The tool may normalize limited schema-near shorthand, but prefer this\",\n \"canonical form.\",\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","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 getBuiltInItemTypeAuthoringReference,\n surveyAuthoringReferences,\n surveyAuthoringReferenceTopics,\n} from \"../authoring-references\";\nimport {\n resolveAssistantCapabilityReference,\n type SurveyAssistantEngineContext,\n} from \"../../engine\";\nimport {\n formatSurveyOperationContractReference,\n isSurveyOperationKind,\n SURVEY_OPERATION_CONTRACT_DETAIL_LEVELS,\n} from \"../operation-contract-reference\";\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\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\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: `No built-in survey_change operation named \"${inputData.operationKind}\" is available.`,\n };\n }\n\n if (inputData.itemType && !itemCapability) {\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: `No installed survey item capability named \"${inputData.itemType}\" is available.`,\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 const capabilityEntry = capabilityReference\n ? {\n title: capabilityReference.title ?? `${capability?.manifest.displayName} authoring`,\n content: capabilityReference.markdown,\n }\n : undefined;\n const entry = focusedBuiltInItemTypeReference ?? capabilityEntry ?? builtInEntry;\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: 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 };\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 { 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\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 'Create items with { kind: \"create-item\", target: { parentItemId, index? }, item: { id?, key, itemType, config }, translations? }. Put respondent content in top-level translations and item settings in item.config.',\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary text or content for a complete structured value. Item titles and option/field labels are translations, not item labels.\",\n \"Use remove-survey-locale with locale to remove an existing survey language; the final remaining locale cannot be removed.\",\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 \"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 placement that already exists in the live survey or validated turn draft.\",\n \"When deleting referenced images and assets, include every reference-removal operation and remove-image-asset last in the same operations array.\",\n 'Raw fallback is one { kind: \"survey-json-patch\", patches } operation containing all related survey-rooted edits; it must be the only operation in the call.',\n \"Keep each delta bounded; successful chunks accumulate automatically in the turn draft.\",\n].join(\" \");\n\nconst inputSchema = z\n .object({\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(1)\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 \"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 \"Draft unchanged. Fix this same rejected target in another call; the previously validated draft is retained. An unrelated valid edit does not repair this rejection.\",\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 }\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 ) {\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\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 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 operationsParse = z\n .array(surveyOperationSchema)\n .safeParse(normalizeSurveyChangeOperations(inputData.operations, defaultLocale));\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 );\n }\n\n return turnDraft.stage({\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 type { JsonPatchOperation } from \"@case-framework/survey-core\";\nimport {\n buildExpressionMutationPatches,\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\nexport const TOOL_ID = \"survey_expression\";\n\nconst contextActionSchema = z.object({\n action: z.literal(\"context\"),\n reason: z.string().max(500).optional(),\n itemIds: z.array(z.string().min(1).max(240)).max(12).optional(),\n includeRawLocations: z.boolean().optional(),\n});\n\nconst prepareActionSchema = z.object({\n action: z.literal(\"prepare\"),\n summary: z.string().min(1).max(500),\n mutations: z.array(expressionMutationSchema).min(1).max(40),\n});\n\nconst inputSchema = z\n .object({\n action: z\n .enum([\"context\", \"prepare\"])\n .describe(\"Use context to inspect expression refs; use prepare to create expression edits.\"),\n reason: z.string().max(500).optional(),\n itemIds: z\n .array(z.string().min(1).max(240))\n .max(12)\n .optional()\n .describe(\"For context: optional item ids/keys to focus existing expression locations.\"),\n includeRawLocations: z\n .boolean()\n .optional()\n .describe(\"For context: include existing expression locations by raw item.\"),\n summary: z.string().min(1).max(500).optional().describe(\"For prepare: user-facing summary.\"),\n mutations: z\n .array(z.record(z.string(), z.unknown()))\n .min(1)\n .max(40)\n .optional()\n .describe(\n 'For prepare: expression mutation objects using kebab-case kind names. Item visibility shape: { kind: \"set-item-display-condition\", itemId: \"<existing-item-id>\", expression: { type: \"function\", functionName: \"eq\", arguments: [...] } }. expression is always CASE expression JSON, never a string or expression-language snippet. Other supported kinds set/clear component display/disabled conditions, validation expressions, prefills, and template values.',\n ),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.action !== \"prepare\") {\n return;\n }\n if (!value.summary) {\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: \"At least one mutation 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 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>;\ntype ExpressionMutation = PrepareExpressionInput[\"mutations\"][number];\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 expressionMutationTarget = (mutation: ExpressionMutation): string => {\n switch (mutation.kind) {\n case \"set-item-display-condition\":\n case \"clear-item-display-condition\":\n return `expression:item:${mutation.itemId}:display`;\n case \"set-component-display-condition\":\n case \"clear-component-display-condition\":\n return `expression:item:${mutation.itemId}:component:${mutation.componentId}:display`;\n case \"set-component-disabled-condition\":\n case \"clear-component-disabled-condition\":\n return `expression:item:${mutation.itemId}:component:${mutation.componentId}:disabled`;\n case \"set-validation-expression\":\n case \"clear-validation-expression\":\n return `expression:item:${mutation.itemId}:validation:${mutation.validationKey}`;\n case \"set-prefill\":\n return `expression:item:${mutation.itemId}:prefill:${mutation.prefill.id}`;\n case \"clear-prefill\":\n return `expression:item:${mutation.itemId}:prefill:${mutation.prefillId}`;\n case \"set-template-value\":\n case \"clear-template-value\":\n return `expression:template:${mutation.templateKey}`;\n }\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 \"Draft unchanged. Fix this same expression target; the previously validated draft is retained. An unrelated valid edit does not repair this rejection.\",\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 return lines.join(\"\\n\");\n};\n\nconst buildContextOutput = (\n snapshot: SurveyAssistantSnapshot,\n input: SurveyExpressionInput,\n): ContextOutput => {\n const rawItems = getRawSurveyItems(snapshot);\n const responseSlotTypes = buildResponseSlotTypes(snapshot);\n const responseSlots = Object.entries(responseSlotTypes).map(([ref, valueType]) => ({\n ref,\n ...(valueType ? { valueType } : {}),\n }));\n const itemFilter =\n input.action === \"context\" && input.itemIds?.length ? new Set(input.itemIds) : undefined;\n const includeRawLocations = input.action === \"context\" && input.includeRawLocations === true;\n const expressionLocations = 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 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 \"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 `Response slots (${responseSlots.length}): ${responseSlots\n .slice(0, 80)\n .map((slot) => `${slot.ref}${slot.valueType ? `:${slot.valueType}` : \"\"}`)\n .join(\", \")}`,\n responseSlots.length > 80\n ? \"Response slot list truncated in summary; inspect context result for more.\"\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 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 const contextParse = contextActionSchema.safeParse(inputData);\n return buildContextOutput(snapshot, contextParse.success ? contextParse.data : input);\n }\n\n const { turnDraft, turnId } = requireSurveyAssistantTurnState(requestContext);\n\n const reject = (event: SurveyChangeSet, addressedTargets: string[] = []) =>\n turnDraft.reject(event, addressedTargets);\n\n const prepareParse = prepareActionSchema.safeParse(inputData);\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 );\n }\n const prepareInput = prepareParse.data;\n const addressedTargets = [...new Set(prepareInput.mutations.map(expressionMutationTarget))];\n\n const issues: SurveyValidationIssue[] = [];\n const patches: JsonPatchOperation[] = [];\n const responseSlotTypes = buildResponseSlotTypes(snapshot);\n\n prepareInput.mutations.forEach((mutation, operationIndex) => {\n buildExpressionMutationPatches({\n mutation,\n operationIndex,\n issues,\n patches,\n responseSlotTypes,\n snapshot,\n });\n });\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 addressedTargets,\n );\n }\n\n if (patches.length === 0) {\n return reject(\n rejectedEvent({\n summary: prepareInput.summary,\n turnId,\n issues: [\n createIssue({\n code: \"no-expression-patches\",\n message:\n \"No expression patches were produced. Check whether the requested locations already match the target state.\",\n }),\n ],\n warnings,\n }),\n addressedTargets,\n );\n }\n\n const operation: SurveyOperation = {\n kind: \"survey-json-patch\",\n patches,\n };\n\n const event = turnDraft.stage({\n addressedTargets,\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 { createTool } from \"@mastra/core/tools\";\nimport 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 { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_get_current_context\";\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(160)\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.infer<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\nconst summarizeForModel = (output: SurveyGetCurrentContextOutput) => {\n if (!output.ok) {\n return output.reason ?? \"Current editor context is unavailable.\";\n }\n\n const lines = [`Snapshot revision ${output.revision}, content hash ${output.contentHash}.`];\n\n if (output.summary) {\n const selected = output.summary.selectedItemId ?? \"none\";\n const surveyKey = output.summary.surveyKey ?? \"not set\";\n lines.push(\n `Summary: view=${output.summary.view}; selectedItemId=${selected}; locale=${output.summary.selectedLocale}; surveyKey=${surveyKey}; itemCount=${output.summary.itemCount} (excluding the structural root group).`,\n );\n if (output.summary.rootItem) {\n lines.push(\n `Root group for top-level create-item target.parentItemId: ${output.summary.rootItem.fullKey} (id=${output.summary.rootItem.itemId}, key=${output.summary.rootItem.key}).`,\n );\n }\n lines.push(\n `Outline access: ${output.summary.outlineItemCount} item(s), including the structural root group, are pageable.`,\n );\n const creatableDetails = output.summary.itemTypeDetails\n .filter((entry) => entry.create === \"deterministic\")\n .map((entry) => {\n const primarySurface = entry.contentSurfaces.find((surface) => surface.role === \"primary\");\n const fixedSurfaces = entry.contentSurfaces\n .filter((surface) => !surface.pattern)\n .map((surface) => surface.key);\n const patterns = entry.contentSurfaces\n .filter((surface) => surface.pattern)\n .map((surface) => surface.key);\n const contentKeys = [\n primarySurface ? `primary=${primarySurface.key}` : undefined,\n fixedSurfaces.length ? `visible=${fixedSurfaces.join(\"|\")}` : undefined,\n patterns.length ? `dynamic=${patterns.join(\"|\")}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return contentKeys ? `${entry.itemType} (${contentKeys})` : entry.itemType;\n });\n if (creatableDetails.length > 0) {\n lines.push(`Creatable item types: ${creatableDetails.join(\", \")}.`);\n }\n }\n\n if (output.selectedItem) {\n if (output.selectedItem.available && output.selectedItem.item) {\n lines.push(\n `Selected item: ${output.selectedItem.item.fullKey} (${output.selectedItem.item.itemType})${output.selectedItem.item.itemLabel ? ` - ${output.selectedItem.item.itemLabel}` : \"\"}.`,\n );\n if (output.selectedItem.translationSnippets?.length) {\n lines.push(\n `Translation snippets: ${output.selectedItem.translationSnippets\n .map((entry) => `${entry.locale}.${entry.contentKey}: ${entry.text}`)\n .join(\"; \")}`,\n );\n }\n } else {\n lines.push(`Selected item unavailable: ${output.selectedItem.reason ?? \"unknown reason\"}.`);\n }\n }\n\n if (output.outline) {\n lines.push(\n `Outline (${output.outline.strategy}${output.outline.mode ? `, mode=${output.outline.mode}` : \"\"}): ${output.outline.returned}/${output.outline.totalAvailable} rows returned.`,\n );\n for (const item of output.outline.items) {\n lines.push(\n `- ${item.fullKey} (${item.itemType})${item.itemLabel ? ` - ${item.itemLabel}` : \"\"}`,\n );\n }\n lines.push(`Outline order: ${output.outline.ordering}`);\n if (output.outline.nextCursor) {\n lines.push(`More outline rows are available with cursor ${output.outline.nextCursor}.`);\n }\n }\n\n if (output.responseSlots) {\n lines.push(\n output.responseSlots.available\n ? `Response slots: ${output.responseSlots.slots.join(\", \") || \"none\"}`\n : `Response slots unavailable: ${output.responseSlots.note ?? \"not indexed\"}.`,\n );\n if (output.responseSlots.available) {\n lines.push(`Response-slot order: ${output.responseSlots.ordering}`);\n }\n }\n\n if (output.uiContext) {\n lines.push(\n `UI context: activeSurface=${output.uiContext.activeSurface ?? \"not provided\"}; openPanels=${output.uiContext.openPanels.join(\", \") || \"none\"}; highlights=${output.uiContext.highlights.map((entry) => entry.label ?? entry.itemId ?? entry.componentId ?? entry.kind).join(\", \") || \"none\"}.`,\n );\n }\n\n if (output.history) {\n lines.push(\n `Recent editor history (${output.history.currentIndex + 1}/${output.history.totalEntries}): ${output.history.recent.map((entry) => `${entry.index}:${entry.label}${entry.isCurrent ? \" [current]\" : \"\"}`).join(\"; \") || \"none\"}.`,\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const surveyGetCurrentContextTool = createTool({\n id: TOOL_ID,\n description:\n \"Read the current Survey Editor context from the latest request snapshot. Use for questions about this screen, selected item, survey outline, item keys, labels, locales, or response slots. The outline scope can page the complete survey key index, so use cursor/limit instead of guessing when a focused outline is truncated.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Get current survey context\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveyGetCurrentContextOutput> => {\n const input: SurveyGetCurrentContextInput = {\n ...inputData,\n scopes: inputData.scopes ?? [\"summary\"],\n limit: inputData.limit ?? DEFAULT_LIMIT,\n outlineMode: inputData.outlineMode ?? \"full\",\n };\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | 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\":\n \"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 output;\n },\n toModelOutput: (value) =>\n toTextModelOutput<SurveyGetCurrentContextOutput>(value, summarizeForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport 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 type ItemConfigDetails,\n inspectAssistantItem,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { z } from \"zod\";\nimport { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_get_item_details\";\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 SurveyGetItemDetailsInput = z.infer<typeof inputSchema>;\ntype SurveyGetItemDetailsOutput = z.infer<typeof outputSchema>;\n\nconst summarizeConfigDetails = (configDetails: ItemConfigDetails) => {\n const lines = [`Config details (${configDetails.kind}): ${configDetails.summary.join(\"; \")}`];\n\n if (configDetails.mainResponseSlotId) {\n lines.push(`Main response slot: ${configDetails.mainResponseSlotId}`);\n }\n\n for (const option of configDetails.choiceOptions ?? []) {\n lines.push(\n `- ${option.position}. option ${option.key ?? option.id} (id=${option.id}, labelContentKey=${option.labelContentKey})`,\n );\n if (option.embeddedFormItemId || option.embeddedFormFieldGroupCount) {\n lines.push(\n ` embedded form: itemId=${option.embeddedFormItemId ?? \"inline\"}, fieldGroups=${\n option.embeddedFormFieldGroupCount ?? 0\n }`,\n );\n if (option.embeddedFormTranslationPrefix || option.embeddedFormResponseSlotPrefix) {\n lines.push(\n ` embedded form keys: translationPrefix=${option.embeddedFormTranslationPrefix ?? \"n/a\"}, responseSlotPrefix=${option.embeddedFormResponseSlotPrefix ?? \"n/a\"}`,\n );\n }\n }\n }\n\n for (const group of configDetails.formFieldGroups ?? []) {\n lines.push(\n `- ${group.position}. field group ${group.id}: ${group.fieldCount} field(s), titleContentKey=${group.titleContentKey}, layout=${group.layout.base}/${group.layout.xs}/${group.layout.sm}/${group.layout.md}/${group.layout.xl}`,\n );\n if (group.hasDisplayCondition !== undefined) {\n lines.push(` hasDisplayCondition=${group.hasDisplayCondition ? \"true\" : \"false\"}`);\n }\n for (const field of group.fields) {\n lines.push(\n ` - ${field.position}. field ${field.key} (${field.type}, id=${field.id}, responseSlot=${field.responseSlotId}, labelContentKey=${field.labelContentKey})`,\n );\n lines.push(\n ` extra content keys: description=${field.descriptionContentKey}, error=${field.errorContentKey}${field.placeholderContentKey ? `, placeholder=${field.placeholderContentKey}` : \"\"}${field.unitContentKey ? `, unit=${field.unitContentKey}` : \"\"}${field.checkedLabelContentKey ? `, checkedLabel=${field.checkedLabelContentKey}` : \"\"}${field.uncheckedLabelContentKey ? `, uncheckedLabel=${field.uncheckedLabelContentKey}` : \"\"}`,\n );\n if (field.validationTypes?.length) {\n lines.push(` validations: ${field.validationTypes.join(\", \")}`);\n }\n if (field.validationMessageContentKeys?.length) {\n lines.push(` validation message keys: ${field.validationMessageContentKeys.join(\", \")}`);\n }\n if (field.selectOptions?.length) {\n lines.push(\n ` select options: ${field.selectOptions\n .map(\n (option) =>\n `${option.position}. ${option.value ?? option.id} (${option.labelContentKey})`,\n )\n .join(\", \")}`,\n );\n }\n }\n }\n\n return lines;\n};\n\nconst summarizeForModel = (output: SurveyGetItemDetailsOutput) => {\n if (!output.ok) {\n return output.reason ?? \"Item details are unavailable.\";\n }\n\n const lines: string[] = [];\n\n if (output.item) {\n lines.push(\n `Item: ${output.item.fullKey} (${output.item.itemType})${output.item.itemLabel ? ` - ${output.item.itemLabel}` : \"\"}.`,\n );\n }\n\n if (output.translations?.length) {\n lines.push(\n `Translations: ${output.translations\n .map((entry) => `${entry.locale}.${entry.contentKey}: ${entry.text}`)\n .join(\"; \")}`,\n );\n } else {\n lines.push(\"Translations: none found for this item.\");\n }\n\n if (output.surveyChildren) {\n lines.push(`Survey-tree children (${output.surveyChildren.length}):`);\n for (const child of output.surveyChildren) {\n lines.push(\n `- ${child.fullKey} (${child.itemType})${child.itemLabel ? ` - ${child.itemLabel}` : \"\"}`,\n );\n }\n if (output.surveyChildrenTruncated) {\n lines.push(\"More children exist than were returned; narrow down or raise childrenLimit.\");\n }\n }\n\n if (output.configDetails) {\n if (output.configDetails.listOrdering) {\n for (const [list, meaning] of Object.entries(output.configDetails.listOrdering)) {\n lines.push(`List order (${list}): ${meaning}`);\n }\n }\n lines.push(...summarizeConfigDetails(output.configDetails));\n }\n\n if (output.capabilityDetails) {\n lines.push(`Item capability: ${output.capabilityDetails.summary}`);\n if (output.capabilityDetails.details !== undefined) {\n lines.push(`Capability details: ${JSON.stringify(output.capabilityDetails.details)}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const surveyGetItemDetailsTool = createTool({\n id: TOOL_ID,\n description:\n \"Fetch full details for a SPECIFIC survey item, whether or not it is currently selected. Returns item translations plus item-internal config details such as choice options and form fields. Use survey_search_items first when you only know visible text.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Get survey item details\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveyGetItemDetailsOutput> => {\n const input: SurveyGetItemDetailsInput = {\n ...inputData,\n textLimit: inputData.textLimit ?? DEFAULT_TEXT_LIMIT,\n includeSurveyChildren: inputData.includeSurveyChildren ?? inputData.includeChildren ?? false,\n includeItemConfig: inputData.includeItemConfig ?? true,\n childrenLimit: inputData.childrenLimit ?? DEFAULT_CHILDREN_LIMIT,\n };\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | 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 output;\n },\n toModelOutput: (value) => toTextModelOutput<SurveyGetItemDetailsOutput>(value, summarizeForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport 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 { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_get_raw_survey\";\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 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 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 SurveyGetRawSurveyInput = z.infer<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 },\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 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\nconst summarizeForModel = (output: SurveyGetRawSurveyOutput) => {\n if (!output.ok) {\n return output.reason ?? \"Raw survey context is unavailable.\";\n }\n\n const lines: string[] = [];\n\n if (output.overview) {\n lines.push(\n `Raw survey overview: ${output.overview.surveyItemCount} item(s), top-level keys ${output.overview.topLevelKeys.join(\", \")}.`,\n );\n lines.push(`Locales: ${output.overview.locales.join(\", \") || \"none\"}.`);\n lines.push(\"Survey item JSON paths:\");\n for (const item of output.overview.itemPaths.slice(0, 50)) {\n lines.push(\n `- ${item.path}: ${item.key} (${item.itemType}, id=${item.id})${\n item.parentId ? ` parent=${item.parentId}` : \"\"\n }`,\n );\n }\n if (output.overview.itemPaths.length > 50) {\n lines.push(\"More item paths exist; request a specific path for exact raw JSON.\");\n }\n }\n\n if (output.listOrdering) {\n for (const [list, meaning] of Object.entries(output.listOrdering)) {\n lines.push(`List order (${list}): ${meaning}`);\n }\n }\n\n for (const item of output.items ?? []) {\n if (!item.found) {\n lines.push(`${item.identifier}: not found (${item.error ?? \"unknown error\"})`);\n continue;\n }\n\n lines.push(`${item.identifier}: itemId=${item.itemId}; raw path ${item.itemPath}.`);\n if (item.translationPaths?.length) {\n lines.push(`Translation paths: ${item.translationPaths.join(\", \")}.`);\n }\n if (item.rawItemTruncated) {\n lines.push(`Raw item truncated preview:\\n${item.rawItemPreview ?? \"\"}`);\n } else {\n lines.push(`Raw item: ${JSON.stringify(item.rawItem)}`);\n }\n if (item.translationsTruncated) {\n lines.push(`Translations truncated preview:\\n${item.translationsPreview ?? \"\"}`);\n } else {\n lines.push(`Translations by locale: ${JSON.stringify(item.translationsByLocale ?? {})}`);\n }\n }\n\n for (const entry of output.values ?? []) {\n if (!entry.found) {\n lines.push(`${entry.path}: not found (${entry.error ?? \"unknown error\"})`);\n continue;\n }\n\n if (entry.truncated) {\n lines.push(`${entry.path}: truncated JSON preview:\\n${entry.preview ?? \"\"}`);\n } else {\n lines.push(`${entry.path}: ${JSON.stringify(entry.value)}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const surveyGetRawSurveyTool = createTool({\n id: TOOL_ID,\n description:\n \"Inspect exact raw survey JSON by item id/key/fullKey or JSON Pointer path. Use this before survey-json-patch edits to inspect item config, survey-level metadata, maxItemsPerPage, templateValues, translations/locales, or group ordering arrays.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Get raw survey JSON\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveyGetRawSurveyOutput> => {\n const input: SurveyGetRawSurveyInput = {\n ...inputData,\n valueCharacterLimit: inputData.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT,\n };\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | 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 {\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 valueCharacterLimit: input.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT,\n })\n : undefined,\n };\n },\n toModelOutput: (value) => toTextModelOutput<SurveyGetRawSurveyOutput>(value, summarizeForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport 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 { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_search_items\";\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 SurveySearchItemsInput = z.infer<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\nconst summarizeForModel = (output: SurveySearchItemsOutput) => {\n if (!output.ok) {\n return output.reason ?? \"Survey item search is unavailable.\";\n }\n\n const lines = [\n `Search \"${output.query ?? \"\"}\": ${output.returned ?? 0}/${output.totalAvailable ?? 0} matching item(s) returned.`,\n ];\n\n for (const result of output.results ?? []) {\n lines.push(\n `- ${result.item.fullKey} (${result.item.itemType}, itemId=${result.item.itemId}, score=${result.score})`,\n );\n for (const match of result.matches) {\n const source =\n match.source === \"translation\"\n ? `${match.locale}.${match.contentKey}`\n : (match.field ?? match.source);\n lines.push(` match ${match.source}:${source}: ${match.text}`);\n }\n }\n\n if (output.nextCursor) {\n lines.push(`More search results are available with cursor ${output.nextCursor}.`);\n }\n\n if (output.ordering) {\n lines.push(`Search-result order: ${output.ordering}`);\n }\n\n lines.push('Use survey_inspect with action \"item-details\" and itemRef to inspect a result.');\n\n return lines.join(\"\\n\");\n};\n\nexport const surveySearchItemsTool = createTool({\n id: TOOL_ID,\n description:\n \"Search all survey items by visible translated text, item keys, labels, and config identifiers. Use this when the user refers to an unselected item by title, label, option text, field label, or another phrase rather than an item id.\",\n inputSchema,\n outputSchema,\n mcp: {\n annotations: {\n title: \"Search survey items\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n execute: async (inputData, context): Promise<SurveySearchItemsOutput> => {\n const input: SurveySearchItemsInput = {\n ...inputData,\n limit: inputData.limit ?? DEFAULT_LIMIT,\n };\n const snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | 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 {\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 },\n toModelOutput: (value) => toTextModelOutput<SurveySearchItemsOutput>(value, summarizeForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport type { SurveyAssistantEngineContext as SurveyAssistantSnapshot } from \"../../engine\";\nimport {\n getAssetUsagesFromContent,\n type Content,\n type RawSurvey,\n type RawSurveyAsset,\n} from \"@case-framework/survey-core\";\nimport { z } from \"zod\";\nimport { surveyGetCurrentContextTool } from \"./survey-get-current-context-tool\";\nimport { surveyGetItemDetailsTool } from \"./survey-get-item-details-tool\";\nimport { surveyGetRawSurveyTool } from \"./survey-get-raw-survey-tool\";\nimport { surveySearchItemsTool } from \"./survey-search-items-tool\";\nimport { toTextModelOutput } from \"./tool-model-output\";\nimport {\n getSurveyAssistantEngineContext,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\n\nexport const TOOL_ID = \"survey_inspect\";\n\nconst inspectActionSchema = z.enum([\n \"current-context\",\n \"search-items\",\n \"item-details\",\n \"assets\",\n \"raw-json\",\n]);\nconst outlineModeSchema = z.enum([\"full\", \"focused\", \"children\"]);\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 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 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(z.array(z.string().min(1).max(500)).min(1).max(20)).describe(\n \"For raw-json: exact JSON Pointer paths to inspect. Empty means omitted.\",\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\ntype ExecutableTool = {\n execute?: unknown;\n};\n\nconst runTool = async (tool: ExecutableTool, input: Record<string, unknown>, context: unknown) => {\n const execute = tool.execute as\n | ((inputData: unknown, executionContext: unknown) => Promise<unknown>)\n | undefined;\n\n if (!execute) {\n throw new Error(\"Survey inspection backend is not executable.\");\n }\n\n return execute(input, context);\n};\n\nconst unwrapToolOutput = (value: unknown) => {\n if (\n value &&\n typeof value === \"object\" &&\n \"output\" in value &&\n (value as { output?: unknown }).output !== undefined\n ) {\n return (value as { output: unknown }).output;\n }\n\n return value;\n};\n\nconst stringifyForModel = (value: unknown) => {\n if (typeof value === \"string\") {\n return value;\n }\n\n return JSON.stringify(value, null, 2);\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, image assets with explicit asset IDs and usages, or focused raw JSON. 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 snapshot = getSurveyAssistantEngineContext(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n ) as SurveyAssistantSnapshot | 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 result = unwrapToolOutput(\n await runTool(\n surveyGetCurrentContextTool,\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 context,\n ),\n );\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\n const result = unwrapToolOutput(\n await runTool(\n surveySearchItemsTool,\n {\n query: input.query,\n limit: input.limit,\n cursor: input.cursor,\n },\n context,\n ),\n );\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 result = unwrapToolOutput(\n await runTool(\n surveyGetItemDetailsTool,\n {\n itemId,\n includeSurveyChildren: input.includeChildren ?? false,\n includeItemConfig: input.includeItemConfig ?? true,\n childrenLimit: input.limit,\n },\n context,\n ),\n );\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\n 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 = resolveItemRef(input, snapshot);\n const itemIdentifiers = itemId ? [itemId] : undefined;\n const result = unwrapToolOutput(\n await runTool(\n surveyGetRawSurveyTool,\n {\n paths: input.paths,\n itemIdentifiers,\n },\n context,\n ),\n );\n\n return {\n ok: true,\n action: input.action,\n modelSummary: stringifyForModel(result),\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 .describe(\"IDs of only the stored attachments needed for the current request.\"),\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 }),\n ),\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. After this succeeds, read the original files directly and continue the task.\",\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 requestedIds = [...new Set(inputData.documentIds)];\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 id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n })),\n };\n },\n toModelOutput: (value) =>\n toTextModelOutput(\n value,\n () =>\n \"The selected original attachments are included in this model input. Read them directly now and continue the user's task. Do not claim that their content is unavailable or ask the user to paste extracted text.\",\n ),\n});\n","import { createTool } from \"@mastra/core/tools\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport { auditSurvey, type SurveyAssistantEngineContext } 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 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\nexport const surveyAuditTool = createTool({\n id: TOOL_ID,\n description:\n \"Audit the current survey for deterministic structural, content, localization, response, and asset issues, and return a research-informed questionnaire-quality review rubric for qualitative critique. 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, (output) => JSON.stringify(output, null, 2)),\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\nexport const TOOL_ID = \"survey_asset\";\n\nconst inputSchema = z\n .object({\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 it in a richText image block inside the create-item translation content.`,\n );\n lines.push(\n `New info-item translation example: { \"locale\": \"<selected-locale>\", \"contentKey\": \"content\", \"content\": { \"type\": \"richText\", \"version\": 1, \"doc\": { \"type\": \"doc\", \"blocks\": [{ \"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 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(event, [`asset:${operation.assetId}`]);\n }\n }\n\n return turnDraft.stage({\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\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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