@case-framework/survey-assistant 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{authoring-references-DYuOAdVx.mjs → authoring-references-ChDTVnms.mjs} +8 -2
- package/dist/authoring-references-ChDTVnms.mjs.map +1 -0
- package/dist/{capabilities-DlC1l6qy.d.mts → capabilities-CnsVuJ1k.d.mts} +12 -4
- package/dist/capabilities-CnsVuJ1k.d.mts.map +1 -0
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +38 -4
- package/dist/capabilities-default.mjs.map +1 -1
- package/dist/{constants-CgV4cTg5.d.mts → constants-BK1-g6pR.d.mts} +12 -7
- package/dist/constants-BK1-g6pR.d.mts.map +1 -0
- package/dist/{controller-proxy-BzpEOygv.d.mts → controller-proxy-CIDRd8Wu.d.mts} +2 -2
- package/dist/{controller-proxy-BzpEOygv.d.mts.map → controller-proxy-CIDRd8Wu.d.mts.map} +1 -1
- package/dist/{controller-proxy-0WJZUZYx.mjs → controller-proxy-DY36XFV3.mjs} +2 -2
- package/dist/{controller-proxy-0WJZUZYx.mjs.map → controller-proxy-DY36XFV3.mjs.map} +1 -1
- package/dist/{digest-BvXpeWcR.d.mts → digest-Dyjch_sC.d.mts} +2 -2
- package/dist/{digest-BvXpeWcR.d.mts.map → digest-Dyjch_sC.d.mts.map} +1 -1
- package/dist/digest.d.mts +1 -1
- package/dist/{engine-0AJrv0hI.mjs → engine-CWTuN3o2.mjs} +866 -663
- package/dist/engine-CWTuN3o2.mjs.map +1 -0
- package/dist/engine.d.mts +3 -3
- package/dist/engine.mjs +3 -3
- package/dist/fair-guidance-CEdJYccK.mjs +21 -0
- package/dist/fair-guidance-CEdJYccK.mjs.map +1 -0
- package/dist/form-authoring-DCd9XfXf.mjs +155 -0
- package/dist/form-authoring-DCd9XfXf.mjs.map +1 -0
- package/dist/{index-BUF-sE8j.d.mts → index-Bp5W_oPa.d.mts} +27 -7
- package/dist/index-Bp5W_oPa.d.mts.map +1 -0
- package/dist/{index-BdXb6jER.d.mts → index-CPOQgkTN.d.mts} +67 -6
- package/dist/index-CPOQgkTN.d.mts.map +1 -0
- package/dist/{index-BiTT71Xp.d.mts → index-EDL1V168.d.mts} +101 -7
- package/dist/{index-BiTT71Xp.d.mts.map → index-EDL1V168.d.mts.map} +1 -1
- package/dist/{index-BNdvGEaq.d.mts → index-SPHf3OoJ.d.mts} +9 -3
- package/dist/index-SPHf3OoJ.d.mts.map +1 -0
- package/dist/{memory-thread-repository-1ocPOda8.mjs → memory-thread-repository-acbz6HZJ.mjs} +181 -26
- package/dist/memory-thread-repository-acbz6HZJ.mjs.map +1 -0
- package/dist/{protocol-DpCYmCjr.mjs → protocol-DATvkr1S.mjs} +125 -6
- package/dist/protocol-DATvkr1S.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +2 -2
- package/dist/{react-DXK5zWNo.mjs → react-3kSE6WtS.mjs} +127 -9
- package/dist/react-3kSE6WtS.mjs.map +1 -0
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.mjs +2 -2
- package/dist/references/assistant-operations.md +13 -18
- package/dist/references/embedded-forms.md +41 -2
- package/dist/references/expressions.md +17 -9
- package/dist/references/fair-by-design.md +80 -0
- package/dist/references/item-types.md +19 -3
- package/dist/references/localization.md +7 -4
- package/dist/references/source-material-surveys.md +6 -4
- package/dist/{request-context-BBzU3VdG.mjs → request-context-BEjnaaFr.mjs} +10 -5
- package/dist/request-context-BEjnaaFr.mjs.map +1 -0
- package/dist/server-agent.d.mts +28 -8
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +70 -13
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +22 -11
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +47 -19
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +4 -3
- package/dist/server-tasks.mjs.map +1 -1
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +16 -7
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -4
- package/dist/storage-postgres.d.mts +1 -1
- package/dist/{tasks-BuLnWrR4.d.mts → tasks-DIZgr4nD.d.mts} +8 -4
- package/dist/tasks-DIZgr4nD.d.mts.map +1 -0
- package/dist/{thread-documents-BlxNjc7S.d.mts → thread-documents-C3kf0Vds.d.mts} +1 -1
- package/dist/{thread-documents-BlxNjc7S.d.mts.map → thread-documents-C3kf0Vds.d.mts.map} +1 -1
- package/dist/{thread-handlers-6L8sAreR.d.mts → thread-handlers-DZ1WsorO.d.mts} +9 -4
- package/dist/thread-handlers-DZ1WsorO.d.mts.map +1 -0
- package/dist/{tools-wgLen05n.mjs → tools-GDd5_GUh.mjs} +403 -77
- package/dist/tools-GDd5_GUh.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 +152 -36
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +73 -5
- package/package.json +4 -4
- package/dist/authoring-references-DYuOAdVx.mjs.map +0 -1
- package/dist/capabilities-DKbNCnBf.mjs +0 -66
- package/dist/capabilities-DKbNCnBf.mjs.map +0 -1
- package/dist/capabilities-DlC1l6qy.d.mts.map +0 -1
- package/dist/constants-CgV4cTg5.d.mts.map +0 -1
- package/dist/engine-0AJrv0hI.mjs.map +0 -1
- package/dist/index-BNdvGEaq.d.mts.map +0 -1
- package/dist/index-BUF-sE8j.d.mts.map +0 -1
- package/dist/index-BdXb6jER.d.mts.map +0 -1
- package/dist/memory-thread-repository-1ocPOda8.mjs.map +0 -1
- package/dist/protocol-DpCYmCjr.mjs.map +0 -1
- package/dist/react-DXK5zWNo.mjs.map +0 -1
- package/dist/request-context-BBzU3VdG.mjs.map +0 -1
- package/dist/tasks-BuLnWrR4.d.mts.map +0 -1
- package/dist/thread-handlers-6L8sAreR.d.mts.map +0 -1
- package/dist/tools-wgLen05n.mjs.map +0 -1
package/dist/server-agent.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as getDeterministicCreateItemTypes } from "./form-authoring-DCd9XfXf.mjs";
|
|
2
2
|
import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CFUWrRtl.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { t as FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from "./fair-guidance-CEdJYccK.mjs";
|
|
4
|
+
import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-GDd5_GUh.mjs";
|
|
4
5
|
import { createHash } from "node:crypto";
|
|
5
6
|
import { Agent } from "@mastra/core/agent";
|
|
6
7
|
import { Memory } from "@mastra/memory";
|
|
@@ -91,6 +92,7 @@ const formatCurrentEditorContext = (snapshot) => {
|
|
|
91
92
|
`Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,
|
|
92
93
|
`Survey locales: ${locales}`,
|
|
93
94
|
`Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,
|
|
95
|
+
"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.",
|
|
94
96
|
`Deterministically creatable item types: ${creatableItemTypes}`,
|
|
95
97
|
`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.`
|
|
96
98
|
].filter((line) => Boolean(line)).join("\n");
|
|
@@ -108,9 +110,35 @@ const formatDocumentTransition = (transition) => {
|
|
|
108
110
|
"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."
|
|
109
111
|
].filter((line) => Boolean(line)).join("\n");
|
|
110
112
|
};
|
|
113
|
+
const formatPreviousApplyOutcome = (outcome) => {
|
|
114
|
+
if (!outcome) return void 0;
|
|
115
|
+
const resultDetails = (outcome.results ?? []).map((result) => JSON.stringify({
|
|
116
|
+
changeId: result.changeId,
|
|
117
|
+
status: result.status,
|
|
118
|
+
summary: result.summary,
|
|
119
|
+
message: result.message,
|
|
120
|
+
appliedOperations: result.appliedOperations
|
|
121
|
+
}));
|
|
122
|
+
const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) => JSON.stringify({
|
|
123
|
+
changeId: change.changeId,
|
|
124
|
+
status: change.status,
|
|
125
|
+
summary: change.summary,
|
|
126
|
+
operationCount: change.operationCount
|
|
127
|
+
}));
|
|
128
|
+
const common = [
|
|
129
|
+
`Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,
|
|
130
|
+
"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.",
|
|
131
|
+
...resultDetails.length > 0 ? [`Reported change results:\n${resultDetails.join("\n")}`] : [],
|
|
132
|
+
...preparedChangeDetails.length > 0 ? [`Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\n${preparedChangeDetails.join("\n")}`] : []
|
|
133
|
+
];
|
|
134
|
+
if (outcome.status === "settle-failed") common.push("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.");
|
|
135
|
+
else common.push("Do not repeat the prior completion claim or assume the proposed change set was applied in full. Use the reported per-change results and current snapshot; if the user still wants missing work, inspect current state and repair or retry it.");
|
|
136
|
+
return common.join("\n");
|
|
137
|
+
};
|
|
111
138
|
const buildInstructions = ({ requestContext }) => {
|
|
112
139
|
const snapshot = requestContext.get("engineContext");
|
|
113
140
|
const documentTransition = requestContext.get("documentTransition");
|
|
141
|
+
const previousApplyOutcome = requestContext.get("previousApplyOutcome");
|
|
114
142
|
const attachmentAccess = requestContext.get("attachmentAccess");
|
|
115
143
|
const attachmentManifest = attachmentAccess?.documents.length ? attachmentAccess.documents.map((document) => JSON.stringify({
|
|
116
144
|
id: document.id,
|
|
@@ -126,14 +154,15 @@ const buildInstructions = ({ requestContext }) => {
|
|
|
126
154
|
"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.",
|
|
127
155
|
"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.",
|
|
128
156
|
"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.",
|
|
129
|
-
`Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. 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.`,
|
|
130
|
-
`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, 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.`,
|
|
157
|
+
`Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. 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
|
+
`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.`,
|
|
159
|
+
FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,
|
|
131
160
|
`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.`,
|
|
132
161
|
`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.`,
|
|
133
162
|
`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.`,
|
|
134
163
|
"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.",
|
|
135
164
|
"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.",
|
|
136
|
-
"Survey languages are locale branches. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code;
|
|
165
|
+
"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.",
|
|
137
166
|
"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.",
|
|
138
167
|
"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.",
|
|
139
168
|
"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.",
|
|
@@ -141,24 +170,27 @@ const buildInstructions = ({ requestContext }) => {
|
|
|
141
170
|
"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.",
|
|
142
171
|
"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.",
|
|
143
172
|
"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.",
|
|
144
|
-
"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther.
|
|
173
|
+
"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.",
|
|
145
174
|
"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.",
|
|
146
175
|
"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.",
|
|
147
176
|
"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.",
|
|
148
|
-
`Files attached to the current user message are already available directly. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing. 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 selected original PDFs/images are attached to your next model input: read
|
|
177
|
+
`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.`,
|
|
149
178
|
`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.`,
|
|
150
179
|
"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.",
|
|
151
180
|
`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.`,
|
|
152
181
|
"A rejected mutation leaves the validated draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. Never drop requested behavior merely to obtain validation.",
|
|
153
|
-
"
|
|
154
|
-
"
|
|
182
|
+
"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.",
|
|
183
|
+
"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.",
|
|
184
|
+
"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.",
|
|
185
|
+
"Before answering, reconcile every requested target against the latest validated draft. 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.",
|
|
155
186
|
"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.",
|
|
156
|
-
"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt,
|
|
187
|
+
"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.",
|
|
157
188
|
"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.",
|
|
158
189
|
`Attachment document ids available for explicit loading or asset import:\n${attachmentManifest}`,
|
|
190
|
+
formatPreviousApplyOutcome(previousApplyOutcome),
|
|
159
191
|
formatDocumentTransition(documentTransition),
|
|
160
192
|
formatCurrentEditorContext(snapshot)
|
|
161
|
-
].join("\n\n");
|
|
193
|
+
].filter((section) => Boolean(section)).join("\n\n");
|
|
162
194
|
};
|
|
163
195
|
const isInitialMessageRecall = (inputData) => {
|
|
164
196
|
if (!inputData || typeof inputData !== "object" || Array.isArray(inputData)) return false;
|
|
@@ -168,6 +200,23 @@ const isInitialMessageRecall = (inputData) => {
|
|
|
168
200
|
const hasThreadId = typeof input.threadId === "string" && input.threadId.length > 0;
|
|
169
201
|
return (mode === void 0 || mode === "messages") && !hasCursor && !hasThreadId;
|
|
170
202
|
};
|
|
203
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
204
|
+
const createBrowsingOnlyRecallInputSchema = (schema) => {
|
|
205
|
+
const rawSchema = isRecord(schema) && typeof schema.getSchema === "function" ? schema.getSchema() : schema;
|
|
206
|
+
if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;
|
|
207
|
+
const properties = { ...rawSchema.properties };
|
|
208
|
+
const mode = properties.mode;
|
|
209
|
+
if (isRecord(mode) && Array.isArray(mode.enum)) properties.mode = {
|
|
210
|
+
...mode,
|
|
211
|
+
enum: mode.enum.filter((value) => value !== "search"),
|
|
212
|
+
description: "What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured."
|
|
213
|
+
};
|
|
214
|
+
delete properties.query;
|
|
215
|
+
return {
|
|
216
|
+
...rawSchema,
|
|
217
|
+
properties
|
|
218
|
+
};
|
|
219
|
+
};
|
|
171
220
|
var ThreadScopedSurveyAssistantMemory = class extends Memory {
|
|
172
221
|
listTools(config) {
|
|
173
222
|
const tools = super.listTools(config);
|
|
@@ -178,7 +227,15 @@ var ThreadScopedSurveyAssistantMemory = class extends Memory {
|
|
|
178
227
|
...tools,
|
|
179
228
|
recall: {
|
|
180
229
|
...recall,
|
|
230
|
+
description: "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.",
|
|
231
|
+
inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),
|
|
181
232
|
execute: async (inputData, context) => {
|
|
233
|
+
if (isRecord(inputData) && inputData.mode === "search") return {
|
|
234
|
+
error: "Semantic conversation search is unavailable because this memory has no vector store or embedder.",
|
|
235
|
+
code: "semantic-search-unavailable",
|
|
236
|
+
availableModes: ["messages", "threads"],
|
|
237
|
+
recovery: "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."
|
|
238
|
+
};
|
|
182
239
|
if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);
|
|
183
240
|
const threadId = context.agent?.threadId;
|
|
184
241
|
return executeRecall(threadId ? {
|
|
@@ -213,7 +270,7 @@ const createSurveyAssistantObservationalMemoryOptions = ({ model, observation, r
|
|
|
213
270
|
previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,
|
|
214
271
|
threadTitle: true,
|
|
215
272
|
observeAttachments: false,
|
|
216
|
-
instruction: "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. 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.",
|
|
273
|
+
instruction: "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.",
|
|
217
274
|
...observation
|
|
218
275
|
},
|
|
219
276
|
reflection: {
|
|
@@ -222,7 +279,7 @@ const createSurveyAssistantObservationalMemoryOptions = ({ model, observation, r
|
|
|
222
279
|
blockAfter: 1.5,
|
|
223
280
|
activateAfterIdle: false,
|
|
224
281
|
activateOnProviderChange: true,
|
|
225
|
-
instruction: "Consolidate related survey requirements and decisions while preserving corrections, explicit constraints, unresolved work, source references,
|
|
282
|
+
instruction: "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.",
|
|
226
283
|
...reflection
|
|
227
284
|
}
|
|
228
285
|
});
|
|
@@ -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 { 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 `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 buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\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, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. 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 `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, 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 `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. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; load its assistant-operations contract before proposing the change. Never substitute translation-by-translation deletion or a raw patch. The final remaining locale cannot be removed.\",\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. Load embedded-forms and prefer set-embedded-form with its relative translations. If the option is also new, put add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. 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. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing. 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 selected original PDFs/images are attached to your next model input: read them 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 draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. Never drop requested behavior merely to obtain validation.\",\n \"Prefer one mutation call for an ordinary request. Split work only for genuine dependencies or bounded chunks; accumulation is automatic.\",\n \"Before answering, reconcile every requested target against the latest validated draft. Never claim rejected, missing, partial, or failed work was completed. If a request remains incomplete, correct it once or state the exact remaining work.\",\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, prepare the complete change, then 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 formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\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\n// Mastra's thread-scoped recall schema omits threadId and rejects the first page\n// when the model provides neither a cursor nor a thread ID. Bind the active\n// thread internally so retrieval stays thread-scoped instead of widening to a resource.\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 execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\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. 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 constraints, unresolved work, source references, and completion or failure status. Remove superseded assumptions and repetitive tool detail. 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":";;;;;;;AAaA,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,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AgB,OAAO;AAC7B,SAAO;GACL,GAAG;GACH,QAAQ;IACN,GAAG;IACH,SAAS,OACP,WACA,YACG;AACH,SAAI,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 { 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 the proposed change set was applied in full. Use the reported per-change results and current snapshot; if the user still wants missing work, inspect current state and repair or retry it.\",\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, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. 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 `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 draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. 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. 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,QA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SAAS,UAAU,IAAI,UAAU,SAAS,SAC5C,QAAO;MACL,OACE;MACF,MAAM;MACN,gBAAgB,CAAC,YAAY,UAAU;MACvC,UACE;MACH;AAEH,SAAI,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,16 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-
|
|
1
|
+
import { E as SurveyAssistantModelCatalog } from "./index-EDL1V168.mjs";
|
|
2
|
+
import { Bt as SurveyAssistantCapabilitySet } from "./index-CPOQgkTN.mjs";
|
|
3
|
+
import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-C3kf0Vds.mjs";
|
|
4
|
+
import { a as SurveyAssistantModelSelection } from "./constants-BK1-g6pR.mjs";
|
|
4
5
|
import { SurveyAssistantObservationalMemoryOptions, createSurveyAssistantAgent } from "./server-agent.mjs";
|
|
5
|
-
import { O as SurveyAssistantRequestLimits, c as SurveyAssistantAuthorize, f as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions } from "./thread-handlers-
|
|
6
|
-
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-
|
|
6
|
+
import { O as SurveyAssistantRequestLimits, c as SurveyAssistantAuthorize, f as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions } from "./thread-handlers-DZ1WsorO.mjs";
|
|
7
|
+
import { c as createSurveyAssistantTaskAgent, n as CreateSurveyAssistantTaskHandlerOptions, s as SurveyAssistantTaskModelResolutionInput } from "./tasks-DIZgr4nD.mjs";
|
|
7
8
|
import { AgentExecutionOptions } from "@mastra/core/agent";
|
|
8
9
|
import { AzureOpenAIGatewayConfig, MastraModelGatewayInterface } from "@mastra/core/llm";
|
|
9
10
|
import { Mastra } from "@mastra/core/mastra";
|
|
10
11
|
|
|
11
12
|
//#region src/server/runtime-config.d.ts
|
|
12
|
-
type SurveyAssistantProvider = "azure-openai" | "mistral" | "openai";
|
|
13
|
-
type SurveyAssistantProviderOptionsKey = "azure" | "mistral" | "openai";
|
|
13
|
+
type SurveyAssistantProvider = "azure-openai" | "lmstudio" | "mistral" | "openai";
|
|
14
|
+
type SurveyAssistantProviderOptionsKey = "azure" | "lmstudio" | "mistral" | "openai";
|
|
14
15
|
interface SurveyAssistantAzureConfig {
|
|
15
16
|
apiKey?: string;
|
|
16
17
|
apiVersion: string;
|
|
@@ -18,8 +19,15 @@ interface SurveyAssistantAzureConfig {
|
|
|
18
19
|
management?: AzureOpenAIGatewayConfig["management"];
|
|
19
20
|
resourceName?: string;
|
|
20
21
|
}
|
|
22
|
+
interface SurveyAssistantLmStudioConfig {
|
|
23
|
+
apiKey?: string;
|
|
24
|
+
baseUrl: string;
|
|
25
|
+
}
|
|
21
26
|
interface SurveyAssistantExecutionConfig {
|
|
27
|
+
firstResponseTimeoutMs: number;
|
|
28
|
+
idleTimeoutMs: number;
|
|
22
29
|
maxConcurrentRequests: number;
|
|
30
|
+
/** Absolute execution ceiling. Active streams still stop when this duration is reached. */
|
|
23
31
|
maxDurationMs: number;
|
|
24
32
|
maxSteps: number;
|
|
25
33
|
providerOptions?: AgentExecutionOptions["providerOptions"];
|
|
@@ -27,6 +35,7 @@ interface SurveyAssistantExecutionConfig {
|
|
|
27
35
|
}
|
|
28
36
|
interface SurveyAssistantRuntimeConfig {
|
|
29
37
|
azure?: SurveyAssistantAzureConfig;
|
|
38
|
+
lmstudio?: SurveyAssistantLmStudioConfig;
|
|
30
39
|
/** Default chat model and fallback for chat requests without a selection. */
|
|
31
40
|
defaultModelId: string;
|
|
32
41
|
enabled: boolean;
|
|
@@ -46,6 +55,7 @@ interface SurveyAssistantRuntimeConfig {
|
|
|
46
55
|
execution: SurveyAssistantExecutionConfig;
|
|
47
56
|
}
|
|
48
57
|
interface ParseSurveyAssistantEnvironmentOptions {
|
|
58
|
+
defaultLmStudioModel?: string;
|
|
49
59
|
defaultMistralModel?: string;
|
|
50
60
|
defaultOpenAIModel?: string;
|
|
51
61
|
defaultProvider?: SurveyAssistantProvider;
|
|
@@ -55,6 +65,7 @@ interface ParseSurveyAssistantEnvironmentOptions {
|
|
|
55
65
|
type Environment = Record<string, string | undefined>;
|
|
56
66
|
declare const resolveSurveyAssistantProviderOptionsKey: (provider: SurveyAssistantProvider) => SurveyAssistantProviderOptionsKey;
|
|
57
67
|
declare const parseSurveyAssistantEnvironment: (env: Environment, {
|
|
68
|
+
defaultLmStudioModel,
|
|
58
69
|
defaultMistralModel,
|
|
59
70
|
defaultOpenAIModel,
|
|
60
71
|
defaultProvider,
|
|
@@ -64,17 +75,17 @@ declare const parseSurveyAssistantEnvironment: (env: Environment, {
|
|
|
64
75
|
//#endregion
|
|
65
76
|
//#region src/server/runtime.d.ts
|
|
66
77
|
interface SurveyAssistantModelRouter {
|
|
67
|
-
defaultModel:
|
|
78
|
+
defaultModel: SurveyAssistantModelSelection["model"];
|
|
68
79
|
gateways?: Record<string, MastraModelGatewayInterface>;
|
|
69
80
|
getCatalog(options?: {
|
|
70
81
|
refresh?: boolean;
|
|
71
82
|
}): Promise<SurveyAssistantModelCatalog>;
|
|
72
|
-
memoryModel:
|
|
83
|
+
memoryModel: SurveyAssistantModelSelection["model"];
|
|
73
84
|
providerName: string;
|
|
74
85
|
providerOptions?: AgentExecutionOptions["providerOptions"];
|
|
75
86
|
resolveModel: SurveyAssistantResolveModel;
|
|
76
87
|
resolveTaskModel(input: SurveyAssistantTaskModelResolutionInput): ReturnType<SurveyAssistantResolveModel>;
|
|
77
|
-
taskModel?:
|
|
88
|
+
taskModel?: SurveyAssistantModelSelection["model"];
|
|
78
89
|
}
|
|
79
90
|
declare const createSurveyAssistantModelRouter: (config: SurveyAssistantRuntimeConfig) => SurveyAssistantModelRouter;
|
|
80
91
|
interface SurveyAssistantRuntimeComponents {
|
|
@@ -135,5 +146,5 @@ interface CreateSurveyAssistantRuntimeOptions {
|
|
|
135
146
|
*/
|
|
136
147
|
declare const createSurveyAssistantRuntime: (config: SurveyAssistantRuntimeConfig, runtimeOptions?: CreateSurveyAssistantRuntimeOptions) => SurveyAssistantRuntime;
|
|
137
148
|
//#endregion
|
|
138
|
-
export { CreateConfiguredSurveyAssistantRuntimeHandlersOptions, CreateSurveyAssistantRuntimeHandlersOptions, CreateSurveyAssistantRuntimeOptions, type ParseSurveyAssistantEnvironmentOptions, type SurveyAssistantAzureConfig, type SurveyAssistantExecutionConfig, SurveyAssistantModelRouter, type SurveyAssistantProvider, type SurveyAssistantProviderOptionsKey, SurveyAssistantRuntime, SurveyAssistantRuntimeComponents, type SurveyAssistantRuntimeConfig, createSurveyAssistantModelRouter, createSurveyAssistantRuntime, createSurveyAssistantRuntimeComponents, createSurveyAssistantRuntimeHandlers, parseSurveyAssistantEnvironment, resolveSurveyAssistantProviderOptionsKey };
|
|
149
|
+
export { CreateConfiguredSurveyAssistantRuntimeHandlersOptions, CreateSurveyAssistantRuntimeHandlersOptions, CreateSurveyAssistantRuntimeOptions, type ParseSurveyAssistantEnvironmentOptions, type SurveyAssistantAzureConfig, type SurveyAssistantExecutionConfig, type SurveyAssistantLmStudioConfig, SurveyAssistantModelRouter, type SurveyAssistantProvider, type SurveyAssistantProviderOptionsKey, SurveyAssistantRuntime, SurveyAssistantRuntimeComponents, type SurveyAssistantRuntimeConfig, createSurveyAssistantModelRouter, createSurveyAssistantRuntime, createSurveyAssistantRuntimeComponents, createSurveyAssistantRuntimeHandlers, parseSurveyAssistantEnvironment, resolveSurveyAssistantProviderOptionsKey };
|
|
139
150
|
//# sourceMappingURL=server-runtime.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":";;;;;;;;;;;;KAYY,uBAAA;AAAA,KACA,iCAAA;AAAA,UAEK,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;EAlB2C;EAoB3C,aAAA;EACA,QAAA;E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