@case-framework/survey-assistant 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/attachments-B0hg3vpT.mjs +11 -0
- package/dist/attachments-B0hg3vpT.mjs.map +1 -0
- package/dist/authoring-references-CW38pYzK.mjs +115 -0
- package/dist/authoring-references-CW38pYzK.mjs.map +1 -0
- package/dist/{capabilities-CnsVuJ1k.d.mts → capabilities-DVTfogjv.d.mts} +1 -1
- package/dist/{capabilities-CnsVuJ1k.d.mts.map → capabilities-DVTfogjv.d.mts.map} +1 -1
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +39 -9
- package/dist/capabilities-default.mjs.map +1 -1
- package/dist/{constants-CFUWrRtl.mjs → constants-0UHGFcRJ.mjs} +1 -1
- package/dist/{constants-CFUWrRtl.mjs.map → constants-0UHGFcRJ.mjs.map} +1 -1
- package/dist/{constants-k1b_evIb.d.mts → constants-BMGTgfjv.d.mts} +4 -4
- package/dist/{constants-k1b_evIb.d.mts.map → constants-BMGTgfjv.d.mts.map} +1 -1
- package/dist/{controller-proxy-jWIPOZAv.mjs → controller-proxy-DMTqer6T.mjs} +1 -1
- package/dist/{controller-proxy-jWIPOZAv.mjs.map → controller-proxy-DMTqer6T.mjs.map} +1 -1
- package/dist/{controller-proxy-quQjtA7j.d.mts → controller-proxy-mRvez2qw.d.mts} +3 -3
- package/dist/{controller-proxy-quQjtA7j.d.mts.map → controller-proxy-mRvez2qw.d.mts.map} +1 -1
- package/dist/{digest-Dyjch_sC.d.mts → digest-SJmoYVaK.d.mts} +2 -2
- package/dist/{digest-Dyjch_sC.d.mts.map → digest-SJmoYVaK.d.mts.map} +1 -1
- package/dist/digest.d.mts +1 -1
- package/dist/{engine-BvfUx_Jx.mjs → engine-CQwOAcwK.mjs} +167 -24
- package/dist/engine-CQwOAcwK.mjs.map +1 -0
- package/dist/engine.d.mts +3 -3
- package/dist/engine.mjs +3 -3
- package/dist/{fair-guidance-CEdJYccK.mjs → fair-guidance-CRYCRxQm.mjs} +1 -1
- package/dist/{fair-guidance-CEdJYccK.mjs.map → fair-guidance-CRYCRxQm.mjs.map} +1 -1
- package/dist/{form-authoring-BQh40yDb.mjs → form-authoring-kQDgC5oz.mjs} +1 -1
- package/dist/{form-authoring-BQh40yDb.mjs.map → form-authoring-kQDgC5oz.mjs.map} +1 -1
- package/dist/{index-biZnRl-h.d.mts → index-B0lxsAzx.d.mts} +10 -6
- package/dist/index-B0lxsAzx.d.mts.map +1 -0
- package/dist/{index-BDp6S7r9.d.mts → index-BS-Xjk1h.d.mts} +4 -4
- package/dist/{index-BDp6S7r9.d.mts.map → index-BS-Xjk1h.d.mts.map} +1 -1
- package/dist/{index-r8HVcn5b.d.mts → index-D6nqkz0O.d.mts} +49 -8
- package/dist/{index-r8HVcn5b.d.mts.map → index-D6nqkz0O.d.mts.map} +1 -1
- package/dist/{index-8x1Eqlnz.d.mts → index-DvTqML-0.d.mts} +10 -5
- package/dist/index-DvTqML-0.d.mts.map +1 -0
- package/dist/{lifecycle-DWv5CiSu.d.mts → lifecycle-BmGAIUlv.d.mts} +2 -2
- package/dist/{lifecycle-DWv5CiSu.d.mts.map → lifecycle-BmGAIUlv.d.mts.map} +1 -1
- package/dist/{memory-thread-repository-xBZOog_q.mjs → memory-thread-repository-CjFGVNZh.mjs} +44 -13
- package/dist/{memory-thread-repository-xBZOog_q.mjs.map → memory-thread-repository-CjFGVNZh.mjs.map} +1 -1
- package/dist/protocol.d.mts +4 -4
- package/dist/protocol.mjs +2 -1
- package/dist/{react-CY6N7lVi.mjs → react-Dqlmasrs.mjs} +2 -2
- package/dist/{react-CY6N7lVi.mjs.map → react-Dqlmasrs.mjs.map} +1 -1
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.mjs +2 -2
- package/dist/{request-context-DixY5DYu.mjs → request-context-BjTHNcDd.mjs} +2 -2
- package/dist/{request-context-DixY5DYu.mjs.map → request-context-BjTHNcDd.mjs.map} +1 -1
- package/dist/{request-guardrails-h4t6u8mP.mjs → request-guardrails-TmgQtqp4.mjs} +5 -12
- package/dist/request-guardrails-TmgQtqp4.mjs.map +1 -0
- package/dist/server-agent.d.mts +9 -7
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +8 -6
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +28 -14
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +47 -8
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +4 -4
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +7 -7
- package/dist/server.mjs +6 -6
- package/dist/storage-postgres.d.mts +1 -1
- package/dist/storage-postgres.mjs +4 -1
- package/dist/storage-postgres.mjs.map +1 -1
- package/dist/{tasks-BWmTMXoK.d.mts → tasks-DxzD25Zc.d.mts} +16 -4
- package/dist/tasks-DxzD25Zc.d.mts.map +1 -0
- package/dist/{thread-documents-Dvo6XS7o.d.mts → thread-documents-rmd6nyX9.d.mts} +1 -1
- package/dist/{thread-documents-Dvo6XS7o.d.mts.map → thread-documents-rmd6nyX9.d.mts.map} +1 -1
- package/dist/{thread-handlers-D8gkLfU6.d.mts → thread-handlers-AbQbt4sX.d.mts} +13 -6
- package/dist/{thread-handlers-D8gkLfU6.d.mts.map → thread-handlers-AbQbt4sX.d.mts.map} +1 -1
- package/dist/{tools-TXI8bfzZ.mjs → tools-CFh35R4d.mjs} +14 -6
- package/dist/tools-CFh35R4d.mjs.map +1 -0
- package/dist/ui.css +1 -1
- package/dist/ui.d.mts +3 -3
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +198 -83
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +37 -3
- package/package.json +2 -2
- package/dist/authoring-references-yyYC4Ydi.mjs +0 -98
- package/dist/authoring-references-yyYC4Ydi.mjs.map +0 -1
- package/dist/engine-BvfUx_Jx.mjs.map +0 -1
- package/dist/index-8x1Eqlnz.d.mts.map +0 -1
- package/dist/index-biZnRl-h.d.mts.map +0 -1
- package/dist/request-guardrails-h4t6u8mP.mjs.map +0 -1
- package/dist/tasks-BWmTMXoK.d.mts.map +0 -1
- package/dist/tools-TXI8bfzZ.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-guardrails-TmgQtqp4.mjs","names":[],"sources":["../src/server/request-guardrails.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\nimport { SURVEY_ASSISTANT_ATTACHMENT_MEDIA_TYPES } from \"../protocol/attachments\";\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;\nexport const SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS = 255;\n\nexport const SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES = new Set<string>(\n SURVEY_ASSISTANT_ATTACHMENT_MEDIA_TYPES,\n);\n\nexport interface SurveyAssistantRequestLimits {\n acceptedAttachmentTypes: ReadonlySet<string>;\n maxAttachmentBytes: number;\n maxAttachmentNameChars: number;\n maxAttachments: number;\n maxMessages: number;\n maxRequestBytes: number;\n maxTextPartChars: number;\n maxTotalAttachmentBytes: number;\n}\n\nexport const SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS: SurveyAssistantRequestLimits = Object.freeze({\n acceptedAttachmentTypes: SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES,\n maxAttachmentBytes: SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES,\n maxAttachmentNameChars: SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS,\n maxAttachments: SURVEY_ASSISTANT_MAX_ATTACHMENTS,\n maxMessages: SURVEY_ASSISTANT_MAX_MESSAGES,\n maxRequestBytes: SURVEY_ASSISTANT_MAX_REQUEST_BYTES,\n maxTextPartChars: SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS,\n maxTotalAttachmentBytes: SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES,\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 attachmentSignatures: Record<string, (bytes: Uint8Array) => boolean> = {\n \"application/pdf\": (bytes) =>\n bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46,\n \"image/jpeg\": (bytes) => bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff,\n \"image/png\": (bytes) =>\n [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every(\n (value, index) => bytes[index] === value,\n ),\n};\n\nconst decodeBase64Prefix = (payload: string) => {\n try {\n const binary = atob(payload.slice(0, 24));\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n } catch {\n throw new SurveyAssistantRequestError(\"The survey assistant attachment is malformed.\");\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 signatureMatches = attachmentSignatures[expectedMediaType.toLowerCase()];\n if (signatureMatches && !signatureMatches(decodeBase64Prefix(payload))) {\n throw new SurveyAssistantRequestError(\n \"Attachment content does not match its declared media type.\",\n );\n }\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 = (\n value: unknown,\n limits: SurveyAssistantRequestLimits = SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS,\n): UIMessage[] => {\n if (!Array.isArray(value) || value.length === 0) {\n throw new SurveyAssistantRequestError(\"A survey assistant message is required.\");\n }\n if (value.length > limits.maxMessages) {\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 > limits.maxTextPartChars) {\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 > limits.maxAttachments) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant request has too many attachments.\",\n );\n }\n if (\n typeof part.mediaType !== \"string\" ||\n !limits.acceptedAttachmentTypes.has(part.mediaType.toLowerCase())\n ) {\n throw new SurveyAssistantRequestError(\n \"The survey assistant attachment type is not supported. Upload a PDF, PNG, or JPEG file.\",\n );\n }\n if (typeof part.url !== \"string\") {\n throw new SurveyAssistantRequestError(\"The survey assistant attachment is malformed.\");\n }\n if (\n part.filename !== undefined &&\n (typeof part.filename !== \"string\" ||\n part.filename.length > limits.maxAttachmentNameChars ||\n /[\\u0000-\\u001f\\u007f]/.test(part.filename))\n ) {\n throw new SurveyAssistantRequestError(\"The survey assistant attachment name is invalid.\");\n }\n\n const bytes = getDataUrlBytes(part.url, part.mediaType);\n if (bytes > limits.maxAttachmentBytes) {\n throw new SurveyAssistantRequestError(\"A survey assistant attachment is too large.\");\n }\n totalAttachmentBytes += bytes;\n if (totalAttachmentBytes > limits.maxTotalAttachmentBytes) {\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 (\n request: Request,\n maxRequestBytes = SURVEY_ASSISTANT_MAX_REQUEST_BYTES,\n): Promise<unknown> => {\n const declaredLength = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > maxRequestBytes) {\n throw new SurveyAssistantRequestError(\"The survey assistant request is too large.\", 413);\n }\n\n const reader = request.body?.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n totalBytes += value.byteLength;\n if (totalBytes > maxRequestBytes) {\n await reader.cancel();\n throw new SurveyAssistantRequestError(\"The survey assistant request is too large.\", 413);\n }\n chunks.push(value);\n }\n }\n const bytes = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n const text = new TextDecoder().decode(bytes);\n\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new SurveyAssistantRequestError(\"The survey assistant request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,OAAO,MAAM;AAE5C,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,QAAM,IAAI,4BAA4B,kDAAkD"}
|
package/dist/server-agent.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { g as SurveyChangeSetShape } from "./lifecycle-
|
|
2
|
-
import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-
|
|
3
|
-
import { n as surveyAssistantTools } from "./index-
|
|
1
|
+
import { g as SurveyChangeSetShape } from "./lifecycle-BmGAIUlv.mjs";
|
|
2
|
+
import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-BMGTgfjv.mjs";
|
|
3
|
+
import { n as surveyAssistantTools } from "./index-B0lxsAzx.mjs";
|
|
4
4
|
import * as _$_mastra_core_agent0 from "@mastra/core/agent";
|
|
5
5
|
import { Agent, AgentConfig } from "@mastra/core/agent";
|
|
6
6
|
import { Memory } from "@mastra/memory";
|
|
@@ -37,7 +37,7 @@ declare const createSurveyAssistantAgent: ({
|
|
|
37
37
|
observationalMemory
|
|
38
38
|
}: CreateSurveyAssistantAgentOptions) => Agent<"survey-assistant-agent", Readonly<{
|
|
39
39
|
survey_inspect: _$_mastra_core_tools0.Tool<{
|
|
40
|
-
action: "current-context" | "search-items" | "item-details" | "
|
|
40
|
+
action: "localization" | "current-context" | "search-items" | "item-details" | "assets" | "expression-diagnostics" | "raw-json";
|
|
41
41
|
reason?: string | undefined;
|
|
42
42
|
scopes?: ("summary" | "selected-item" | "outline" | "response-slots" | "ui-context" | "history")[] | undefined;
|
|
43
43
|
query?: string | undefined;
|
|
@@ -53,7 +53,7 @@ declare const createSurveyAssistantAgent: ({
|
|
|
53
53
|
limit?: number | undefined;
|
|
54
54
|
}, {
|
|
55
55
|
ok: boolean;
|
|
56
|
-
action: "current-context" | "search-items" | "item-details" | "
|
|
56
|
+
action: "localization" | "current-context" | "search-items" | "item-details" | "assets" | "expression-diagnostics" | "raw-json";
|
|
57
57
|
modelSummary: string;
|
|
58
58
|
reason?: string | undefined;
|
|
59
59
|
result?: unknown;
|
|
@@ -66,7 +66,7 @@ declare const createSurveyAssistantAgent: ({
|
|
|
66
66
|
topic: string;
|
|
67
67
|
itemType?: string | undefined;
|
|
68
68
|
operationKind?: string | undefined;
|
|
69
|
-
detail?: "
|
|
69
|
+
detail?: "compact" | "full" | undefined;
|
|
70
70
|
reason?: string | undefined;
|
|
71
71
|
}, {
|
|
72
72
|
ok: boolean;
|
|
@@ -75,7 +75,7 @@ declare const createSurveyAssistantAgent: ({
|
|
|
75
75
|
content: string;
|
|
76
76
|
itemType?: string | undefined;
|
|
77
77
|
operationKind?: string | undefined;
|
|
78
|
-
detail?: "
|
|
78
|
+
detail?: "compact" | "full" | undefined;
|
|
79
79
|
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_authoring_reference", unknown>;
|
|
80
80
|
survey_expression: _$_mastra_core_tools0.Tool<{
|
|
81
81
|
action: "context" | "prepare";
|
|
@@ -128,6 +128,8 @@ declare const createSurveyAssistantAgent: ({
|
|
|
128
128
|
sourceLocale?: string | undefined;
|
|
129
129
|
targetLocales?: string[] | undefined;
|
|
130
130
|
maxFindings?: number | undefined;
|
|
131
|
+
keyReviewOffset?: number | undefined;
|
|
132
|
+
keyReviewLimit?: number | undefined;
|
|
131
133
|
reason?: string | undefined;
|
|
132
134
|
}, {
|
|
133
135
|
ok: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-agent.d.mts","names":[],"sources":["../src/server/agent.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"server-agent.d.mts","names":[],"sources":["../src/server/agent.ts"],"mappings":";;;;;;;;;;cAyBa,wCAAA,EAA0C,cAAA;AAAA,KA8SlD,0BAAA,GAA6B,WAAA,QACzB,yBAAA,SACA,oBAAA,aAEP,6BAAA;AAAA,KAGG,4BAAA,GAA+B,WAAA,CAClC,WAAA,CAAY,qBAAA,QAA6B,MAAA;AAAA,KA8E/B,yCAAA,GAA4C,OAAA,CACtD,4BAAA;AAAA,KAIG,8CAAA,GAAiD,OAAA,CACpD,IAAA,CAAK,yCAAA;EAEL,KAAA,EAAO,WAAA,CAAY,yCAAA;AAAA;AAAA,cAGR,8CAAA;EAAA;;;;cAMA,+CAAA;EAAmD,KAAA;EAAA,WAAA;EAAA,UAAA;EAAA,GAAA;AAAA,GAK7D,8CAAA,KAAiD,yCAAA;AAAA,UAkCnC,iCAAA;EACf,KAAA,EAAO,0BAAA;EACP,MAAA,GAAS,0BAAA;EACT,mBAAA,GAAsB,yCAAA;AAAA;AAAA,cAGX,0BAAA;EAA8B,MAAA;EAAA,KAAA;EAAA;AAAA,GAIxC,iCAAA,KAAiC,KAAA,2BAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;uBAAA,qBAAA,CAAA,oBAAA"}
|
package/dist/server-agent.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { d as getDeterministicCreateItemTypes } from "./form-authoring-
|
|
2
|
-
import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { d as getDeterministicCreateItemTypes } from "./form-authoring-kQDgC5oz.mjs";
|
|
2
|
+
import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-0UHGFcRJ.mjs";
|
|
3
|
+
import { n as formatSurveyAuthoringReferenceRoutingInstructions } from "./authoring-references-CW38pYzK.mjs";
|
|
4
|
+
import { t as FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from "./fair-guidance-CRYCRxQm.mjs";
|
|
5
|
+
import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-CFh35R4d.mjs";
|
|
5
6
|
import { createHash } from "node:crypto";
|
|
6
7
|
import { Agent } from "@mastra/core/agent";
|
|
7
8
|
import { Memory } from "@mastra/memory";
|
|
@@ -155,8 +156,9 @@ const buildInstructions = ({ requestContext }) => {
|
|
|
155
156
|
"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.",
|
|
156
157
|
"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.",
|
|
157
158
|
`Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action "expression-diagnostics" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, and bounded replacement candidates. Use action "localization" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action "assets" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what "this", "here", or "the highlighted part" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,
|
|
158
|
-
"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.",
|
|
159
|
-
`Use ${AUTHORING_REFERENCE_TOOL_NAME} to load
|
|
159
|
+
"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Apply its key-semantic-consistency principle to the returned key/content evidence; for a comprehensive audit, page keyReviewOffset until all key-review evidence has been reviewed. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.",
|
|
160
|
+
`Use ${AUTHORING_REFERENCE_TOOL_NAME} to load focused stable authoring conventions and payload contracts.`,
|
|
161
|
+
formatSurveyAuthoringReferenceRoutingInstructions(),
|
|
160
162
|
FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,
|
|
161
163
|
`Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,
|
|
162
164
|
`Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateItemTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments =\n surveyRequestContext?.get(\"modelAttachments\") ??\n surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments;\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = (attachments ?? []).filter(\n (attachment) =>\n !currentFileKeys.has(`${attachment.mediaType}\\u0000${attachment.contentHash}`),\n );\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? `${rootItem.fullKey} (id=${rootItem.itemId}, key=${rootItem.key})`\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.itemTypes.length > 0\n ? snapshot.capabilities.itemTypes\n .map((entry) => {\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const details = [\n `create=${entry.create}`,\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.itemType} (${details})` : entry.itemType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and itemType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"expression-diagnostics\" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, and bounded replacement candidates. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n \"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.\",\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load one narrow convention when needed: core-rules, survey-data-model, source-material-surveys, localization, rich-text-content, item-types, embedded-forms, expressions, assistant-operations, fair-by-design, or survey-quality. For item-types, pass itemType to load only the relevant installed type; omit itemType only for a genuine cross-type comparison. Load survey-quality before giving a substantive questionnaire-quality critique.`,\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover item structure/content/config, choices, forms, survey content, and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an item type, itemType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Reorders replace the complete inspected list and use optionIds, groupIds, or itemIds as documented by the tool.`,\n \"Canonical create-item shape: put parentItemId and optional index in target; put id, key, itemType, config, and any creation-time expressions in item; put respondent-visible plainText or structured content in top-level translations. Put choice maxSelection and options inside item.config. For top-level creation, target the root group identified by the snapshot or inspection.\",\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary respondent-visible text. Use content only for a complete structured Content value when formatting carries meaning. Item title, subtitle, topContent, bottomContent, cardFooter, info content, option labels, and field labels are translations, not item labels.\",\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"Use update-placed-image only for an image already embedded in rich text in the live survey or validated turn draft. It can switch the placement between a local asset and an external URL and update its rendered ALT text, caption, width, height, maximum dimensions, and alignment. For a new item, prefer putting the complete richText value with the image block directly in create-item.translations[].content. Do not use image asset metadata when the user asked to change one placed image.\",\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an info item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"A survey-json-patch proposal contains exactly one operation with kind survey-json-patch and one plural patches array containing every related raw edit. It must be the only operation in that survey_change call. Paths are rooted at the survey document, such as /surveyItems/<index>/config or /translations/<locale>; never start at /config or modify /$schema. Patch translation leaves rather than replacing existing locale or item-translation containers.\",\n \"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. For a newly created choiceItem, put the option and its embeddedForm directly in create-item. Default authoringMode to simple when the embedded form has exactly one supported field in one ordinary single-column group; use custom only for blank, multi-field, multi-group, conditional, or layout-customized follow-ups. For a new option on an existing choice item, use add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. Load embedded-forms and use set-embedded-form with relative translations for existing choice options. Use a raw patch only when the typed operations cannot express the requested change.\",\n \"For choiceItem, maxSelection 1 is single choice, null is unlimited multiple choice, and a positive number is capped multiple choice. Choice config options use ids/keys/configuration; respondent-visible option labels belong in translations at options.<optionId>.label.\",\n \"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Files attached to the current user message are already available directly. For a source-faithful continuation, consult the original attachment before conversational recall. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing; when the relevant pages, question range, or section are known, use documentRequests to provide that bounded reading focus. Always load the relevant stored source for factual document questions or source-faithful authoring; conversational memory is not a lossless copy. After the tool succeeds, the complete selected original PDFs/images are attached to your next model input: prioritize the requested focus, read the source directly, and continue the task. Never claim that a successfully loaded attachment is unavailable, ask for extracted text, or describe the attachment tool as an extraction limitation. Do not load unrelated attachments, and do not ask the user to upload a listed file again.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may also be embedded directly in create-item.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"When required structure or behavior is clear but ordinary respondent wording is open, choose concise, neutral, internally consistent wording. Ask only when ambiguity materially affects purpose, domain, language, or compliance.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;AAcA,MAAM,CACJ,mBACA,kBACA,sBACA,+BACA,sBACA,iBACA,mBACE;AAEJ,MAAa,2CAA2D;CACtE,IAAI;CACJ,kBAAkB,EAAE,QAAQ,kBAAkB;EAC5C,MAAM,uBAAuB;EAG7B,MAAM,cACJ,sBAAsB,IAAI,mBAAmB,IAC7C,sBAAsB,IAAI,mBAAmB,EAAE;EAEjD,IAAI,YAAY;AAChB,OAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,EACvD,KAAI,OAAO,QAAQ,SAAS,QAAQ;AAClC,eAAY;AACZ;;AAGJ,MAAI,YAAY,EAAG;EACnB,MAAM,cAAc,OAAO;AAC3B,MAAI,CAAC,eAAe,YAAY,SAAS,OAAQ;EAEjD,IAAI,wBAAwB;EAC5B,MAAM,iBAAiB,YAAY,QAAQ,KAAK,SAAS;AACvD,OAAI,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS,SAAU,QAAO;GAClE,MAAM,QAAQ,8CAA8C,KAAK,KAAK,KAAK;AAC3E,OA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,CAAC,uBAAuB,UAAU,CAAE,QAAO,cAAc,WAAW,QAAQ;KAEhF,MAAM,WAAW,QAAQ,OAAO;AAChC,YAAO,cAAc,WAAW;MAAE,GAAG;MAAW;MAAU,GAAG,WAAW,QAAQ;;IAEnF;GACF;;;AAeL,MAAa,iDAAiD;CAC5D,eAAe;CACf,mBAAmB;CACnB,wBAAwB;CACzB;AAED,MAAa,mDAAmD,EAC9D,OACA,aACA,YACA,GAAG,iBAC6F;CAChG;CACA,OAAO;CACP,mBAAmB;CACnB,0BAA0B;CAC1B,WAAW,EAAE,OAAO,UAAU;CAC9B,kBAAkB;CAClB,iBAAiB;CACjB,GAAG;CACH,aAAa;EACX,eAAe,+CAA+C;EAC9D,cAAc;EACd,kBAAkB;EAClB,YAAY;EACZ,cAAc;EACd,wBAAwB,+CAA+C;EACvE,aAAa;EACb,oBAAoB;EACpB,aACE;EACF,GAAG;EACJ;CACD,YAAY;EACV,mBAAmB,+CAA+C;EAClE,kBAAkB;EAClB,YAAY;EACZ,mBAAmB;EACnB,0BAA0B;EAC1B,aACE;EACF,GAAG;EACJ;CACF;AAQD,MAAa,8BAA8B,EACzC,QACA,OACA,0BAEA,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cAAc;CACd;CACA,OAAO;CACP,QACE,UACA,IAAI,kCAAkC,EACpC,SAAS;EACP,cAAc;EACd,qBACE,wBAAwB,QACpB,QACC,uBACD,gDAAgD,EACvC,OACR,CAAC;EACT,EACF,CAAC;CACJ,iBAAiB,CAAC,yCAAyC;CAC5D,CAAC"}
|
|
1
|
+
{"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateItemTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { formatSurveyAuthoringReferenceRoutingInstructions } from \"./authoring-references\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments =\n surveyRequestContext?.get(\"modelAttachments\") ??\n surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments;\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = (attachments ?? []).filter(\n (attachment) =>\n !currentFileKeys.has(`${attachment.mediaType}\\u0000${attachment.contentHash}`),\n );\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? `${rootItem.fullKey} (id=${rootItem.itemId}, key=${rootItem.key})`\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.itemTypes.length > 0\n ? snapshot.capabilities.itemTypes\n .map((entry) => {\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const details = [\n `create=${entry.create}`,\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.itemType} (${details})` : entry.itemType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and itemType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"expression-diagnostics\" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, and bounded replacement candidates. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n \"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Apply its key-semantic-consistency principle to the returned key/content evidence; for a comprehensive audit, page keyReviewOffset until all key-review evidence has been reviewed. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.\",\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load focused stable authoring conventions and payload contracts.`,\n formatSurveyAuthoringReferenceRoutingInstructions(),\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover item structure/content/config, choices, forms, survey content, and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an item type, itemType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Reorders replace the complete inspected list and use optionIds, groupIds, or itemIds as documented by the tool.`,\n \"Canonical create-item shape: put parentItemId and optional index in target; put id, key, itemType, config, and any creation-time expressions in item; put respondent-visible plainText or structured content in top-level translations. Put choice maxSelection and options inside item.config. For top-level creation, target the root group identified by the snapshot or inspection.\",\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary respondent-visible text. Use content only for a complete structured Content value when formatting carries meaning. Item title, subtitle, topContent, bottomContent, cardFooter, info content, option labels, and field labels are translations, not item labels.\",\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"Use update-placed-image only for an image already embedded in rich text in the live survey or validated turn draft. It can switch the placement between a local asset and an external URL and update its rendered ALT text, caption, width, height, maximum dimensions, and alignment. For a new item, prefer putting the complete richText value with the image block directly in create-item.translations[].content. Do not use image asset metadata when the user asked to change one placed image.\",\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an info item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"A survey-json-patch proposal contains exactly one operation with kind survey-json-patch and one plural patches array containing every related raw edit. It must be the only operation in that survey_change call. Paths are rooted at the survey document, such as /surveyItems/<index>/config or /translations/<locale>; never start at /config or modify /$schema. Patch translation leaves rather than replacing existing locale or item-translation containers.\",\n \"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. For a newly created choiceItem, put the option and its embeddedForm directly in create-item. Default authoringMode to simple when the embedded form has exactly one supported field in one ordinary single-column group; use custom only for blank, multi-field, multi-group, conditional, or layout-customized follow-ups. For a new option on an existing choice item, use add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. Load embedded-forms and use set-embedded-form with relative translations for existing choice options. Use a raw patch only when the typed operations cannot express the requested change.\",\n \"For choiceItem, maxSelection 1 is single choice, null is unlimited multiple choice, and a positive number is capped multiple choice. Choice config options use ids/keys/configuration; respondent-visible option labels belong in translations at options.<optionId>.label.\",\n \"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Files attached to the current user message are already available directly. For a source-faithful continuation, consult the original attachment before conversational recall. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing; when the relevant pages, question range, or section are known, use documentRequests to provide that bounded reading focus. Always load the relevant stored source for factual document questions or source-faithful authoring; conversational memory is not a lossless copy. After the tool succeeds, the complete selected original PDFs/images are attached to your next model input: prioritize the requested focus, read the source directly, and continue the task. Never claim that a successfully loaded attachment is unavailable, ask for extracted text, or describe the attachment tool as an extraction limitation. Do not load unrelated attachments, and do not ask the user to upload a listed file again.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may also be embedded directly in create-item.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"When required structure or behavior is clear but ordinary respondent wording is open, choose concise, neutral, internally consistent wording. Ask only when ambiguity materially affects purpose, domain, language, or compliance.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;;AAeA,MAAM,CACJ,mBACA,kBACA,sBACA,+BACA,sBACA,iBACA,mBACE;AAEJ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;EACnB,0BAA0B;EAC1B,aACE;EACF,GAAG;EACJ;CACF;AAQD,MAAa,8BAA8B,EACzC,QACA,OACA,0BAEA,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cAAc;CACd;CACA,OAAO;CACP,QACE,UACA,IAAI,kCAAkC,EACpC,SAAS;EACP,cAAc;EACd,qBACE,wBAAwB,QACpB,QACC,uBACD,gDAAgD,EACvC,OACR,CAAC;EACT,EACF,CAAC;CACJ,iBAAiB,CAAC,yCAAyC;CAC5D,CAAC"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { t as SurveyAssistantModelCatalog } from "./index-
|
|
2
|
-
import {
|
|
3
|
-
import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-
|
|
4
|
-
import { a as SurveyAssistantModelSelection } from "./constants-
|
|
1
|
+
import { t as SurveyAssistantModelCatalog } from "./index-DvTqML-0.mjs";
|
|
2
|
+
import { Gt as SurveyAssistantCapabilitySet } from "./index-D6nqkz0O.mjs";
|
|
3
|
+
import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-rmd6nyX9.mjs";
|
|
4
|
+
import { a as SurveyAssistantModelSelection } from "./constants-BMGTgfjv.mjs";
|
|
5
5
|
import { SurveyAssistantObservationalMemoryOptions, createSurveyAssistantAgent } from "./server-agent.mjs";
|
|
6
|
-
import {
|
|
7
|
-
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-
|
|
6
|
+
import { d as SurveyAssistantChatHandlerOptions, k as SurveyAssistantRequestLimits, l as SurveyAssistantAuthorize, p as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions } from "./thread-handlers-AbQbt4sX.mjs";
|
|
7
|
+
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-DxzD25Zc.mjs";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import { AgentExecutionOptions } from "@mastra/core/agent";
|
|
10
10
|
import { AzureOpenAIGatewayConfig, MastraModelGatewayInterface } from "@mastra/core/llm";
|
|
@@ -71,6 +71,18 @@ interface ParseSurveyAssistantEnvironmentOptions {
|
|
|
71
71
|
defaultMistralModel?: string;
|
|
72
72
|
defaultOpenAIModel?: string;
|
|
73
73
|
defaultProvider?: SurveyAssistantProvider;
|
|
74
|
+
/**
|
|
75
|
+
* Adds an explicit production rollout gate to assistant enablement. When
|
|
76
|
+
* true, an otherwise enabled assistant remains disabled outside development
|
|
77
|
+
* unless `SURVEY_ASSISTANT_ALLOW_EXPERIMENTAL_IDENTITY=true` is also set.
|
|
78
|
+
*
|
|
79
|
+
* Despite the legacy environment-variable name, this does not select an
|
|
80
|
+
* identity authority or replace the host's authorization callback. Most
|
|
81
|
+
* hosts with authenticated identity integration should omit it unless they
|
|
82
|
+
* deliberately want the additional rollout gate.
|
|
83
|
+
*
|
|
84
|
+
* @default false
|
|
85
|
+
*/
|
|
74
86
|
requireExperimentalIdentityOptIn?: boolean;
|
|
75
87
|
requireStorage?: boolean;
|
|
76
88
|
}
|
|
@@ -108,8 +120,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
108
120
|
off: "off";
|
|
109
121
|
}>>;
|
|
110
122
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
111
|
-
default: "default";
|
|
112
123
|
auto: "auto";
|
|
124
|
+
default: "default";
|
|
113
125
|
flex: "flex";
|
|
114
126
|
priority: "priority";
|
|
115
127
|
}>>;
|
|
@@ -136,8 +148,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
136
148
|
off: "off";
|
|
137
149
|
}>>;
|
|
138
150
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
139
|
-
default: "default";
|
|
140
151
|
auto: "auto";
|
|
152
|
+
default: "default";
|
|
141
153
|
flex: "flex";
|
|
142
154
|
priority: "priority";
|
|
143
155
|
}>>;
|
|
@@ -176,8 +188,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
176
188
|
off: "off";
|
|
177
189
|
}>>;
|
|
178
190
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
179
|
-
default: "default";
|
|
180
191
|
auto: "auto";
|
|
192
|
+
default: "default";
|
|
181
193
|
flex: "flex";
|
|
182
194
|
priority: "priority";
|
|
183
195
|
}>>;
|
|
@@ -204,8 +216,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
204
216
|
off: "off";
|
|
205
217
|
}>>;
|
|
206
218
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
207
|
-
default: "default";
|
|
208
219
|
auto: "auto";
|
|
220
|
+
default: "default";
|
|
209
221
|
flex: "flex";
|
|
210
222
|
priority: "priority";
|
|
211
223
|
}>>;
|
|
@@ -246,8 +258,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
246
258
|
off: "off";
|
|
247
259
|
}>>;
|
|
248
260
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
249
|
-
default: "default";
|
|
250
261
|
auto: "auto";
|
|
262
|
+
default: "default";
|
|
251
263
|
flex: "flex";
|
|
252
264
|
priority: "priority";
|
|
253
265
|
}>>;
|
|
@@ -274,8 +286,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
274
286
|
off: "off";
|
|
275
287
|
}>>;
|
|
276
288
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
277
|
-
default: "default";
|
|
278
289
|
auto: "auto";
|
|
290
|
+
default: "default";
|
|
279
291
|
flex: "flex";
|
|
280
292
|
priority: "priority";
|
|
281
293
|
}>>;
|
|
@@ -327,8 +339,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
327
339
|
off: "off";
|
|
328
340
|
}>>;
|
|
329
341
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
330
|
-
default: "default";
|
|
331
342
|
auto: "auto";
|
|
343
|
+
default: "default";
|
|
332
344
|
flex: "flex";
|
|
333
345
|
priority: "priority";
|
|
334
346
|
}>>;
|
|
@@ -355,8 +367,8 @@ declare const surveyAssistantConfigurationDocumentSchema: z.ZodObject<{
|
|
|
355
367
|
off: "off";
|
|
356
368
|
}>>;
|
|
357
369
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
358
|
-
default: "default";
|
|
359
370
|
auto: "auto";
|
|
371
|
+
default: "default";
|
|
360
372
|
flex: "flex";
|
|
361
373
|
priority: "priority";
|
|
362
374
|
}>>;
|
|
@@ -441,6 +453,7 @@ interface CreateSurveyAssistantRuntimeHandlersOptions {
|
|
|
441
453
|
mastra: Mastra | (() => Mastra | Promise<Mastra>);
|
|
442
454
|
modelRouter: SurveyAssistantModelRouter;
|
|
443
455
|
task?: TaskHandlerOverrides;
|
|
456
|
+
threads?: Pick<CreateSurveyAssistantThreadHandlersOptions, "onError">;
|
|
444
457
|
threadDocuments?: SurveyAssistantThreadDocumentRepository;
|
|
445
458
|
}
|
|
446
459
|
type CreateConfiguredSurveyAssistantRuntimeHandlersOptions = Omit<CreateSurveyAssistantRuntimeHandlersOptions, "config" | "modelRouter">;
|
|
@@ -451,6 +464,7 @@ declare const createSurveyAssistantRuntimeHandlers: ({
|
|
|
451
464
|
mastra,
|
|
452
465
|
modelRouter,
|
|
453
466
|
task,
|
|
467
|
+
threads: threadOptions,
|
|
454
468
|
threadDocuments
|
|
455
469
|
}: CreateSurveyAssistantRuntimeHandlersOptions) => {
|
|
456
470
|
chat: (request: Request) => Promise<Response>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":";;;;;;;;;;;;;KAaY,uBAAA;AAAA,KACA,iCAAA;AAAA,KAEA,wBAAA;AAAA,UAEK,8BAAA;EACf,EAAA;EACA,KAAA;EACA,eAAA;EACA,eAAA,GAAkB,qBAAA;AAAA;AAAA,UAGH,0BAAA;EACf,MAAA;EACA,UAAA;EACA,cAAA;EACA,UAAA,GAAa,wBAAA;EACb,YAAA;AAAA;AAAA,UAGe,6BAAA;EACf,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,8BAAA;EACf,sBAAA;EACA,aAAA;EACA,qBAAA;EAvB6C;EAyB7C,aAAA;EACA,QAAA;EACA,eAAA,GAAkB,qBAAA;EAClB,aAAA;AAAA;AAAA,UAGe,4BAAA;EACf,KAAA,GAAQ,0BAAA;EACR,QAAA,GAAW,6BAAA;EA7B4B;EA+BvC,cAAA;EACA,OAAA;;EAEA,aAAA;EACA,iBAAA;EA9BA;EAgCA,MAAA,GAAS,8BAAA;EACT,QAAA;EACA,mBAAA,EAAqB,yCAAA;EACrB,QAAA,EAAU,uBAAA;EAhCE;EAkCZ,cAAA;EACA,aAAA,EAAe,IAAA,CACb,4BAAA;EAOF,cAAA;;;;AAnCF;EAwCE,WAAA;EACA,SAAA,EAAW,8BAAA;AAAA;AAAA,UAGI,sCAAA;EACf,oBAAA;EACA,mBAAA;EACA,kBAAA;EACA,eAAA,GAAkB,uBAAA;
|
|
1
|
+
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":";;;;;;;;;;;;;KAaY,uBAAA;AAAA,KACA,iCAAA;AAAA,KAEA,wBAAA;AAAA,UAEK,8BAAA;EACf,EAAA;EACA,KAAA;EACA,eAAA;EACA,eAAA,GAAkB,qBAAA;AAAA;AAAA,UAGH,0BAAA;EACf,MAAA;EACA,UAAA;EACA,cAAA;EACA,UAAA,GAAa,wBAAA;EACb,YAAA;AAAA;AAAA,UAGe,6BAAA;EACf,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,8BAAA;EACf,sBAAA;EACA,aAAA;EACA,qBAAA;EAvB6C;EAyB7C,aAAA;EACA,QAAA;EACA,eAAA,GAAkB,qBAAA;EAClB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D,IAAA,CAClE,2CAAA;AAAA,cAOW,oCAAA;EAAwC,SAAA;EAAA,IAAA;EAAA,MAAA;EAAA,MAAA;EAAA,WAAA;EAAA,IAAA;EAAA,OAAA,EAAA,aAAA;EAAA;AAAA,GASlD,2CAAA;;oBAyD8B,OAAA,KAAO,OAAA,CAAA,QAAA;;;;;;;;;;UAwCvB,sBAAA,SAA+B,gCAAA;EAC9C,MAAA,EAAQ,4BAAA;EACR,cAAA,CACE,OAAA,EAAS,qDAAA,GACR,UAAA,QAAkB,oCAAA;AAAA;AAAA,UAGN,mCAAA;ED3WF;EC6Wb,mBAAA,GAAsB,4BAAA;AAAA;;;;;;cAQX,4BAAA,GACX,MAAA,EAAQ,4BAAA,EACR,cAAA,GAAgB,mCAAA,KACf,sBAAA"}
|
package/dist/server-runtime.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-
|
|
2
|
-
import { n as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./request-guardrails-
|
|
3
|
-
import { i as createSurveyAssistantChatHandler, n as createSurveyAssistantThreadHandlers, r as SurveyAssistantAuthorizationError, t as createMastraMemoryThreadRepository } from "./memory-thread-repository-
|
|
4
|
-
import { t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-
|
|
1
|
+
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-0UHGFcRJ.mjs";
|
|
2
|
+
import { n as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./request-guardrails-TmgQtqp4.mjs";
|
|
3
|
+
import { i as createSurveyAssistantChatHandler, n as createSurveyAssistantThreadHandlers, r as SurveyAssistantAuthorizationError, t as createMastraMemoryThreadRepository } from "./memory-thread-repository-CjFGVNZh.mjs";
|
|
4
|
+
import { t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-CFh35R4d.mjs";
|
|
5
5
|
import { SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS, createSurveyAssistantAgent, createSurveyAssistantObservationalMemoryOptions } from "./server-agent.mjs";
|
|
6
6
|
import { createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler } from "./server-tasks.mjs";
|
|
7
7
|
import { z } from "zod";
|
|
@@ -171,10 +171,46 @@ const createProviderOptions = (provider, options, sendReasoning) => {
|
|
|
171
171
|
};
|
|
172
172
|
return { [providerOptionsKey]: resolved };
|
|
173
173
|
};
|
|
174
|
+
const getConfiguredEnabledOverride = (env) => {
|
|
175
|
+
const value = getValue(env, "SURVEY_ASSISTANT_ENABLED");
|
|
176
|
+
if (value !== void 0 && value !== "true" && value !== "false") throw new Error("SURVEY_ASSISTANT_ENABLED must be \"true\" or \"false\".");
|
|
177
|
+
return value === void 0 ? void 0 : value === "true";
|
|
178
|
+
};
|
|
179
|
+
const isSurveyAssistantExplicitlyDisabled = (input, env) => {
|
|
180
|
+
const environmentOverride = getConfiguredEnabledOverride(env);
|
|
181
|
+
if (environmentOverride !== void 0) return !environmentOverride;
|
|
182
|
+
return typeof input === "object" && input !== null && "enabled" in input && input.enabled === false;
|
|
183
|
+
};
|
|
184
|
+
const createDisabledSurveyAssistantRuntimeConfig = () => {
|
|
185
|
+
const disabledModelId = "survey-assistant-disabled";
|
|
186
|
+
return {
|
|
187
|
+
provider: "openai",
|
|
188
|
+
defaultModelId: disabledModelId,
|
|
189
|
+
memoryModelId: disabledModelId,
|
|
190
|
+
modelIds: [disabledModelId],
|
|
191
|
+
models: [{
|
|
192
|
+
id: disabledModelId,
|
|
193
|
+
label: "Survey assistant disabled",
|
|
194
|
+
upstreamModelId: disabledModelId
|
|
195
|
+
}],
|
|
196
|
+
modelCatalogTtlMs: DEFAULT_CATALOG_TTL_MS,
|
|
197
|
+
enabled: false,
|
|
198
|
+
readinessError: null,
|
|
199
|
+
requestLimits: { ...SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS },
|
|
200
|
+
execution: {
|
|
201
|
+
firstResponseTimeoutMs: DEFAULT_FIRST_RESPONSE_TIMEOUT_MS,
|
|
202
|
+
idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,
|
|
203
|
+
maxConcurrentRequests: 4,
|
|
204
|
+
maxDurationMs: DEFAULT_MAX_DURATION_MS,
|
|
205
|
+
maxSteps: DEFAULT_MAX_STEPS,
|
|
206
|
+
sendReasoning: false
|
|
207
|
+
},
|
|
208
|
+
observationalMemory: false
|
|
209
|
+
};
|
|
210
|
+
};
|
|
174
211
|
const resolveConfiguredEnabled = (env, configured, requireExperimentalIdentityOptIn) => {
|
|
175
|
-
const environmentOverride =
|
|
176
|
-
|
|
177
|
-
return (environmentOverride === "true" ? true : environmentOverride === "false" ? false : configured ?? env.NODE_ENV === "development") && (!requireExperimentalIdentityOptIn || env.NODE_ENV === "development" || getBoolean(env, "SURVEY_ASSISTANT_ALLOW_EXPERIMENTAL_IDENTITY", false));
|
|
212
|
+
const environmentOverride = getConfiguredEnabledOverride(env);
|
|
213
|
+
return (environmentOverride !== void 0 ? environmentOverride : configured ?? env.NODE_ENV === "development") && (!requireExperimentalIdentityOptIn || env.NODE_ENV === "development" || getBoolean(env, "SURVEY_ASSISTANT_ALLOW_EXPERIMENTAL_IDENTITY", false));
|
|
178
214
|
};
|
|
179
215
|
const parseProvider = (env, fallback) => {
|
|
180
216
|
const value = getValue(env, "SURVEY_ASSISTANT_PROVIDER")?.toLowerCase();
|
|
@@ -207,6 +243,7 @@ const getReadinessError = ({ azure, env, modelWasConfigured, provider, requireSt
|
|
|
207
243
|
return null;
|
|
208
244
|
};
|
|
209
245
|
const parseSurveyAssistantConfigurationDocument = (input, env, { requireExperimentalIdentityOptIn = false, requireStorage = true } = {}) => {
|
|
246
|
+
if (isSurveyAssistantExplicitlyDisabled(input, env)) return createDisabledSurveyAssistantRuntimeConfig();
|
|
210
247
|
const document = surveyAssistantConfigurationDocumentSchema.parse(input);
|
|
211
248
|
const activeProvider = document.providers[document.activeProvider];
|
|
212
249
|
if (!activeProvider) throw new Error(`activeProvider references unknown provider "${document.activeProvider}".`);
|
|
@@ -340,6 +377,7 @@ const parseSurveyAssistantConfigurationDocument = (input, env, { requireExperime
|
|
|
340
377
|
};
|
|
341
378
|
};
|
|
342
379
|
const parseSurveyAssistantEnvironment = (env, { defaultLmStudioModel, defaultMistralModel = "mistral-medium-latest", defaultOpenAIModel = "gpt-5.4-nano", defaultProvider = "openai", requireExperimentalIdentityOptIn = false, requireStorage = true } = {}) => {
|
|
380
|
+
if (getConfiguredEnabledOverride(env) === false) return createDisabledSurveyAssistantRuntimeConfig();
|
|
343
381
|
const provider = parseProvider(env, defaultProvider);
|
|
344
382
|
const modelIdOptions = { allowNestedId: provider === "lmstudio" };
|
|
345
383
|
const configuredModelId = getOptionalSameProviderModelId(env, "SURVEY_ASSISTANT_MODEL", modelIdOptions);
|
|
@@ -585,7 +623,7 @@ const createSurveyAssistantRuntimeComponents = (config) => {
|
|
|
585
623
|
};
|
|
586
624
|
};
|
|
587
625
|
const resolveMastra = async (mastra) => typeof mastra === "function" ? mastra() : mastra;
|
|
588
|
-
const createSurveyAssistantRuntimeHandlers = ({ authorize, chat = {}, config, mastra, modelRouter, task = {}, threadDocuments }) => {
|
|
626
|
+
const createSurveyAssistantRuntimeHandlers = ({ authorize, chat = {}, config, mastra, modelRouter, task = {}, threads: threadOptions = {}, threadDocuments }) => {
|
|
589
627
|
const isEnabled = chat.isEnabled ?? (() => config.enabled);
|
|
590
628
|
const getReadinessError = chat.getReadinessError ?? (() => config.readinessError);
|
|
591
629
|
const chatHandler = createSurveyAssistantChatHandler({
|
|
@@ -632,6 +670,7 @@ const createSurveyAssistantRuntimeHandlers = ({ authorize, chat = {}, config, ma
|
|
|
632
670
|
if (!config.enabled) throw new SurveyAssistantAuthorizationError("Survey assistant is disabled.", 404);
|
|
633
671
|
return authorize.thread(request);
|
|
634
672
|
},
|
|
673
|
+
...threadOptions,
|
|
635
674
|
repository: createMastraMemoryThreadRepository({
|
|
636
675
|
getMemory,
|
|
637
676
|
threadDocuments
|