@case-framework/survey-assistant 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +71 -11
  2. package/dist/{authoring-references-X6uRaWuf.mjs → authoring-references-DYuOAdVx.mjs} +26 -2
  3. package/dist/authoring-references-DYuOAdVx.mjs.map +1 -0
  4. package/dist/{capabilities-B6tvE7fK.mjs → capabilities-DZ0a_o2y.mjs} +2 -2
  5. package/dist/{capabilities-B6tvE7fK.mjs.map → capabilities-DZ0a_o2y.mjs.map} +1 -1
  6. package/dist/{capabilities-DvSKtjAw.d.mts → capabilities-DlC1l6qy.d.mts} +4 -1
  7. package/dist/capabilities-DlC1l6qy.d.mts.map +1 -0
  8. package/dist/capabilities-default.d.mts +1 -1
  9. package/dist/capabilities-default.d.mts.map +1 -1
  10. package/dist/capabilities-default.mjs +6 -3
  11. package/dist/capabilities-default.mjs.map +1 -1
  12. package/dist/{constants-Jw0k8ojS.d.mts → constants-56jf_4ls.d.mts} +36 -9
  13. package/dist/constants-56jf_4ls.d.mts.map +1 -0
  14. package/dist/{controller-proxy-BRDusFiO.d.mts → controller-proxy-2VH0b_5E.d.mts} +29 -4
  15. package/dist/controller-proxy-2VH0b_5E.d.mts.map +1 -0
  16. package/dist/{controller-proxy-Duxo2IFE.mjs → controller-proxy-ClsY4lFI.mjs} +74 -5
  17. package/dist/controller-proxy-ClsY4lFI.mjs.map +1 -0
  18. package/dist/{digest-BsoVq49o.d.mts → digest-BvXpeWcR.d.mts} +2 -2
  19. package/dist/{digest-BsoVq49o.d.mts.map → digest-BvXpeWcR.d.mts.map} +1 -1
  20. package/dist/digest.d.mts +1 -1
  21. package/dist/{engine-sPvuixWg.mjs → engine-DQrCO_ur.mjs} +392 -50
  22. package/dist/engine-DQrCO_ur.mjs.map +1 -0
  23. package/dist/engine.d.mts +2 -2
  24. package/dist/engine.mjs +2 -2
  25. package/dist/{index-MpEMQzTm.d.mts → index-B_x2IYi7.d.mts} +5 -1
  26. package/dist/index-B_x2IYi7.d.mts.map +1 -0
  27. package/dist/{index-BWNHkpkh.d.mts → index-C_x686M7.d.mts} +27 -5
  28. package/dist/index-C_x686M7.d.mts.map +1 -0
  29. package/dist/{index-TFtvBiSQ.d.mts → index-DVxVyhAu.d.mts} +31 -9
  30. package/dist/index-DVxVyhAu.d.mts.map +1 -0
  31. package/dist/{index-CUqbBjkc.d.mts → index-DZ6KBwVR.d.mts} +16 -3
  32. package/dist/index-DZ6KBwVR.d.mts.map +1 -0
  33. package/dist/{memory-thread-repository-CJkkVE2-.mjs → memory-thread-repository-Cm1BJyRw.mjs} +110 -41
  34. package/dist/memory-thread-repository-Cm1BJyRw.mjs.map +1 -0
  35. package/dist/{protocol-DV0ka9WT.mjs → protocol-7EEgcYja.mjs} +70 -97
  36. package/dist/protocol-7EEgcYja.mjs.map +1 -0
  37. package/dist/protocol.d.mts +3 -3
  38. package/dist/protocol.mjs +2 -2
  39. package/dist/{react-VuYe-cPh.mjs → react-B_5smfiK.mjs} +145 -38
  40. package/dist/react-B_5smfiK.mjs.map +1 -0
  41. package/dist/react-integration.d.mts +2 -2
  42. package/dist/react-integration.mjs +2 -2
  43. package/dist/react.d.mts +3 -3
  44. package/dist/react.mjs +3 -3
  45. package/dist/references/assistant-operations.md +6 -0
  46. package/dist/references/core-rules.md +6 -0
  47. package/dist/references/embedded-forms.md +21 -14
  48. package/dist/references/expressions.md +3 -0
  49. package/dist/references/item-types.md +37 -10
  50. package/dist/references/source-material-surveys.md +9 -1
  51. package/dist/references/survey-data-model.md +13 -0
  52. package/dist/request-context-BDBw4-Gw.mjs +79 -0
  53. package/dist/request-context-BDBw4-Gw.mjs.map +1 -0
  54. package/dist/request-guardrails-h4t6u8mP.mjs +129 -0
  55. package/dist/request-guardrails-h4t6u8mP.mjs.map +1 -0
  56. package/dist/server-agent.d.mts +6 -2
  57. package/dist/server-agent.d.mts.map +1 -1
  58. package/dist/server-agent.mjs +39 -24
  59. package/dist/server-agent.mjs.map +1 -1
  60. package/dist/server-runtime.d.mts +21 -5
  61. package/dist/server-runtime.d.mts.map +1 -1
  62. package/dist/server-runtime.mjs +98 -32
  63. package/dist/server-runtime.mjs.map +1 -1
  64. package/dist/server-tasks.d.mts +2 -78
  65. package/dist/server-tasks.mjs +103 -46
  66. package/dist/server-tasks.mjs.map +1 -1
  67. package/dist/server-tools.d.mts +1 -1
  68. package/dist/server-tools.mjs +1 -1
  69. package/dist/server.d.mts +89 -21
  70. package/dist/server.d.mts.map +1 -1
  71. package/dist/server.mjs +136 -5
  72. package/dist/server.mjs.map +1 -0
  73. package/dist/storage-postgres.d.mts +12 -2
  74. package/dist/storage-postgres.d.mts.map +1 -1
  75. package/dist/storage-postgres.mjs +11 -6
  76. package/dist/storage-postgres.mjs.map +1 -1
  77. package/dist/tasks-COQnhSeT.d.mts +140 -0
  78. package/dist/tasks-COQnhSeT.d.mts.map +1 -0
  79. package/dist/{thread-documents-DamIq9Od.d.mts → thread-documents-BlxNjc7S.d.mts} +21 -5
  80. package/dist/thread-documents-BlxNjc7S.d.mts.map +1 -0
  81. package/dist/{thread-handlers-DpynUc64.d.mts → thread-handlers-l79JBl5m.d.mts} +38 -5
  82. package/dist/thread-handlers-l79JBl5m.d.mts.map +1 -0
  83. package/dist/{tools-Hz2p7vyv.mjs → tools-DDXaJ8Za.mjs} +257 -38
  84. package/dist/tools-DDXaJ8Za.mjs.map +1 -0
  85. package/dist/ui.d.mts +5 -3
  86. package/dist/ui.d.mts.map +1 -1
  87. package/dist/ui.mjs +91 -12
  88. package/dist/ui.mjs.map +1 -1
  89. package/docs/integration.md +234 -0
  90. package/package.json +9 -7
  91. package/dist/authoring-references-Cy8J-DWt.d.mts +0 -48
  92. package/dist/authoring-references-Cy8J-DWt.d.mts.map +0 -1
  93. package/dist/authoring-references-X6uRaWuf.mjs.map +0 -1
  94. package/dist/capabilities-DvSKtjAw.d.mts.map +0 -1
  95. package/dist/constants-Jw0k8ojS.d.mts.map +0 -1
  96. package/dist/controller-proxy-BRDusFiO.d.mts.map +0 -1
  97. package/dist/controller-proxy-Duxo2IFE.mjs.map +0 -1
  98. package/dist/engine-sPvuixWg.mjs.map +0 -1
  99. package/dist/index-BWNHkpkh.d.mts.map +0 -1
  100. package/dist/index-CUqbBjkc.d.mts.map +0 -1
  101. package/dist/index-MpEMQzTm.d.mts.map +0 -1
  102. package/dist/index-TFtvBiSQ.d.mts.map +0 -1
  103. package/dist/memory-thread-repository-CJkkVE2-.mjs.map +0 -1
  104. package/dist/protocol-DV0ka9WT.mjs.map +0 -1
  105. package/dist/react-VuYe-cPh.mjs.map +0 -1
  106. package/dist/request-context-jcmXT_Q2.mjs +0 -44
  107. package/dist/request-context-jcmXT_Q2.mjs.map +0 -1
  108. package/dist/request-guardrails-C59IWnH8.mjs +0 -73
  109. package/dist/request-guardrails-C59IWnH8.mjs.map +0 -1
  110. package/dist/server-tasks.d.mts.map +0 -1
  111. package/dist/thread-documents-DamIq9Od.d.mts.map +0 -1
  112. package/dist/thread-handlers-DpynUc64.d.mts.map +0 -1
  113. package/dist/tools-Hz2p7vyv.mjs.map +0 -1
@@ -1,73 +0,0 @@
1
- //#region src/server/request-guardrails.ts
2
- const SURVEY_ASSISTANT_MAX_REQUEST_BYTES = 20 * 1024 * 1024;
3
- const SURVEY_ASSISTANT_MAX_MESSAGES = 32;
4
- const SURVEY_ASSISTANT_MAX_ATTACHMENTS = 4;
5
- const SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
6
- const SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES = 12 * 1024 * 1024;
7
- const SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS = 64e3;
8
- const SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES = new Set([
9
- "application/pdf",
10
- "image/gif",
11
- "image/jpeg",
12
- "image/png",
13
- "image/webp"
14
- ]);
15
- var SurveyAssistantRequestError = class extends Error {
16
- status;
17
- constructor(message, status = 400) {
18
- super(message);
19
- this.name = "SurveyAssistantRequestError";
20
- this.status = status;
21
- }
22
- };
23
- const getDataUrlBytes = (url, expectedMediaType) => {
24
- const match = /^data:([^;,]+);base64,([A-Za-z0-9+/]*={0,2})$/.exec(url);
25
- if (!match) throw new SurveyAssistantRequestError("Attachments must be base64 data URLs.");
26
- if (match[1]?.toLowerCase() !== expectedMediaType.toLowerCase()) throw new SurveyAssistantRequestError("Attachment media type does not match its data URL.");
27
- const payload = match[2] ?? "";
28
- const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
29
- return Math.max(0, Math.floor(payload.length * 3 / 4) - padding);
30
- };
31
- const validateSurveyAssistantMessages = (value) => {
32
- if (!Array.isArray(value) || value.length === 0) throw new SurveyAssistantRequestError("A survey assistant message is required.");
33
- if (value.length > 32) throw new SurveyAssistantRequestError("The survey assistant request contains too many messages.");
34
- if (value.length !== 1 || value[0]?.role !== "user") throw new SurveyAssistantRequestError("The survey assistant request must contain only the current user message.");
35
- let attachmentCount = 0;
36
- let totalAttachmentBytes = 0;
37
- for (const message of value) {
38
- if (!message || typeof message !== "object" || !Array.isArray(message.parts)) throw new SurveyAssistantRequestError("The survey assistant messages are malformed.");
39
- for (const part of message.parts) {
40
- if (!part || typeof part !== "object" || typeof part.type !== "string") throw new SurveyAssistantRequestError("A survey assistant message part is malformed.");
41
- if (part.type === "text") {
42
- if (typeof part.text !== "string") throw new SurveyAssistantRequestError("A survey assistant text part is malformed.");
43
- if (part.text.length > 64e3) throw new SurveyAssistantRequestError("A survey assistant message is too long.");
44
- continue;
45
- }
46
- if (part.type !== "file") throw new SurveyAssistantRequestError("The survey assistant message part is not supported.");
47
- attachmentCount += 1;
48
- if (attachmentCount > 4) throw new SurveyAssistantRequestError("The survey assistant request has too many attachments.");
49
- if (typeof part.mediaType !== "string" || !SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES.has(part.mediaType.toLowerCase())) throw new SurveyAssistantRequestError("The survey assistant attachment type is not supported.");
50
- if (typeof part.url !== "string") throw new SurveyAssistantRequestError("The survey assistant attachment is malformed.");
51
- const bytes = getDataUrlBytes(part.url, part.mediaType);
52
- if (bytes > 5242880) throw new SurveyAssistantRequestError("A survey assistant attachment is too large.");
53
- totalAttachmentBytes += bytes;
54
- if (totalAttachmentBytes > 12582912) throw new SurveyAssistantRequestError("The survey assistant attachments are too large in total.");
55
- }
56
- }
57
- return value;
58
- };
59
- const readSurveyAssistantRequestJson = async (request) => {
60
- const declaredLength = Number(request.headers.get("content-length"));
61
- if (Number.isFinite(declaredLength) && declaredLength > 20971520) throw new SurveyAssistantRequestError("The survey assistant request is too large.", 413);
62
- const text = await request.text();
63
- if (new TextEncoder().encode(text).byteLength > 20971520) throw new SurveyAssistantRequestError("The survey assistant request is too large.", 413);
64
- try {
65
- return JSON.parse(text);
66
- } catch {
67
- throw new SurveyAssistantRequestError("The survey assistant request is not valid JSON.");
68
- }
69
- };
70
- //#endregion
71
- export { SURVEY_ASSISTANT_MAX_REQUEST_BYTES as a, SurveyAssistantRequestError as c, SURVEY_ASSISTANT_MAX_MESSAGES as i, readSurveyAssistantRequestJson as l, SURVEY_ASSISTANT_MAX_ATTACHMENTS as n, SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS as o, SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES as r, SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES as s, SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES as t, validateSurveyAssistantMessages as u };
72
-
73
- //# sourceMappingURL=request-guardrails-C59IWnH8.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-guardrails-C59IWnH8.mjs","names":[],"sources":["../src/server/request-guardrails.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\nexport const SURVEY_ASSISTANT_MAX_REQUEST_BYTES = 20 * 1024 * 1024;\nexport const SURVEY_ASSISTANT_MAX_MESSAGES = 32;\nexport const SURVEY_ASSISTANT_MAX_ATTACHMENTS = 4;\nexport const SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;\nexport const SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES = 12 * 1024 * 1024;\nexport const SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS = 64_000;\n\nexport const SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES = new Set([\n \"application/pdf\",\n \"image/gif\",\n \"image/jpeg\",\n \"image/png\",\n \"image/webp\",\n]);\n\nexport class SurveyAssistantRequestError extends Error {\n readonly status: number;\n\n constructor(message: string, status = 400) {\n super(message);\n this.name = \"SurveyAssistantRequestError\";\n this.status = status;\n }\n}\n\nconst getDataUrlBytes = (url: string, expectedMediaType: string): number => {\n const match = /^data:([^;,]+);base64,([A-Za-z0-9+/]*={0,2})$/.exec(url);\n if (!match) {\n throw new SurveyAssistantRequestError(\"Attachments must be base64 data URLs.\");\n }\n if (match[1]?.toLowerCase() !== expectedMediaType.toLowerCase()) {\n throw new SurveyAssistantRequestError(\"Attachment media type does not match its data URL.\");\n }\n\n const payload = match[2] ?? \"\";\n const padding = payload.endsWith(\"==\") ? 2 : payload.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);\n};\n\nexport const validateSurveyAssistantMessages = (value: unknown): UIMessage[] => {\n if (!Array.isArray(value) || value.length === 0) {\n throw new SurveyAssistantRequestError(\"A survey assistant message is required.\");\n }\n if (value.length > SURVEY_ASSISTANT_MAX_MESSAGES) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant request contains too many messages.\",\n );\n }\n if (value.length !== 1 || value[0]?.role !== \"user\") {\n throw new SurveyAssistantRequestError(\n \"The survey assistant request must contain only the current user message.\",\n );\n }\n\n let attachmentCount = 0;\n let totalAttachmentBytes = 0;\n for (const message of value) {\n if (!message || typeof message !== \"object\" || !Array.isArray(message.parts)) {\n throw new SurveyAssistantRequestError(\"The survey assistant messages are malformed.\");\n }\n\n for (const part of message.parts) {\n if (!part || typeof part !== \"object\" || typeof part.type !== \"string\") {\n throw new SurveyAssistantRequestError(\"A survey assistant message part is malformed.\");\n }\n if (part.type === \"text\") {\n if (typeof part.text !== \"string\") {\n throw new SurveyAssistantRequestError(\"A survey assistant text part is malformed.\");\n }\n if (part.text.length > SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS) {\n throw new SurveyAssistantRequestError(\"A survey assistant message is too long.\");\n }\n continue;\n }\n if (part.type !== \"file\") {\n throw new SurveyAssistantRequestError(\n \"The survey assistant message part is not supported.\",\n );\n }\n\n attachmentCount += 1;\n if (attachmentCount > SURVEY_ASSISTANT_MAX_ATTACHMENTS) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant request has too many attachments.\",\n );\n }\n if (\n typeof part.mediaType !== \"string\" ||\n !SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES.has(part.mediaType.toLowerCase())\n ) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant attachment type is not supported.\",\n );\n }\n if (typeof part.url !== \"string\") {\n throw new SurveyAssistantRequestError(\"The survey assistant attachment is malformed.\");\n }\n\n const bytes = getDataUrlBytes(part.url, part.mediaType);\n if (bytes > SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES) {\n throw new SurveyAssistantRequestError(\"A survey assistant attachment is too large.\");\n }\n totalAttachmentBytes += bytes;\n if (totalAttachmentBytes > SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant attachments are too large in total.\",\n );\n }\n }\n }\n\n return value as UIMessage[];\n};\n\nexport const readSurveyAssistantRequestJson = async (request: Request): Promise<unknown> => {\n const declaredLength = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > SURVEY_ASSISTANT_MAX_REQUEST_BYTES) {\n throw new SurveyAssistantRequestError(\"The survey assistant request is too large.\", 413);\n }\n\n const text = await request.text();\n if (new TextEncoder().encode(text).byteLength > SURVEY_ASSISTANT_MAX_REQUEST_BYTES) {\n throw new SurveyAssistantRequestError(\"The survey assistant request is too large.\", 413);\n }\n\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new SurveyAssistantRequestError(\"The survey assistant request is not valid JSON.\");\n }\n};\n"],"mappings":";AAEA,MAAa,qCAAqC,KAAK,OAAO;AAC9D,MAAa,gCAAgC;AAC7C,MAAa,mCAAmC;AAChD,MAAa,wCAAwC,IAAI,OAAO;AAChE,MAAa,8CAA8C,KAAK,OAAO;AACvE,MAAa,uCAAuC;AAEpD,MAAa,6CAA6C,IAAI,IAAI;CAChE;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,IAAa,8BAAb,cAAiD,MAAM;CACrD;CAEA,YAAY,SAAiB,SAAS,KAAK;AACzC,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;;;AAIlB,MAAM,mBAAmB,KAAa,sBAAsC;CAC1E,MAAM,QAAQ,gDAAgD,KAAK,IAAI;AACvE,KAAI,CAAC,MACH,OAAM,IAAI,4BAA4B,wCAAwC;AAEhF,KAAI,MAAM,IAAI,aAAa,KAAK,kBAAkB,aAAa,CAC7D,OAAM,IAAI,4BAA4B,qDAAqD;CAG7F,MAAM,UAAU,MAAM,MAAM;CAC5B,MAAM,UAAU,QAAQ,SAAS,KAAK,GAAG,IAAI,QAAQ,SAAS,IAAI,GAAG,IAAI;AACzE,QAAO,KAAK,IAAI,GAAG,KAAK,MAAO,QAAQ,SAAS,IAAK,EAAE,GAAG,QAAQ;;AAGpE,MAAa,mCAAmC,UAAgC;AAC9E,KAAI,CAAC,MAAM,QAAQ,MAAM,IAAI,MAAM,WAAW,EAC5C,OAAM,IAAI,4BAA4B,0CAA0C;AAElF,KAAI,MAAM,SAAA,GACR,OAAM,IAAI,4BACR,2DACD;AAEH,KAAI,MAAM,WAAW,KAAK,MAAM,IAAI,SAAS,OAC3C,OAAM,IAAI,4BACR,2EACD;CAGH,IAAI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AAQ,8BAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thread-handlers-DpynUc64.d.mts","names":[],"sources":["../src/server/handler.ts","../src/server/thread-handlers.ts"],"mappings":";;;;;;;KA0CK,eAAA,GAAkB,qBAAA;AAAA,UAEN,iCAAA;EACf,OAAA,EAAS,OAAA;EACT,mBAAA;EACA,iBAAA;EACA,iBAAA;AAAA;AAAA,KAGU,iCAAA,GAAoC,8BAAA;AAAA,KAEpC,wBAAA,IACV,KAAA,EAAO,iCAAA,KACJ,OAAA,CAAQ,iCAAA,IAAqC,iCAAA;AAAA,UAEjC,mCAAA;EACf,QAAA,EAAU,iCAAA;EACV,OAAA,EAAS,OAAA;EACT,gBAAA;AAAA;AAAA,KAGU,2BAAA,IACV,KAAA,EAAO,mCAAA,KAEL,OAAA,CAAQ,6BAAA,uBACR,6BAAA;AAAA,cAIS,iCAAA,SAA0C,KAAA;EAAA,SAC5C,MAAA;cAEG,OAAA,WAA6D,MAAA;AAAA;AAAA,UAO1D,0BAAA;EACf,aAAA;EACA,SAAA;EACA,WAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,iBAAA;AAAA;AAAA,UAGe,iCAAA;EACf,UAAA;EACA,QAAA;AAAA;AAAA,UAGe,iCAAA;EACf,MAAA,EAAQ,MAAA,UAAgB,MAAA,GAAS,OAAA,CAAQ,MAAA;EACzC,SAAA,EAAW,wBAAA;EACX,WAAA;EACA,OAAA;EACA,mBAAA,GAAsB,4BAAA;EACtB,SAAA,IAAa,OAAA,EAAS,OAAA,eAAsB,OAAA;EAC5C,iBAAA,IAAqB,OAAA,EAAS,OAAA,qBAA4B,OAAA;EAC1D,qBAAA;EACA,QAAA;EACA,YAAA;EACA,eAAA,GAAkB,eAAA;EAClB,aAAA;EACA,iBAAA,IAAqB,KAAA,WAAgB,OAAA,EAAS,iCAAA;EAC9C,aAAA,IAAiB,KAAA,WAAgB,OAAA,EAAS,iCAAA;EAC1C,aAAA,IAAiB,KAAA;IACf,OAA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EAAO,QAAA,aAAkB,OAAA,CAAA,QAAA;oBAgBvB,OAAA,EAAO,QAAA,aAAkB,OAAA,CAAA,QAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools-Hz2p7vyv.mjs","names":["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/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 { 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 { z } from \"zod\";\nimport { surveyAuthoringReferences, surveyAuthoringReferenceTopics } from \"../authoring-references\";\nimport {\n resolveAssistantCapabilityReference,\n type SurveyAssistantEngineContext,\n} from \"../../engine\";\nimport { toTextModelOutput } from \"./tool-model-output\";\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(\"Installed custom item type that owns this reference, when applicable.\"),\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 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 survey authoring reference or an installed item capability's reference. For a capability-owned reference, provide both itemType and the reference topic advertised in the capability manifest.\",\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 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 engineContext = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantEngineContext\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 entry = capabilityReference\n ? {\n title: capabilityReference.title ?? `${capability?.manifest.displayName} authoring`,\n content: capabilityReference.markdown,\n }\n : builtInEntry;\n\n if (!entry) {\n return {\n ok: false,\n topic: inputData.topic,\n itemType: inputData.itemType,\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 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 {\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 SURVEY_CHANGE_CONTINUATION_DESCRIPTION,\n SURVEY_CHANGE_CONTINUATION_MODES,\n createSurveyChangeSet,\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 requireSurveyAssistantTurnState,\n type SurveyAssistantRequestContext,\n} from \"../request-context\";\nimport { toTextModelOutput } from \"./tool-model-output\";\n\nexport const TOOL_ID = \"survey_change\";\n\nconst inputSchema = z.object({\n intent: z.string().min(1).max(500).describe(\"The concrete survey change requested by the user.\"),\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(\n 'Assistant operation objects to validate and package as one undoable change. Every operation uses the exact discriminator field \"kind\", never \"type\". Canonical create shape: { kind: \"create-item\", target: { parentItemId, index? }, item: { id, key, itemType, config }, translations?: [{ locale, contentKey, plainText } | { locale, contentKey, content }] }. Put parentItemId in target, respondent content in top-level translations, and item-type settings in item.config. When creating a new item that contains an imported or external image, put the complete richText content including its image block directly in create-item.translations[].content in the same call; never create a placeholder and then call update-placed-image because the new item is absent from the immutable snapshot. When deleting referenced images and their assets, include all reference-removal operations and remove-image-asset in this same operations array, with remove-image-asset last; do not split that dependency across survey_change and survey_asset. For a choice item, config.options entries use id and optional key/embeddedForm only; option labels are top-level translations at options.<optionId>.label. Canonical presentation shapes are { kind: \"update-item-label\", itemId, itemLabel } for the editor-only label and { kind: \"update-item-color\", itemId, color } for a supported editor swatch. Across editor views, unqualified labels for items/questions mean update-item-label; question titles and option/field labels are respondent-visible translations. Canonical item config shape: { kind: \"patch-item-config\", itemId, patches: [{ op, path, value? }] }, where paths are relative to that item config root. Inspect the item and load its capability reference first. Canonical add-choice-option shape: { kind: \"add-choice-option\", itemId, locale?, index?, option: { id?, key?, label: \"visible text\" } }; label is a plain string, and this operation creates its translation. Canonical text-update shape: { kind: \"update-item-translation\", itemId, locale, contentKey, plainText } for ordinary text; content is only a structured Content object for meaningful formatting. To edit one image already placed in rich text, use { kind: \"update-placed-image\", itemId, locale, contentKey, imageIndex, expectedAssetId?, changes } where imageIndex counts only image blocks from zero. changes can set a local asset source or an external URL and can update alt, caption, width, height, maxWidth, maxHeight, and alignment; null removes an optional property. This changes the rendered placement, while update-image-asset-metadata changes only global asset metadata. Canonical raw shape: { kind: \"survey-json-patch\", patches: [{ op, path, value? }] }; it must be the only operation and all related raw edits belong in its plural patches array, never patch. Patch paths are rooted at the survey, for example /surveyItems/<index>/config or /translations/<locale>. Keep proposals bounded; if validation says there are too many operations, split the same work into independent smaller change calls. Use compact typed operations for common edits, patch-item-config for item-local config, and one survey-json-patch operation for survey-wide raw edits.',\n ),\n continuationMode: z\n .enum(SURVEY_CHANGE_CONTINUATION_MODES)\n .nullish()\n .transform((value) => value ?? undefined)\n .describe(`${SURVEY_CHANGE_CONTINUATION_DESCRIPTION} Omit this field instead of sending null.`),\n inspectedContext: z\n .array(z.string().max(240))\n .max(20)\n .nullish()\n .transform((value) => value ?? undefined)\n .describe(\"Optional item ids, paths, or references inspected before proposing this change.\"),\n notes: z\n .string()\n .max(1000)\n .nullish()\n .transform((value) => value ?? undefined)\n .describe(\n \"Optional implementation notes for validation/debugging; not shown as persisted survey content.\",\n ),\n});\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 `Change id: ${event.id}`,\n ];\n\n if (event.operations.length > 0) {\n lines.push(`Operations: ${event.operations.map((operation) => operation.kind).join(\", \")}`);\n }\n\n if (event.status === \"rejected\") {\n lines.push(\n 'Apply status: this turn is blocked and will authorize no survey changes unless a later complete proposal validates with continuationMode \"replace\".',\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 \"Lifecycle: this candidate is registered, not live. Do not target its new ids again in this response; successful turn completion authorizes the collector's final candidate ids for browser apply.\",\n );\n if (event.supersedesChangeIds?.length) {\n lines.push(\n `Queue: replaces ${event.supersedesChangeIds.length} earlier survey_change proposal(s) from this response.`,\n );\n }\n }\n\n if (event.supersedesChangeIds?.length && event.status === \"rejected\") {\n lines.push(\n `Queue: discarded ${event.supersedesChangeIds.length} earlier candidate proposal(s); their work is not retained or authorized. Include that discarded work in the complete replacement before claiming the request is complete.`,\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 the complete create-item proposal with continuationMode \"replace\". 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 immediately split these edits into smaller survey_change calls. Use continuationMode \"replace\" on the first repaired chunk, then \"append\" on every later independent chunk. Do not claim that a new snapshot is needed unless a tool explicitly reported a missing snapshot.',\n );\n }\n\n if (issueCodes.has(\"change-mode-required\")) {\n lines.push(\n 'Recovery hint: retry the complete intended proposal with continuationMode \"append\" for independent additional work or \"replace\" for a correction. Nothing from the ambiguous sequence is currently authorized.',\n );\n }\n\n if (issueCodes.has(\"change-mode-repair-required\")) {\n lines.push(\n 'Recovery hint: the turn remains blocked. Retry the complete intended proposal with continuationMode \"replace\". Only a validated replacement clears the block; after that, use \"append\" for later independent chunks.',\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 'Validate and queue one final, bounded, undoable survey change. This is not a dry run and does not mutate the live snapshot during the response. Put related operations and newly created dependencies in one call, in dependency order; embed expressions on new dependent items. Omit continuationMode only on the first mutation call in a turn; every later mutation call must use \"append\" for independent additional work or \"replace\" for a correction. Every operation uses \"kind\". A create-item has top-level target, item, and translations.',\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 { changeCollector, turnId } = requireSurveyAssistantTurnState(\n context?.requestContext as RequestContext<SurveyAssistantRequestContext> | undefined,\n );\n const snapshot = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n const defaultLocale = snapshot?.ui.selectedLocale ?? snapshot?.inspection.locales[0] ?? \"en\";\n const continuationMode = inputData.continuationMode ?? undefined;\n const operationsParse = z\n .array(surveyOperationSchema)\n .safeParse(normalizeSurveyChangeOperations(inputData.operations, defaultLocale));\n\n if (!operationsParse.success) {\n return changeCollector.register(\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 { continuationMode },\n );\n }\n\n const event = createSurveyChangeSet({\n operations: operationsParse.data as SurveyOperation[],\n snapshot,\n summary: inputData.summary,\n turnId,\n });\n\n return changeCollector.register(event, { continuationMode });\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 SURVEY_CHANGE_CONTINUATION_DESCRIPTION,\n SURVEY_CHANGE_CONTINUATION_MODES,\n buildExpressionMutationPatches,\n createSurveyChangeSet,\n expressionMutationSchema,\n getRawSurveyItems,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../../engine\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\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 continuationModeSchema = z\n .enum(SURVEY_CHANGE_CONTINUATION_MODES)\n .optional()\n .describe(SURVEY_CHANGE_CONTINUATION_DESCRIPTION);\n\nconst prepareActionSchema = z.object({\n action: z.literal(\"prepare\"),\n intent: z.string().min(1).max(500),\n summary: z.string().min(1).max(500),\n mutations: z.array(expressionMutationSchema).min(1).max(40),\n continuationMode: continuationModeSchema,\n inspectedContext: z.array(z.string().max(240)).max(20).optional(),\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 intent: z\n .string()\n .min(1)\n .max(500)\n .optional()\n .describe(\"For prepare: requested expression edit.\"),\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 continuationMode: continuationModeSchema,\n inspectedContext: z.array(z.string().max(240)).max(20).optional(),\n })\n .superRefine((value, ctx) => {\n if (value.action !== \"prepare\") {\n return;\n }\n if (!value.intent) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"intent\"],\n message: \"Required for prepare.\",\n });\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 responseSlots: z.array(z.object({ ref: z.string(), valueType: z.string().optional() })),\n expressionLocations: z\n .array(\n z.object({\n itemId: z.string(),\n key: z.string(),\n itemType: z.string(),\n rawIndex: z.number().int().nonnegative(),\n locations: z.array(z.string()),\n }),\n )\n .optional(),\n});\n\nconst outputSchema = z.union([contextOutputSchema, surveyChangeSetSchema]);\n\ntype SurveyExpressionInput = z.infer<typeof inputSchema>;\ntype PrepareExpressionInput = z.infer<typeof prepareActionSchema>;\ntype ContextOutput = z.infer<typeof contextOutputSchema>;\n\ntype IssueInput = Omit<SurveyValidationIssue, \"severity\"> & {\n severity?: SurveyValidationIssue[\"severity\"];\n};\n\nconst createIssue = ({ severity = \"error\", ...input }: IssueInput): SurveyValidationIssue => ({\n severity,\n ...input,\n});\n\nconst buildResponseSlotTypes = (snapshot: SurveyAssistantSnapshot) => snapshot.responseSlotTypes;\n\nconst rejectedEvent = ({\n issues,\n summary,\n turnId,\n warnings = [],\n}: {\n issues: SurveyValidationIssue[];\n summary: string;\n turnId: string;\n warnings?: SurveyValidationIssue[];\n}): SurveyChangeSet => ({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n id: randomUUID(),\n turnId,\n status: \"rejected\",\n summary,\n operations: [],\n validation: {\n valid: false,\n issues,\n warnings,\n normalizedOperations: [],\n },\n createdAt: new Date().toISOString(),\n});\n\nconst summarizeDraftEvent = (event: SurveyChangeSet) => {\n const lines = [\n `${event.status === \"validated\" ? \"Validated\" : \"Rejected\"} expression change: ${event.summary}`,\n `Change id: ${event.id}`,\n ];\n\n if (event.operations.length > 0) {\n lines.push(`Operations: ${event.operations.map((operation) => operation.kind).join(\", \")}`);\n }\n\n if (event.status === \"rejected\") {\n lines.push(\n 'Apply status: this turn is blocked and will authorize no survey changes unless a later complete proposal validates with continuationMode \"replace\".',\n );\n }\n\n if (event.supersedesChangeIds?.length) {\n lines.push(\n event.status === \"validated\"\n ? `Queue: replaces ${event.supersedesChangeIds.length} earlier candidate proposal(s) from this response.`\n : `Queue: discarded ${event.supersedesChangeIds.length} earlier candidate proposal(s); their work is not retained or authorized.`,\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 (issueCodes.has(\"change-mode-required\")) {\n lines.push(\n 'Recovery hint: retry the complete intended proposal with continuationMode \"append\" for independent additional work or \"replace\" for a correction. Nothing from the ambiguous sequence is currently authorized.',\n );\n }\n if (issueCodes.has(\"change-mode-repair-required\")) {\n lines.push(\n 'Recovery hint: the turn remains blocked. Retry the complete intended proposal with continuationMode \"replace\". Only a validated replacement clears the block; after that, use \"append\" for later independent chunks.',\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\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 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 responseSlots,\n ...(expressionLocations ? { expressionLocations } : {}),\n };\n};\n\nexport const surveyExpressionTool = createTool({\n id: TOOL_ID,\n description:\n 'Inspect response refs or queue expression edits for CASE survey items already present in the live snapshot. Covers display and disabled conditions, validations, prefills, and template values. Newly proposed items are not visible until the response ends; embed their expressions in the same survey_change call that creates them. For prepare, omit continuationMode only on the first mutation call in a turn; every later mutation call must use \"append\" or \"replace\".',\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 = context?.requestContext?.get(\"engineContext\") 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 responseSlots: [],\n };\n }\n\n const { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);\n return changeCollector.register(\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 { continuationMode: input.continuationMode },\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 { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);\n\n const register = (event: SurveyChangeSet) =>\n changeCollector.register(event, { continuationMode: input.continuationMode });\n\n const prepareParse = prepareActionSchema.safeParse(inputData);\n if (!prepareParse.success) {\n return register(\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\n const prepareInput: PrepareExpressionInput = prepareParse.data;\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 register(\n rejectedEvent({ summary: prepareInput.summary, turnId, issues: errors, warnings }),\n );\n }\n\n if (patches.length === 0) {\n return register(\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 );\n }\n\n const operation: SurveyOperation = {\n kind: \"survey-json-patch\",\n patches,\n };\n\n const event = createSurveyChangeSet({\n operations: [operation],\n snapshot,\n summary: prepareInput.summary,\n turnId,\n });\n\n return register({\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 {\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\";\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 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 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 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 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 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}.`,\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(`Outline access: ${output.summary.outlineItemCount} item(s) are pageable.`);\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 ]\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 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 }\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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n scopes: input.scopes,\n };\n }\n\n const scopes = unique<SurveyContextScope>(input.scopes);\n const output: SurveyGetCurrentContextOutput = {\n ok: true,\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\n scopes,\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 {\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\";\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 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 ${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 `- 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 ${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((option) => `${option.value ?? option.id} (${option.labelContentKey})`)\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 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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n };\n }\n\n const outlineById = mapOutlineById(snapshot);\n const indexById = mapKeyIndexById(snapshot);\n const rawItemsById = mapRawItemsById(snapshot);\n const item = resolveItemSummary(input.itemId, indexById, outlineById);\n\n if (!item) {\n return {\n ok: false,\n reason: `No item matching \"${input.itemId}\" (by itemId, key, or fullKey) was found in the current context snapshot.`,\n };\n }\n\n const output: SurveyGetItemDetailsOutput = {\n ok: true,\n item,\n translations: buildItemTranslationEntries(snapshot, item.itemId, input),\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 const rawItem = rawItemsById.get(item.itemId);\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 rawConfig =\n rawItem.config && typeof rawItem.config === \"object\" && !Array.isArray(rawItem.config)\n ? (rawItem.config as { options?: unknown[] })\n : undefined;\n const rawOptions = Array.isArray(rawConfig?.options) ? rawConfig.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 {\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\";\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 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 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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n };\n }\n\n return {\n ok: true,\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\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 { 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\";\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 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 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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n query: input.query,\n };\n }\n\n const results = searchItems(snapshot, input);\n const page = sliceWithCursor(results, input);\n\n return {\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 results: page.items,\n };\n },\n toModelOutput: (value) => toTextModelOutput<SurveySearchItemsOutput>(value, summarizeForModel),\n});\n","import { createTool } from \"@mastra/core/tools\";\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\";\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 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: optionalInput(\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.\"),\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: optionalInput(z.array(z.string().min(1).max(500)).min(1).max(20)).describe(\n \"For raw-json: exact JSON Pointer paths to inspect.\",\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 assets,\n };\n};\n\nexport const surveyInspectTool = createTool({\n id: TOOL_ID,\n description:\n \"Inspect current survey state through one compact interface: current context, item search, item details, image assets with explicit asset IDs and usages, or focused raw JSON. Use this before making changes when the answer depends on the live editor state.\",\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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantSnapshot\n | undefined;\n\n if (!snapshot) {\n return {\n ok: false,\n action: input.action,\n reason: \"No live editor snapshot was provided with this assistant turn.\",\n modelSummary: \"No live editor snapshot 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 { z } from \"zod\";\nimport { auditSurvey, type SurveyAssistantEngineContext } from \"../../engine\";\nimport { toTextModelOutput } from \"./tool-model-output\";\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 = context?.requestContext?.get(\"engineContext\") as\n | SurveyAssistantEngineContext\n | 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 {\n createSurveyChangeSet,\n SURVEY_CHANGE_CONTINUATION_MODES,\n type SurveyAssistantEngineContext,\n} from \"../../engine\";\nimport {\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.object({\n action: z.enum([\"import-attachment\", \"update-metadata\", \"remove\"]),\n documentId: z.string().min(1).optional().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 continuationMode: z\n .enum(SURVEY_CHANGE_CONTINUATION_MODES)\n .optional()\n .describe(\n 'Required after any earlier mutation candidate in the turn. Use \"append\" to keep earlier candidates, including an imported asset; use \"replace\" only when resubmitting the complete intended proposal.',\n ),\n summary: z.string().min(1).max(500),\n});\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 `Change id: ${event.id}`,\n ];\n\n if (event.operations.length > 0) {\n lines.push(`Operations: ${event.operations.map(describeAssetOperation).join(\", \")}`);\n }\n if (event.status === \"validated\") {\n lines.push(\n \"Lifecycle: this candidate is registered, not live. The 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(`Asset id to reference: ${importedAssetIds.join(\", \")}`);\n lines.push(\n 'Required continuation: pass continuationMode \"append\" on every following mutation that should keep this asset import. To use the image in a NEW item, create that item in one survey_change call and put the image block directly in create-item.translations[].content; do not create placeholder text and do not call update-placed-image for an item that is not in the immutable snapshot. For an existing rich-text image placement, use update-placed-image. If a later proposal is rejected, re-import the attachment with continuationMode \"replace\", then append one corrected dependent survey_change; never replace the turn with only the asset reference.',\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 survey assets without asking the model to copy base64, or update/remove an existing image asset. The result is an undoable candidate change, not a live asset. After importing, pass continuationMode \"append\" to the dependent mutation so the import and references are authorized together. For a new item, embed the asset image block directly in create-item.translations[].content in that one dependent call; update-placed-image is only for an image placement that already exists in the immutable snapshot. This tool refuses to remove a currently referenced asset. To delete references and their asset together, use one survey_change candidate with reference-removal operations 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 { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);\n const snapshot = requestContext?.get(\"engineContext\") 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 while (snapshot?.survey.assets?.[assetId]) assetId = `${base}-${suffix++}`;\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 candidate containing every reference-removal operation first and remove-image-asset last. If replacing earlier candidates in this turn, that combined candidate must use continuationMode \"replace\".',\n operationIndex: 0,\n },\n ],\n normalizedOperations: [],\n },\n });\n }\n }\n\n return changeCollector.register(event, { continuationMode: input.continuationMode });\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":";;;;;;;;;;AAEA,MAAM,sBACJ;AAEF,MAAaA,sBAAoB,UAC/B,SAAS,OAAO,UAAU,YAAY,YAAY,SAAS,MAAM,WAAW,KAAA,IACxE,M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