@case-framework/survey-assistant 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +212 -0
- package/dist/authoring-references-Cy8J-DWt.d.mts +48 -0
- package/dist/authoring-references-Cy8J-DWt.d.mts.map +1 -0
- package/dist/authoring-references-X6uRaWuf.mjs +68 -0
- package/dist/authoring-references-X6uRaWuf.mjs.map +1 -0
- package/dist/capabilities-B6tvE7fK.mjs +66 -0
- package/dist/capabilities-B6tvE7fK.mjs.map +1 -0
- package/dist/capabilities-DvSKtjAw.d.mts +182 -0
- package/dist/capabilities-DvSKtjAw.d.mts.map +1 -0
- package/dist/capabilities-default.d.mts +15 -0
- package/dist/capabilities-default.d.mts.map +1 -0
- package/dist/capabilities-default.mjs +347 -0
- package/dist/capabilities-default.mjs.map +1 -0
- package/dist/constants-CFUWrRtl.mjs +7 -0
- package/dist/constants-CFUWrRtl.mjs.map +1 -0
- package/dist/constants-Jw0k8ojS.d.mts +67 -0
- package/dist/constants-Jw0k8ojS.d.mts.map +1 -0
- package/dist/controller-proxy-BRDusFiO.d.mts +57 -0
- package/dist/controller-proxy-BRDusFiO.d.mts.map +1 -0
- package/dist/controller-proxy-Duxo2IFE.mjs +92 -0
- package/dist/controller-proxy-Duxo2IFE.mjs.map +1 -0
- package/dist/digest-BsoVq49o.d.mts +9 -0
- package/dist/digest-BsoVq49o.d.mts.map +1 -0
- package/dist/digest.d.mts +2 -0
- package/dist/digest.mjs +20 -0
- package/dist/digest.mjs.map +1 -0
- package/dist/engine-sPvuixWg.mjs +4857 -0
- package/dist/engine-sPvuixWg.mjs.map +1 -0
- package/dist/engine.d.mts +3 -0
- package/dist/engine.mjs +4 -0
- package/dist/index-BWNHkpkh.d.mts +187 -0
- package/dist/index-BWNHkpkh.d.mts.map +1 -0
- package/dist/index-CUqbBjkc.d.mts +641 -0
- package/dist/index-CUqbBjkc.d.mts.map +1 -0
- package/dist/index-MpEMQzTm.d.mts +123 -0
- package/dist/index-MpEMQzTm.d.mts.map +1 -0
- package/dist/index-TFtvBiSQ.d.mts +1149 -0
- package/dist/index-TFtvBiSQ.d.mts.map +1 -0
- package/dist/memory-thread-repository-CJkkVE2-.mjs +718 -0
- package/dist/memory-thread-repository-CJkkVE2-.mjs.map +1 -0
- package/dist/protocol-DV0ka9WT.mjs +1032 -0
- package/dist/protocol-DV0ka9WT.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -0
- package/dist/protocol.mjs +2 -0
- package/dist/react-VuYe-cPh.mjs +521 -0
- package/dist/react-VuYe-cPh.mjs.map +1 -0
- package/dist/react-integration.d.mts +2 -0
- package/dist/react-integration.mjs +3 -0
- package/dist/react.d.mts +3 -0
- package/dist/react.mjs +4 -0
- package/dist/references/assistant-operations.md +287 -0
- package/dist/references/core-rules.md +11 -0
- package/dist/references/embedded-forms.md +80 -0
- package/dist/references/expressions.md +301 -0
- package/dist/references/item-types.md +364 -0
- package/dist/references/localization.md +25 -0
- package/dist/references/rich-text-content.md +193 -0
- package/dist/references/source-material-surveys.md +60 -0
- package/dist/references/survey-data-model.md +109 -0
- package/dist/references/survey-quality.md +23 -0
- package/dist/request-context-jcmXT_Q2.mjs +44 -0
- package/dist/request-context-jcmXT_Q2.mjs.map +1 -0
- package/dist/request-guardrails-C59IWnH8.mjs +73 -0
- package/dist/request-guardrails-C59IWnH8.mjs.map +1 -0
- package/dist/server-agent.d.mts +131 -0
- package/dist/server-agent.d.mts.map +1 -0
- package/dist/server-agent.mjs +229 -0
- package/dist/server-agent.mjs.map +1 -0
- package/dist/server-runtime.d.mts +123 -0
- package/dist/server-runtime.d.mts.map +1 -0
- package/dist/server-runtime.mjs +296 -0
- package/dist/server-runtime.mjs.map +1 -0
- package/dist/server-tasks.d.mts +78 -0
- package/dist/server-tasks.d.mts.map +1 -0
- package/dist/server-tasks.mjs +253 -0
- package/dist/server-tasks.mjs.map +1 -0
- package/dist/server-tools.d.mts +2 -0
- package/dist/server-tools.mjs +2 -0
- package/dist/server.d.mts +52 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +6 -0
- package/dist/storage-postgres.d.mts +37 -0
- package/dist/storage-postgres.d.mts.map +1 -0
- package/dist/storage-postgres.mjs +167 -0
- package/dist/storage-postgres.mjs.map +1 -0
- package/dist/thread-documents-DamIq9Od.d.mts +91 -0
- package/dist/thread-documents-DamIq9Od.d.mts.map +1 -0
- package/dist/thread-handlers-DpynUc64.d.mts +112 -0
- package/dist/thread-handlers-DpynUc64.d.mts.map +1 -0
- package/dist/tools-Hz2p7vyv.mjs +1879 -0
- package/dist/tools-Hz2p7vyv.mjs.map +1 -0
- package/dist/ui.css +2 -0
- package/dist/ui.d.mts +63 -0
- package/dist/ui.d.mts.map +1 -0
- package/dist/ui.mjs +2238 -0
- package/dist/ui.mjs.map +1 -0
- package/package.json +166 -0
- package/ui.css.d.ts +3 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { a as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-Jw0k8ojS.mjs";
|
|
2
|
+
import { n as surveyAssistantTools } from "./index-MpEMQzTm.mjs";
|
|
3
|
+
import * as _$_mastra_core_agent0 from "@mastra/core/agent";
|
|
4
|
+
import { Agent, AgentConfig } from "@mastra/core/agent";
|
|
5
|
+
import { Memory } from "@mastra/memory";
|
|
6
|
+
import * as _$_mastra_core_tools0 from "@mastra/core/tools";
|
|
7
|
+
import { InputProcessor } from "@mastra/core/processors";
|
|
8
|
+
|
|
9
|
+
//#region src/server/agent.d.ts
|
|
10
|
+
declare const surveyAssistantThreadAttachmentProcessor: InputProcessor;
|
|
11
|
+
type SurveyAssistantAgentConfig = AgentConfig<typeof SURVEY_ASSISTANT_AGENT_ID, typeof surveyAssistantTools, undefined, SurveyAssistantRequestContext>;
|
|
12
|
+
type SurveyAssistantMemoryOptions = NonNullable<NonNullable<ConstructorParameters<typeof Memory>[0]>["options"]>;
|
|
13
|
+
type SurveyAssistantObservationalMemoryOptions = Exclude<SurveyAssistantMemoryOptions["observationalMemory"], boolean | undefined>;
|
|
14
|
+
type SurveyAssistantObservationalMemoryOptionsInput = Partial<Omit<SurveyAssistantObservationalMemoryOptions, "model">> & {
|
|
15
|
+
model: NonNullable<SurveyAssistantObservationalMemoryOptions["model"]>;
|
|
16
|
+
};
|
|
17
|
+
declare const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS: {
|
|
18
|
+
readonly messageTokens: 48000;
|
|
19
|
+
readonly observationTokens: 80000;
|
|
20
|
+
readonly previousObserverTokens: 24000;
|
|
21
|
+
};
|
|
22
|
+
declare const createSurveyAssistantObservationalMemoryOptions: ({
|
|
23
|
+
model,
|
|
24
|
+
observation,
|
|
25
|
+
reflection,
|
|
26
|
+
...overrides
|
|
27
|
+
}: SurveyAssistantObservationalMemoryOptionsInput) => SurveyAssistantObservationalMemoryOptions;
|
|
28
|
+
interface CreateSurveyAssistantAgentOptions {
|
|
29
|
+
model: SurveyAssistantAgentConfig["model"];
|
|
30
|
+
memory?: SurveyAssistantAgentConfig["memory"];
|
|
31
|
+
observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;
|
|
32
|
+
}
|
|
33
|
+
declare const createSurveyAssistantAgent: ({
|
|
34
|
+
memory,
|
|
35
|
+
model,
|
|
36
|
+
observationalMemory
|
|
37
|
+
}: CreateSurveyAssistantAgentOptions) => Agent<"survey-assistant-agent", Readonly<{
|
|
38
|
+
survey_inspect: _$_mastra_core_tools0.Tool<{
|
|
39
|
+
action: "current-context" | "search-items" | "item-details" | "assets" | "raw-json";
|
|
40
|
+
reason: unknown;
|
|
41
|
+
scopes: unknown;
|
|
42
|
+
query: unknown;
|
|
43
|
+
itemRef: unknown;
|
|
44
|
+
cursor: unknown;
|
|
45
|
+
outlineMode: unknown;
|
|
46
|
+
paths: unknown;
|
|
47
|
+
includeChildren: unknown;
|
|
48
|
+
includeItemConfig: unknown;
|
|
49
|
+
limit: unknown;
|
|
50
|
+
} | {
|
|
51
|
+
action: "current-context" | "search-items" | "item-details" | "assets" | "raw-json";
|
|
52
|
+
reason?: string | undefined;
|
|
53
|
+
scopes?: ("summary" | "selected-item" | "outline" | "response-slots" | "ui-context" | "history")[] | undefined;
|
|
54
|
+
query?: string | undefined;
|
|
55
|
+
itemRef?: string | undefined;
|
|
56
|
+
cursor?: string | undefined;
|
|
57
|
+
outlineMode?: "full" | "focused" | "children" | undefined;
|
|
58
|
+
paths?: string[] | undefined;
|
|
59
|
+
includeChildren?: boolean | undefined;
|
|
60
|
+
includeItemConfig?: boolean | undefined;
|
|
61
|
+
limit?: number | undefined;
|
|
62
|
+
}, {
|
|
63
|
+
ok: boolean;
|
|
64
|
+
action: "current-context" | "search-items" | "item-details" | "assets" | "raw-json";
|
|
65
|
+
modelSummary: string;
|
|
66
|
+
reason?: string | undefined;
|
|
67
|
+
result?: unknown;
|
|
68
|
+
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_inspect", unknown>;
|
|
69
|
+
survey_change: _$_mastra_core_tools0.Tool<{
|
|
70
|
+
intent: string;
|
|
71
|
+
summary: string;
|
|
72
|
+
operations: unknown[];
|
|
73
|
+
continuationMode?: "replace" | "append" | null | undefined;
|
|
74
|
+
inspectedContext?: string[] | null | undefined;
|
|
75
|
+
notes?: string | null | undefined;
|
|
76
|
+
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_change", unknown>;
|
|
77
|
+
survey_authoring_reference: _$_mastra_core_tools0.Tool<{
|
|
78
|
+
topic: string;
|
|
79
|
+
itemType?: string | undefined;
|
|
80
|
+
reason?: string | undefined;
|
|
81
|
+
}, {
|
|
82
|
+
ok: boolean;
|
|
83
|
+
topic: string;
|
|
84
|
+
title: string;
|
|
85
|
+
content: string;
|
|
86
|
+
itemType?: string | undefined;
|
|
87
|
+
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_authoring_reference", unknown>;
|
|
88
|
+
survey_expression: _$_mastra_core_tools0.Tool<{
|
|
89
|
+
action: "context" | "prepare";
|
|
90
|
+
reason?: string | undefined;
|
|
91
|
+
itemIds?: string[] | undefined;
|
|
92
|
+
includeRawLocations?: boolean | undefined;
|
|
93
|
+
intent?: string | undefined;
|
|
94
|
+
summary?: string | undefined;
|
|
95
|
+
mutations?: Record<string, unknown>[] | undefined;
|
|
96
|
+
continuationMode?: "replace" | "append" | undefined;
|
|
97
|
+
inspectedContext?: string[] | undefined;
|
|
98
|
+
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_expression", unknown>;
|
|
99
|
+
survey_attachment: _$_mastra_core_tools0.Tool<{
|
|
100
|
+
documentIds: string[];
|
|
101
|
+
}, {
|
|
102
|
+
loaded: {
|
|
103
|
+
id: string;
|
|
104
|
+
filename: string;
|
|
105
|
+
mediaType: string;
|
|
106
|
+
}[];
|
|
107
|
+
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_attachment", unknown>;
|
|
108
|
+
survey_audit: _$_mastra_core_tools0.Tool<{
|
|
109
|
+
sourceLocale?: string | undefined;
|
|
110
|
+
targetLocales?: string[] | undefined;
|
|
111
|
+
maxFindings?: number | undefined;
|
|
112
|
+
reason?: string | undefined;
|
|
113
|
+
}, {
|
|
114
|
+
ok: boolean;
|
|
115
|
+
reason?: string | undefined;
|
|
116
|
+
report?: unknown;
|
|
117
|
+
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_audit", unknown>;
|
|
118
|
+
survey_asset: _$_mastra_core_tools0.Tool<{
|
|
119
|
+
action: "import-attachment" | "update-metadata" | "remove";
|
|
120
|
+
summary: string;
|
|
121
|
+
documentId?: string | undefined;
|
|
122
|
+
assetId?: string | undefined;
|
|
123
|
+
name?: string | null | undefined;
|
|
124
|
+
filename?: string | null | undefined;
|
|
125
|
+
alt?: string | null | undefined;
|
|
126
|
+
continuationMode?: "replace" | "append" | undefined;
|
|
127
|
+
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_asset", unknown>;
|
|
128
|
+
}>, undefined, SurveyAssistantRequestContext, _$_mastra_core_agent0.AgentEditorConfig | undefined>;
|
|
129
|
+
//#endregion
|
|
130
|
+
export { CreateSurveyAssistantAgentOptions, SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS, SurveyAssistantObservationalMemoryOptions, createSurveyAssistantAgent, createSurveyAssistantObservationalMemoryOptions, surveyAssistantThreadAttachmentProcessor };
|
|
131
|
+
//# sourceMappingURL=server-agent.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-agent.d.mts","names":[],"sources":["../src/server/agent.ts"],"mappings":";;;;;;;;;cAuBa,wCAAA,EAA0C,cAAA;AAAA,KAuNlD,0BAAA,GAA6B,WAAA,QACzB,yBAAA,SACA,oBAAA,aAEP,6BAAA;AAAA,KAGG,4BAAA,GAA+B,WAAA,CAClC,WAAA,CAAY,qBAAA,QAA6B,MAAA;AAAA,KAyC/B,yCAAA,GAA4C,OAAA,CACtD,4BAAA;AAAA,KAIG,8CAAA,GAAiD,OAAA,CACpD,IAAA,CAAK,yCAAA;EAEL,KAAA,EAAO,WAAA,CAAY,yCAAA;AAAA;AAAA,cAGR,8CAAA;EAAA;;;;cAMA,+CAAA;EAAmD,KAAA;EAAA,WAAA;EAAA,UAAA;EAAA,GAAA;AAAA,GAK7D,8CAAA,KAAiD,yCAAA;AAAA,UAkCnC,iCAAA;EACf,KAAA,EAAO,0BAAA;EACP,MAAA,GAAS,0BAAA;EACT,mBAAA,GAAsB,yCAAA;AAAA;AAAA,cAGX,0BAAA;EAA8B,MAAA;EAAA,KAAA;EAAA;AAAA,GAIxC,iCAAA,KAAiC,KAAA,2BAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAAA,qBAAA,CAAA,oBAAA"}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { a as getDeterministicCreateItemTypes } from "./capabilities-B6tvE7fK.mjs";
|
|
2
|
+
import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CFUWrRtl.mjs";
|
|
3
|
+
import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-Hz2p7vyv.mjs";
|
|
4
|
+
import { Agent } from "@mastra/core/agent";
|
|
5
|
+
import { Memory } from "@mastra/memory";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
//#region src/server/agent.ts
|
|
8
|
+
const [INSPECT_TOOL_NAME, CHANGE_TOOL_NAME, EXPRESSION_TOOL_NAME, AUTHORING_REFERENCE_TOOL_NAME, ATTACHMENT_TOOL_NAME, AUDIT_TOOL_NAME, ASSET_TOOL_NAME] = SURVEY_ASSISTANT_TOOL_IDS;
|
|
9
|
+
const surveyAssistantThreadAttachmentProcessor = {
|
|
10
|
+
id: "survey-assistant-thread-attachments",
|
|
11
|
+
processLLMRequest({ prompt, requestContext }) {
|
|
12
|
+
const surveyRequestContext = requestContext;
|
|
13
|
+
const attachments = surveyRequestContext?.get("modelAttachments") ?? surveyRequestContext?.get("attachmentAccess")?.selectedAttachments;
|
|
14
|
+
let userIndex = -1;
|
|
15
|
+
for (let index = prompt.length - 1; index >= 0; index -= 1) if (prompt[index]?.role === "user") {
|
|
16
|
+
userIndex = index;
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
if (userIndex < 0) return;
|
|
20
|
+
const userMessage = prompt[userIndex];
|
|
21
|
+
if (!userMessage || userMessage.role !== "user") return;
|
|
22
|
+
let normalizedCurrentFile = false;
|
|
23
|
+
const currentContent = userMessage.content.map((part) => {
|
|
24
|
+
if (part.type !== "file" || typeof part.data !== "string") return part;
|
|
25
|
+
const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);
|
|
26
|
+
if (!match?.[1]) return part;
|
|
27
|
+
normalizedCurrentFile = true;
|
|
28
|
+
return {
|
|
29
|
+
...part,
|
|
30
|
+
data: match[1]
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
const currentFileKeys = new Set(currentContent.flatMap((part) => part.type === "file" && typeof part.data === "string" ? [`${part.mediaType}\u0000${createHash("sha256").update(part.data).digest("hex")}`] : []));
|
|
34
|
+
const attachmentsToAdd = (attachments ?? []).filter((attachment) => !currentFileKeys.has(`${attachment.mediaType}\u0000${attachment.contentHash}`));
|
|
35
|
+
if (!normalizedCurrentFile && attachmentsToAdd.length === 0) return;
|
|
36
|
+
const nextPrompt = [...prompt];
|
|
37
|
+
nextPrompt[userIndex] = {
|
|
38
|
+
...userMessage,
|
|
39
|
+
content: [...attachmentsToAdd.map((attachment) => ({
|
|
40
|
+
type: "file",
|
|
41
|
+
filename: attachment.filename,
|
|
42
|
+
mediaType: attachment.mediaType,
|
|
43
|
+
data: attachment.data
|
|
44
|
+
})), ...currentContent]
|
|
45
|
+
};
|
|
46
|
+
return { prompt: nextPrompt };
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const formatCurrentEditorContext = (snapshot) => {
|
|
50
|
+
if (!snapshot) return ["No live editor snapshot was provided with this turn.", "If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request."].join(" ");
|
|
51
|
+
const selectedItem = snapshot.ui.selectedItemId ?? "none";
|
|
52
|
+
const recentItems = snapshot.ui.recentItemIds?.join(", ") ?? "none";
|
|
53
|
+
const highlights = snapshot.ui.highlights?.map((entry) => entry.label ?? entry.itemId ?? entry.componentId ?? entry.kind).join(", ") ?? "none";
|
|
54
|
+
const history = snapshot.ui.history;
|
|
55
|
+
const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);
|
|
56
|
+
const surveyKey = snapshot.inspection.surveyKey ?? "not set";
|
|
57
|
+
const locales = snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(", ") : "none";
|
|
58
|
+
const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);
|
|
59
|
+
const creatableItemTypes = deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(", ") : "none";
|
|
60
|
+
const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);
|
|
61
|
+
const rootItemDescription = rootItem ? `${rootItem.fullKey} (id=${rootItem.itemId}, key=${rootItem.key})` : "not found in the inspection outline";
|
|
62
|
+
const itemTypeDetails = snapshot.capabilities.itemTypes.length > 0 ? snapshot.capabilities.itemTypes.map((entry) => {
|
|
63
|
+
const visibleContentKeys = entry.contentSurfaces.filter((surface) => !surface.pattern).map((surface) => surface.key);
|
|
64
|
+
const primaryContentKey = entry.contentSurfaces.find((surface) => surface.role === "primary")?.key;
|
|
65
|
+
const dynamicContentKeyPatterns = entry.contentSurfaces.filter((surface) => surface.pattern).map((surface) => surface.key);
|
|
66
|
+
const details = [[
|
|
67
|
+
primaryContentKey ? `primary=${primaryContentKey}` : void 0,
|
|
68
|
+
visibleContentKeys.length > 0 ? `visible=${visibleContentKeys.join("|")}` : void 0,
|
|
69
|
+
dynamicContentKeyPatterns.length > 0 ? `dynamic=${dynamicContentKeyPatterns.join("|")}` : void 0
|
|
70
|
+
].filter((value) => Boolean(value)).join("; "), [
|
|
71
|
+
`create=${entry.create}`,
|
|
72
|
+
entry.supportedOperations.length ? `operations=${entry.supportedOperations.join("|")}` : void 0,
|
|
73
|
+
entry.referenceTopics?.length ? `references=${entry.referenceTopics.join("|")}` : void 0,
|
|
74
|
+
entry.authoring?.configSummary ? `config=${entry.authoring.configSummary}` : void 0
|
|
75
|
+
].filter((value) => Boolean(value)).join("; ")].filter(Boolean).join("; ");
|
|
76
|
+
return details ? `${entry.itemType} (${details})` : entry.itemType;
|
|
77
|
+
}).join(", ") : "none";
|
|
78
|
+
return [
|
|
79
|
+
"Use this live editor snapshot as the authoritative current survey state for this turn.",
|
|
80
|
+
`Only a derived snapshot header is included here. Use it directly for revision, content hash, current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. The authoritative raw survey remains available to inspection tools in request context.`,
|
|
81
|
+
`Snapshot revision: ${snapshot.version.revision}`,
|
|
82
|
+
`Content hash: ${snapshot.version.contentHash}`,
|
|
83
|
+
`Current view: ${snapshot.ui.view}`,
|
|
84
|
+
`Selected item id: ${selectedItem}`,
|
|
85
|
+
`Recent item ids: ${recentItems}`,
|
|
86
|
+
`Active UI surface: ${snapshot.ui.activeSurface ?? "not provided"}`,
|
|
87
|
+
`Open UI panels: ${snapshot.ui.openPanels?.join(", ") ?? "not provided"}`,
|
|
88
|
+
`Highlighted UI targets: ${highlights}`,
|
|
89
|
+
`History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? "not available"}` : "not provided"}`,
|
|
90
|
+
`Selected locale: ${snapshot.ui.selectedLocale}`,
|
|
91
|
+
`Survey key: ${surveyKey}`,
|
|
92
|
+
`Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,
|
|
93
|
+
`Survey locales: ${locales}`,
|
|
94
|
+
`Survey item count: ${snapshot.inspection.itemCount}`,
|
|
95
|
+
`Deterministically creatable item types: ${creatableItemTypes}`,
|
|
96
|
+
`Installed item capabilities: ${itemTypeDetails}`
|
|
97
|
+
].filter((line) => Boolean(line)).join("\n");
|
|
98
|
+
};
|
|
99
|
+
const buildInstructions = ({ requestContext }) => {
|
|
100
|
+
const snapshot = requestContext.get("engineContext");
|
|
101
|
+
const attachmentAccess = requestContext.get("attachmentAccess");
|
|
102
|
+
const attachmentManifest = attachmentAccess?.documents.length ? attachmentAccess.documents.map((document) => JSON.stringify({
|
|
103
|
+
id: document.id,
|
|
104
|
+
filename: document.name,
|
|
105
|
+
mediaType: document.mediaType,
|
|
106
|
+
attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id) ? "current-message-context" : "stored"
|
|
107
|
+
})).join("\n") : "none";
|
|
108
|
+
return [
|
|
109
|
+
"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.",
|
|
110
|
+
"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.",
|
|
111
|
+
"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.",
|
|
112
|
+
"Authority order: the current request snapshot and inspection tools define live survey state; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.",
|
|
113
|
+
"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.",
|
|
114
|
+
"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.",
|
|
115
|
+
`Use ${INSPECT_TOOL_NAME} to inspect current context, UI context/highlights, recent editor history, search, item details, image assets, complete paged outlines, response slots, and exact raw JSON paths. 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 snapshot can resolve it. History explains recent actions but the current snapshot remains authoritative.`,
|
|
116
|
+
`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. Load survey-quality before giving a substantive questionnaire-quality critique.`,
|
|
117
|
+
`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.`,
|
|
118
|
+
`Use ${CHANGE_TOOL_NAME} for ordinary mutations and ${EXPRESSION_TOOL_NAME} for expressions on items already present in the immutable snapshot. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,
|
|
119
|
+
"The typed survey_change operations cover item creation/removal/movement/reordering; item keys, labels, colors, translations, and config; choice options; form groups and fields; embedded forms; survey metadata, pagination, locales, and translations; and image assets. Load assistant-operations for canonical shapes. Use survey-json-patch only for an inspected field not covered by a typed operation.",
|
|
120
|
+
"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.",
|
|
121
|
+
"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.",
|
|
122
|
+
"Use update-placed-image only for an image already embedded in rich text in the immutable snapshot. 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, put the complete richText value with the image block directly in create-item.translations[].content; never create placeholder text and try to update the new placement later. Do not use image asset metadata when the user asked to change one placed image.",
|
|
123
|
+
"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.",
|
|
124
|
+
"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.",
|
|
125
|
+
"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.",
|
|
126
|
+
"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.",
|
|
127
|
+
"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.",
|
|
128
|
+
"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.",
|
|
129
|
+
"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. Load embedded-forms, inspect the exact choice option and survey-root raw path, and include the embedded form config plus every required field label, placeholder, option, and validation-message translation in one raw patch proposal.",
|
|
130
|
+
"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.",
|
|
131
|
+
"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.",
|
|
132
|
+
"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.",
|
|
133
|
+
`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.`,
|
|
134
|
+
`Use ${ASSET_TOOL_NAME} to import an attached image into survey assets without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. Current-message images are already model context but still have document ids for explicit asset import. When the user asks to create a new item containing an attached image: first import it, then make exactly one ${CHANGE_TOOL_NAME} call with continuationMode "append" whose create-item translation contains the asset image block from the start. 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; do not split dependent deletions across ${CHANGE_TOOL_NAME} and ${ASSET_TOOL_NAME}. Never import a screenshot or other image merely because it is attached; do so only when the user asks to use it as survey content.`,
|
|
135
|
+
"For branching, conditions, expression validations, prefills, and template values on existing state, use survey_expression and exact inspected response refs/value types. For newly created dependent items, embed expressions directly in the same survey_change creation proposal.",
|
|
136
|
+
"Treat every turn snapshot as immutable. Do not inspect or mutate an id created earlier in the same turn through a later tool call; put dependent creations and embedded expressions in one bounded change proposal in dependency order.",
|
|
137
|
+
`Prefer one mutation-preparation call for an ordinary request. Omit continuationMode only on the first mutation call in a response. Every later ${CHANGE_TOOL_NAME} or prepare-mode ${EXPRESSION_TOOL_NAME} call must use "append" for independent additional work or "replace" for a complete correction that discards active candidates.`,
|
|
138
|
+
`A validated ${CHANGE_TOOL_NAME} or prepare-mode ${EXPRESSION_TOOL_NAME} result is a candidate, not proof of application. The successful turn-final event alone authorizes final candidate ids. Any rejected mutation blocks the whole turn until a complete corrected candidate uses continuationMode "replace". Never obtain validation by dropping requested behavior.`,
|
|
139
|
+
"When a proposal is rejected, use its concrete issues and target summary to correct the full request once. For an unfamiliar operation or raw shape, load assistant-operations and inspect the exact raw state before retrying. If a complete request exceeds the operation limit, replace it with the first complete bounded chunk and append later independent chunks.",
|
|
140
|
+
"Before answering, reconcile every requested target against the final validated candidates. Never claim rejected, superseded, missing, partial, or failed work was completed. If a request remains incomplete, correct it once or state the exact remaining work.",
|
|
141
|
+
"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.",
|
|
142
|
+
"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.",
|
|
143
|
+
"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.",
|
|
144
|
+
`Attachment document ids available for explicit loading or asset import:\n${attachmentManifest}`,
|
|
145
|
+
formatCurrentEditorContext(snapshot)
|
|
146
|
+
].join("\n\n");
|
|
147
|
+
};
|
|
148
|
+
const isInitialMessageRecall = (inputData) => {
|
|
149
|
+
if (!inputData || typeof inputData !== "object" || Array.isArray(inputData)) return false;
|
|
150
|
+
const input = inputData;
|
|
151
|
+
const mode = input.mode;
|
|
152
|
+
const hasCursor = typeof input.cursor === "string" && input.cursor.length > 0;
|
|
153
|
+
const hasThreadId = typeof input.threadId === "string" && input.threadId.length > 0;
|
|
154
|
+
return (mode === void 0 || mode === "messages") && !hasCursor && !hasThreadId;
|
|
155
|
+
};
|
|
156
|
+
var ThreadScopedSurveyAssistantMemory = class extends Memory {
|
|
157
|
+
listTools(config) {
|
|
158
|
+
const tools = super.listTools(config);
|
|
159
|
+
const recall = tools.recall;
|
|
160
|
+
if (!recall?.execute) return tools;
|
|
161
|
+
const executeRecall = recall.execute;
|
|
162
|
+
return {
|
|
163
|
+
...tools,
|
|
164
|
+
recall: {
|
|
165
|
+
...recall,
|
|
166
|
+
execute: async (inputData, context) => {
|
|
167
|
+
if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);
|
|
168
|
+
const threadId = context.agent?.threadId;
|
|
169
|
+
return executeRecall(threadId ? {
|
|
170
|
+
...inputData,
|
|
171
|
+
threadId
|
|
172
|
+
} : inputData, context);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {
|
|
179
|
+
messageTokens: 48e3,
|
|
180
|
+
observationTokens: 8e4,
|
|
181
|
+
previousObserverTokens: 24e3
|
|
182
|
+
};
|
|
183
|
+
const createSurveyAssistantObservationalMemoryOptions = ({ model, observation, reflection, ...overrides }) => ({
|
|
184
|
+
model,
|
|
185
|
+
scope: "thread",
|
|
186
|
+
activateAfterIdle: false,
|
|
187
|
+
activateOnProviderChange: true,
|
|
188
|
+
retrieval: { scope: "thread" },
|
|
189
|
+
shareTokenBudget: false,
|
|
190
|
+
temporalMarkers: false,
|
|
191
|
+
...overrides,
|
|
192
|
+
observation: {
|
|
193
|
+
messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,
|
|
194
|
+
bufferTokens: .2,
|
|
195
|
+
bufferActivation: .75,
|
|
196
|
+
blockAfter: 1.5,
|
|
197
|
+
bufferOnIdle: false,
|
|
198
|
+
previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,
|
|
199
|
+
threadTitle: true,
|
|
200
|
+
observeAttachments: false,
|
|
201
|
+
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.",
|
|
202
|
+
...observation
|
|
203
|
+
},
|
|
204
|
+
reflection: {
|
|
205
|
+
observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,
|
|
206
|
+
bufferActivation: .5,
|
|
207
|
+
blockAfter: 1.5,
|
|
208
|
+
activateAfterIdle: false,
|
|
209
|
+
activateOnProviderChange: true,
|
|
210
|
+
instruction: "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.",
|
|
211
|
+
...reflection
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
const createSurveyAssistantAgent = ({ memory, model, observationalMemory }) => new Agent({
|
|
215
|
+
id: SURVEY_ASSISTANT_AGENT_ID,
|
|
216
|
+
name: "Survey Assistant",
|
|
217
|
+
instructions: buildInstructions,
|
|
218
|
+
model,
|
|
219
|
+
tools: surveyAssistantTools,
|
|
220
|
+
memory: memory ?? new ThreadScopedSurveyAssistantMemory({ options: {
|
|
221
|
+
lastMessages: false,
|
|
222
|
+
observationalMemory: observationalMemory === false ? false : observationalMemory ?? createSurveyAssistantObservationalMemoryOptions({ model })
|
|
223
|
+
} }),
|
|
224
|
+
inputProcessors: [surveyAssistantThreadAttachmentProcessor]
|
|
225
|
+
});
|
|
226
|
+
//#endregion
|
|
227
|
+
export { SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS, createSurveyAssistantAgent, createSurveyAssistantObservationalMemoryOptions, surveyAssistantThreadAttachmentProcessor };
|
|
228
|
+
|
|
229
|
+
//# sourceMappingURL=server-agent.mjs.map
|
|
@@ -0,0 +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 recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) => entry.label ?? entry.itemId ?? entry.componentId ?? entry.kind)\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 visibleContentKeys = entry.contentSurfaces\n .filter((surface) => !surface.pattern)\n .map((surface) => surface.key);\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const dynamicContentKeyPatterns = entry.contentSurfaces\n .filter((surface) => surface.pattern)\n .map((surface) => surface.key);\n const contentKeys = [\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n visibleContentKeys.length > 0 ? `visible=${visibleContentKeys.join(\"|\")}` : undefined,\n dynamicContentKeyPatterns.length > 0\n ? `dynamic=${dynamicContentKeyPatterns.join(\"|\")}`\n : undefined,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n\n const capabilityDetails = [\n `create=${entry.create}`,\n entry.supportedOperations.length\n ? `operations=${entry.supportedOperations.join(\"|\")}`\n : undefined,\n entry.referenceTopics?.length\n ? `references=${entry.referenceTopics.join(\"|\")}`\n : undefined,\n entry.authoring?.configSummary\n ? `config=${entry.authoring.configSummary}`\n : undefined,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n\n const details = [contentKeys, capabilityDetails].filter(Boolean).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 revision, content hash, current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. The authoritative raw survey remains available to inspection tools in request context.`,\n `Snapshot revision: ${snapshot.version.revision}`,\n `Content hash: ${snapshot.version.contentHash}`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\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: ${snapshot.inspection.itemCount}`,\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities: ${itemTypeDetails}`,\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 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 current request snapshot and inspection tools define live survey state; 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 \"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 context, UI context/highlights, recent editor history, search, item details, image assets, complete paged outlines, response slots, and exact raw JSON paths. 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 snapshot can resolve it. History explains recent actions but the current snapshot remains authoritative.`,\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. 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 ordinary mutations and ${EXPRESSION_TOOL_NAME} for expressions on items already present in the immutable snapshot. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n \"The typed survey_change operations cover item creation/removal/movement/reordering; item keys, labels, colors, translations, and config; choice options; form groups and fields; embedded forms; survey metadata, pagination, locales, and translations; and image assets. Load assistant-operations for canonical shapes. Use survey-json-patch only for an inspected field not covered by a typed operation.\",\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 \"Use update-placed-image only for an image already embedded in rich text in the immutable snapshot. 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, put the complete richText value with the image block directly in create-item.translations[].content; never create placeholder text and try to update the new placement later. 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, inspect the exact choice option and survey-root raw path, and include the embedded form config plus every required field label, placeholder, option, and validation-message translation in one raw patch proposal.\",\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 survey assets without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. Current-message images are already model context but still have document ids for explicit asset import. When the user asks to create a new item containing an attached image: first import it, then make exactly one ${CHANGE_TOOL_NAME} call with continuationMode \"append\" whose create-item translation contains the asset image block from the start. 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; do not split dependent deletions across ${CHANGE_TOOL_NAME} and ${ASSET_TOOL_NAME}. Never import a screenshot or other 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 on existing state, use survey_expression and exact inspected response refs/value types. For newly created dependent items, embed expressions directly in the same survey_change creation proposal.\",\n \"Treat every turn snapshot as immutable. Do not inspect or mutate an id created earlier in the same turn through a later tool call; put dependent creations and embedded expressions in one bounded change proposal in dependency order.\",\n `Prefer one mutation-preparation call for an ordinary request. Omit continuationMode only on the first mutation call in a response. Every later ${CHANGE_TOOL_NAME} or prepare-mode ${EXPRESSION_TOOL_NAME} call must use \"append\" for independent additional work or \"replace\" for a complete correction that discards active candidates.`,\n `A validated ${CHANGE_TOOL_NAME} or prepare-mode ${EXPRESSION_TOOL_NAME} result is a candidate, not proof of application. The successful turn-final event alone authorizes final candidate ids. Any rejected mutation blocks the whole turn until a complete corrected candidate uses continuationMode \"replace\". Never obtain validation by dropping requested behavior.`,\n \"When a proposal is rejected, use its concrete issues and target summary to correct the full request once. For an unfamiliar operation or raw shape, load assistant-operations and inspect the exact raw state before retrying. If a complete request exceeds the operation limit, replace it with the first complete bounded chunk and append later independent chunks.\",\n \"Before answering, reconcile every requested target against the final validated candidates. Never claim rejected, superseded, 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 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,IAC7C,sBAAsB,IAAI,mBAAmB,EAAE;EAEjD,IAAI,YAAY;AAChB,OAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SA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AAW,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"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { S as SurveyAssistantModelCatalog } from "./index-TFtvBiSQ.mjs";
|
|
2
|
+
import { Ft as SurveyAssistantCapabilitySet } from "./index-CUqbBjkc.mjs";
|
|
3
|
+
import { a as SurveyAssistantThreadDocumentRepository } from "./thread-documents-DamIq9Od.mjs";
|
|
4
|
+
import { SurveyAssistantObservationalMemoryOptions, createSurveyAssistantAgent } from "./server-agent.mjs";
|
|
5
|
+
import { c as SurveyAssistantAuthorize, f as SurveyAssistantResolveModel, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions } from "./thread-handlers-DpynUc64.mjs";
|
|
6
|
+
import { CreateSurveyAssistantTaskHandlerOptions, createSurveyAssistantTaskAgent } from "./server-tasks.mjs";
|
|
7
|
+
import { AgentExecutionOptions } from "@mastra/core/agent";
|
|
8
|
+
import { AzureOpenAIGatewayConfig, MastraModelGatewayInterface } from "@mastra/core/llm";
|
|
9
|
+
import { Mastra } from "@mastra/core/mastra";
|
|
10
|
+
|
|
11
|
+
//#region src/server/runtime-config.d.ts
|
|
12
|
+
type SurveyAssistantProvider = "azure-openai" | "mistral" | "openai";
|
|
13
|
+
type SurveyAssistantProviderOptionsKey = "azure" | "mistral" | "openai";
|
|
14
|
+
interface SurveyAssistantAzureConfig {
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
apiVersion: string;
|
|
17
|
+
discoverModels: boolean;
|
|
18
|
+
management?: AzureOpenAIGatewayConfig["management"];
|
|
19
|
+
resourceName?: string;
|
|
20
|
+
}
|
|
21
|
+
interface SurveyAssistantExecutionConfig {
|
|
22
|
+
maxConcurrentRequests: number;
|
|
23
|
+
maxSteps: number;
|
|
24
|
+
providerOptions?: AgentExecutionOptions["providerOptions"];
|
|
25
|
+
sendReasoning: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface SurveyAssistantRuntimeConfig {
|
|
28
|
+
azure?: SurveyAssistantAzureConfig;
|
|
29
|
+
defaultModelId: string;
|
|
30
|
+
enabled: boolean;
|
|
31
|
+
modelCatalogTtlMs: number;
|
|
32
|
+
modelIds: string[];
|
|
33
|
+
observationalMemory: SurveyAssistantObservationalMemoryOptions | false;
|
|
34
|
+
provider: SurveyAssistantProvider;
|
|
35
|
+
readinessError: string | null;
|
|
36
|
+
execution: SurveyAssistantExecutionConfig;
|
|
37
|
+
}
|
|
38
|
+
interface ParseSurveyAssistantEnvironmentOptions {
|
|
39
|
+
defaultMistralModel?: string;
|
|
40
|
+
defaultOpenAIModel?: string;
|
|
41
|
+
defaultProvider?: SurveyAssistantProvider;
|
|
42
|
+
requireExperimentalIdentityOptIn?: boolean;
|
|
43
|
+
requireStorage?: boolean;
|
|
44
|
+
}
|
|
45
|
+
type Environment = Record<string, string | undefined>;
|
|
46
|
+
declare const resolveSurveyAssistantProviderOptionsKey: (provider: SurveyAssistantProvider) => SurveyAssistantProviderOptionsKey;
|
|
47
|
+
declare const parseSurveyAssistantEnvironment: (env: Environment, {
|
|
48
|
+
defaultMistralModel,
|
|
49
|
+
defaultOpenAIModel,
|
|
50
|
+
defaultProvider,
|
|
51
|
+
requireExperimentalIdentityOptIn,
|
|
52
|
+
requireStorage
|
|
53
|
+
}?: ParseSurveyAssistantEnvironmentOptions) => SurveyAssistantRuntimeConfig;
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/server/runtime.d.ts
|
|
56
|
+
interface SurveyAssistantModelRouter {
|
|
57
|
+
defaultModel: string;
|
|
58
|
+
gateways?: Record<string, MastraModelGatewayInterface>;
|
|
59
|
+
getCatalog(options?: {
|
|
60
|
+
refresh?: boolean;
|
|
61
|
+
}): Promise<SurveyAssistantModelCatalog>;
|
|
62
|
+
providerName: string;
|
|
63
|
+
providerOptions?: AgentExecutionOptions["providerOptions"];
|
|
64
|
+
resolveModel: SurveyAssistantResolveModel;
|
|
65
|
+
}
|
|
66
|
+
declare const createSurveyAssistantModelRouter: (config: SurveyAssistantRuntimeConfig) => SurveyAssistantModelRouter;
|
|
67
|
+
interface SurveyAssistantRuntimeComponents {
|
|
68
|
+
agents: Record<string, ReturnType<typeof createSurveyAssistantAgent> | ReturnType<typeof createSurveyAssistantTaskAgent>>;
|
|
69
|
+
gateways?: Record<string, MastraModelGatewayInterface>;
|
|
70
|
+
modelRouter: SurveyAssistantModelRouter;
|
|
71
|
+
}
|
|
72
|
+
declare const createSurveyAssistantRuntimeComponents: (config: SurveyAssistantRuntimeConfig) => SurveyAssistantRuntimeComponents;
|
|
73
|
+
type ChatHandlerOverrides = Partial<Omit<SurveyAssistantChatHandlerOptions, "authorize" | "mastra" | "providerName" | "providerOptions" | "resolveModel">>;
|
|
74
|
+
interface CreateSurveyAssistantRuntimeHandlersOptions {
|
|
75
|
+
authorize: {
|
|
76
|
+
chat: SurveyAssistantAuthorize;
|
|
77
|
+
model?: (request: Request) => unknown | Promise<unknown>;
|
|
78
|
+
task: CreateSurveyAssistantTaskHandlerOptions["authorize"];
|
|
79
|
+
thread: CreateSurveyAssistantThreadHandlersOptions["authorize"];
|
|
80
|
+
};
|
|
81
|
+
chat?: ChatHandlerOverrides;
|
|
82
|
+
config: SurveyAssistantRuntimeConfig;
|
|
83
|
+
mastra: Mastra | (() => Mastra | Promise<Mastra>);
|
|
84
|
+
modelRouter: SurveyAssistantModelRouter;
|
|
85
|
+
threadDocuments?: SurveyAssistantThreadDocumentRepository;
|
|
86
|
+
}
|
|
87
|
+
type CreateConfiguredSurveyAssistantRuntimeHandlersOptions = Omit<CreateSurveyAssistantRuntimeHandlersOptions, "config" | "modelRouter">;
|
|
88
|
+
declare const createSurveyAssistantRuntimeHandlers: ({
|
|
89
|
+
authorize,
|
|
90
|
+
chat,
|
|
91
|
+
config,
|
|
92
|
+
mastra,
|
|
93
|
+
modelRouter,
|
|
94
|
+
threadDocuments
|
|
95
|
+
}: CreateSurveyAssistantRuntimeHandlersOptions) => {
|
|
96
|
+
chat: (request: Request) => Promise<Response>;
|
|
97
|
+
models: (request: Request) => Promise<Response>;
|
|
98
|
+
task: (request: Request) => Promise<Response>;
|
|
99
|
+
threads: {
|
|
100
|
+
create: (request: Request) => Promise<Response>;
|
|
101
|
+
delete: (request: Request, threadId: string) => Promise<Response>;
|
|
102
|
+
list: (request: Request) => Promise<Response>;
|
|
103
|
+
read: (request: Request, threadId: string) => Promise<Response>;
|
|
104
|
+
update: (request: Request, threadId: string) => Promise<Response>;
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
interface SurveyAssistantRuntime extends SurveyAssistantRuntimeComponents {
|
|
108
|
+
config: SurveyAssistantRuntimeConfig;
|
|
109
|
+
createHandlers(options: CreateConfiguredSurveyAssistantRuntimeHandlersOptions): ReturnType<typeof createSurveyAssistantRuntimeHandlers>;
|
|
110
|
+
}
|
|
111
|
+
interface CreateSurveyAssistantRuntimeOptions {
|
|
112
|
+
/** Trusted server-side capabilities for custom registry item types. */
|
|
113
|
+
trustedCapabilities?: SurveyAssistantCapabilitySet;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Creates the reusable assistant runtime without hiding Mastra from the host.
|
|
117
|
+
* Register `agents` and `gateways` in the host's standard Mastra instance, then
|
|
118
|
+
* call `createHandlers` with that instance and host authorization policy.
|
|
119
|
+
*/
|
|
120
|
+
declare const createSurveyAssistantRuntime: (config: SurveyAssistantRuntimeConfig, runtimeOptions?: CreateSurveyAssistantRuntimeOptions) => SurveyAssistantRuntime;
|
|
121
|
+
//#endregion
|
|
122
|
+
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 };
|
|
123
|
+
//# sourceMappingURL=server-runtime.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-runtime.d.mts","names":[],"sources":["../src/server/runtime-config.ts","../src/server/runtime.ts"],"mappings":";;;;;;;;;;;KAQY,uBAAA;AAAA,KACA,iCAAA;AAAA,UAEK,0BAAA;EACf,MAAA;EACA,UAAA;EACA,cAAA;EACA,UAAA,GAAa,wBAAA;E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