@case-framework/survey-assistant 0.7.0 → 0.8.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 +58 -3
- package/dist/{attachments-B0hg3vpT.mjs → attachments-BuNni5vB.mjs} +1 -1
- package/dist/{attachments-B0hg3vpT.mjs.map → attachments-BuNni5vB.mjs.map} +1 -1
- package/dist/{authoring-references-BJQ_1nMX.mjs → authoring-references-DbuOKerg.mjs} +12 -3
- package/dist/authoring-references-DbuOKerg.mjs.map +1 -0
- package/dist/{capabilities-DVTfogjv.d.mts → capabilities-CmeeAjEc.d.mts} +3 -4
- package/dist/capabilities-CmeeAjEc.d.mts.map +1 -0
- package/dist/{capabilities-1KNnNO1_.mjs → capabilities-DCMA71PP.mjs} +4 -19
- package/dist/capabilities-DCMA71PP.mjs.map +1 -0
- package/dist/capabilities-default.d.mts +13 -12
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +2 -411
- package/dist/{constants-Be91Gay9.d.mts → constants-B6HzpEsx.d.mts} +7 -28
- package/dist/constants-B6HzpEsx.d.mts.map +1 -0
- package/dist/{constants-0UHGFcRJ.mjs → constants-Ct-vv9cu.mjs} +1 -1
- package/dist/{constants-0UHGFcRJ.mjs.map → constants-Ct-vv9cu.mjs.map} +1 -1
- package/dist/controller-proxy-D7uQfm5f.d.mts +65 -0
- package/dist/controller-proxy-D7uQfm5f.d.mts.map +1 -0
- package/dist/{controller-proxy-BH05e-C2.mjs → controller-proxy-DEeFl9IA.mjs} +10 -20
- package/dist/controller-proxy-DEeFl9IA.mjs.map +1 -0
- package/dist/default-fhSon2RM.mjs +760 -0
- package/dist/default-fhSon2RM.mjs.map +1 -0
- package/dist/{digest-SJmoYVaK.d.mts → digest-C39WyAWG.d.mts} +2 -3
- package/dist/digest-C39WyAWG.d.mts.map +1 -0
- package/dist/digest.d.mts +1 -1
- package/dist/digest.mjs.map +1 -1
- package/dist/{engine-Bo85Oyj0.mjs → engine-nXoCWYpQ.mjs} +755 -590
- package/dist/engine-nXoCWYpQ.mjs.map +1 -0
- package/dist/engine.d.mts +3 -3
- package/dist/engine.mjs +3 -3
- package/dist/{fair-guidance-CRYCRxQm.mjs → fair-guidance-BmO4PswW.mjs} +1 -1
- package/dist/{fair-guidance-CRYCRxQm.mjs.map → fair-guidance-BmO4PswW.mjs.map} +1 -1
- package/dist/{index-Tnqv-yKW.d.mts → index-Ciq7vHIs.d.mts} +80 -141
- package/dist/index-Ciq7vHIs.d.mts.map +1 -0
- package/dist/{index-nhrgbgO5.d.mts → index-D7wT6P3t.d.mts} +277 -60
- package/dist/index-D7wT6P3t.d.mts.map +1 -0
- package/dist/{index-l_EK4yK7.d.mts → index-WB5kfnz0.d.mts} +15 -71
- package/dist/index-WB5kfnz0.d.mts.map +1 -0
- package/dist/{index-x0qprHgK.d.mts → index-r5riv4md.d.mts} +33 -24
- package/dist/index-r5riv4md.d.mts.map +1 -0
- package/dist/{lifecycle-Bx0aq_4S.d.mts → lifecycle-Dm8u7QFh.d.mts} +34 -18
- package/dist/lifecycle-Dm8u7QFh.d.mts.map +1 -0
- package/dist/{memory-thread-repository-KWHQWFEW.mjs → memory-thread-repository-DAnOGIB3.mjs} +51 -27
- package/dist/memory-thread-repository-DAnOGIB3.mjs.map +1 -0
- package/dist/{protocol-BhzQbx81.mjs → protocol-CF4Bh_Ch.mjs} +118 -36
- package/dist/protocol-CF4Bh_Ch.mjs.map +1 -0
- package/dist/protocol.d.mts +4 -4
- package/dist/protocol.mjs +3 -3
- package/dist/{react-B3ybjJ-X.mjs → react-C_GY-Fsc.mjs} +146 -39
- package/dist/react-C_GY-Fsc.mjs.map +1 -0
- package/dist/react-integration.d.mts +2 -2
- package/dist/react-integration.mjs +2 -2
- package/dist/react.d.mts +3 -3
- package/dist/react.mjs +3 -3
- package/dist/references/assistant-operations.md +100 -31
- package/dist/references/core-rules.md +6 -3
- package/dist/references/embedded-forms.md +34 -14
- package/dist/references/expressions.md +220 -58
- package/dist/references/fair-by-design.md +9 -9
- package/dist/references/item-types.md +305 -71
- package/dist/references/response-variables.md +38 -0
- package/dist/references/source-material-surveys.md +4 -3
- package/dist/references/survey-data-model.md +23 -8
- package/dist/{request-context-CG4SWijt.mjs → request-context-Dg4jSwN1.mjs} +4 -10
- package/dist/request-context-Dg4jSwN1.mjs.map +1 -0
- package/dist/{request-guardrails-TmgQtqp4.mjs → request-guardrails-C0ugBOp0.mjs} +6 -5
- package/dist/request-guardrails-C0ugBOp0.mjs.map +1 -0
- package/dist/server-agent.d.mts +37 -39
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +45 -20
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +23 -42
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +12 -12
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +2 -2
- package/dist/server-tasks.mjs +2 -313
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +13 -36
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -5
- package/dist/server.mjs.map +1 -1
- package/dist/storage-postgres.d.mts +9 -25
- package/dist/storage-postgres.d.mts.map +1 -1
- package/dist/storage-postgres.mjs +5 -4
- package/dist/storage-postgres.mjs.map +1 -1
- package/dist/{tasks-CYqrcaRO.d.mts → tasks-B9h3LPam.d.mts} +18 -34
- package/dist/tasks-B9h3LPam.d.mts.map +1 -0
- package/dist/tasks-BZEiwgxA.mjs +396 -0
- package/dist/tasks-BZEiwgxA.mjs.map +1 -0
- package/dist/thread-documents-DrHbaXqP.d.mts +119 -0
- package/dist/thread-documents-DrHbaXqP.d.mts.map +1 -0
- package/dist/{thread-handlers-DBAaU7BA.d.mts → thread-handlers-Bef0td9N.d.mts} +8 -40
- package/dist/thread-handlers-Bef0td9N.d.mts.map +1 -0
- package/dist/{tools-BvSovehT.mjs → tools-CEsv-WoO.mjs} +296 -105
- package/dist/tools-CEsv-WoO.mjs.map +1 -0
- package/dist/ui.css +1 -1
- package/dist/ui.d.mts +15 -54
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +172 -137
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +11 -1
- package/package.json +40 -35
- package/dist/authoring-references-BJQ_1nMX.mjs.map +0 -1
- package/dist/capabilities-1KNnNO1_.mjs.map +0 -1
- package/dist/capabilities-DVTfogjv.d.mts.map +0 -1
- package/dist/capabilities-default.mjs.map +0 -1
- package/dist/constants-Be91Gay9.d.mts.map +0 -1
- package/dist/controller-proxy-BH05e-C2.mjs.map +0 -1
- package/dist/controller-proxy-Bd0ZHBPF.d.mts +0 -85
- package/dist/controller-proxy-Bd0ZHBPF.d.mts.map +0 -1
- package/dist/digest-SJmoYVaK.d.mts.map +0 -1
- package/dist/engine-Bo85Oyj0.mjs.map +0 -1
- package/dist/index-Tnqv-yKW.d.mts.map +0 -1
- package/dist/index-l_EK4yK7.d.mts.map +0 -1
- package/dist/index-nhrgbgO5.d.mts.map +0 -1
- package/dist/index-x0qprHgK.d.mts.map +0 -1
- package/dist/lifecycle-Bx0aq_4S.d.mts.map +0 -1
- package/dist/memory-thread-repository-KWHQWFEW.mjs.map +0 -1
- package/dist/protocol-BhzQbx81.mjs.map +0 -1
- package/dist/react-B3ybjJ-X.mjs.map +0 -1
- package/dist/request-context-CG4SWijt.mjs.map +0 -1
- package/dist/request-guardrails-TmgQtqp4.mjs.map +0 -1
- package/dist/server-tasks.mjs.map +0 -1
- package/dist/tasks-CYqrcaRO.d.mts.map +0 -1
- package/dist/thread-documents-rmd6nyX9.d.mts +0 -107
- package/dist/thread-documents-rmd6nyX9.d.mts.map +0 -1
- package/dist/thread-handlers-DBAaU7BA.d.mts.map +0 -1
- package/dist/tools-BvSovehT.mjs.map +0 -1
package/dist/server-tasks.mjs
CHANGED
|
@@ -1,313 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { d as readSurveyAssistantRequestJson, u as SurveyAssistantRequestError } from "./request-guardrails-TmgQtqp4.mjs";
|
|
4
|
-
import { a as surveyAuthoringReferences } from "./authoring-references-BJQ_1nMX.mjs";
|
|
5
|
-
import { n as FAIR_ITEM_KEY_RULES_TEXT } from "./fair-guidance-CRYCRxQm.mjs";
|
|
6
|
-
import { z } from "zod";
|
|
7
|
-
import { RequestContext } from "@mastra/core/request-context";
|
|
8
|
-
import { Agent } from "@mastra/core/agent";
|
|
9
|
-
//#region src/server/tasks.ts
|
|
10
|
-
const createSurveyAssistantTaskAgent = ({ model }) => new Agent({
|
|
11
|
-
id: SURVEY_ASSISTANT_TASK_AGENT_ID,
|
|
12
|
-
name: "Survey Assistant Tasks",
|
|
13
|
-
instructions: "Perform the supplied bounded survey-authoring task and return only its requested structured output.",
|
|
14
|
-
model
|
|
15
|
-
});
|
|
16
|
-
const BASE_TASK_INSTRUCTIONS = [
|
|
17
|
-
"You perform one bounded CASE Survey Editor AI task and return only the requested structured result.",
|
|
18
|
-
"The supplied task context was derived from the current canonical survey document snapshot. Use it as current survey context, but do not mutate it and do not claim that any editor change was applied.",
|
|
19
|
-
"Follow the supplied CASE authoring references where relevant. Do not invent item types, locales, ids, or capabilities that are absent from the task input and context.",
|
|
20
|
-
"Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.",
|
|
21
|
-
"Be fast, don't think."
|
|
22
|
-
];
|
|
23
|
-
const runSurveyAssistantTask = async ({ agent, taskId, input, context, schema, instructions, referenceTopics = [], requestContext, providerOptions, abortSignal }) => {
|
|
24
|
-
const references = referenceTopics.map((topic) => ({
|
|
25
|
-
topic,
|
|
26
|
-
title: surveyAuthoringReferences[topic].title,
|
|
27
|
-
content: surveyAuthoringReferences[topic].content
|
|
28
|
-
}));
|
|
29
|
-
const response = await agent.generate(JSON.stringify({
|
|
30
|
-
taskId,
|
|
31
|
-
input,
|
|
32
|
-
currentSurveyContext: context
|
|
33
|
-
}), {
|
|
34
|
-
instructions: [
|
|
35
|
-
...BASE_TASK_INSTRUCTIONS,
|
|
36
|
-
...instructions,
|
|
37
|
-
...references.map((entry) => `Reference: ${entry.title}\n${entry.content}`)
|
|
38
|
-
],
|
|
39
|
-
activeTools: [],
|
|
40
|
-
inputProcessors: [],
|
|
41
|
-
maxSteps: 1,
|
|
42
|
-
structuredOutput: {
|
|
43
|
-
schema,
|
|
44
|
-
errorStrategy: "strict"
|
|
45
|
-
},
|
|
46
|
-
...requestContext ? { requestContext } : {},
|
|
47
|
-
...providerOptions ? { providerOptions } : {},
|
|
48
|
-
...abortSignal ? { abortSignal } : {}
|
|
49
|
-
});
|
|
50
|
-
return schema.parse(response.object);
|
|
51
|
-
};
|
|
52
|
-
const keySuggestionValueSchema = z.object({
|
|
53
|
-
text: z.string().min(1),
|
|
54
|
-
rationale: z.string().optional()
|
|
55
|
-
});
|
|
56
|
-
const keySuggestionCategorySchema = z.enum([
|
|
57
|
-
"survey-pattern",
|
|
58
|
-
"compact",
|
|
59
|
-
"preferred",
|
|
60
|
-
"fair"
|
|
61
|
-
]);
|
|
62
|
-
const keySuggestionSchema = z.object({
|
|
63
|
-
surveyPattern: keySuggestionValueSchema.describe("A key that follows the strongest naming and numbering pattern in the current survey."),
|
|
64
|
-
compact: keySuggestionValueSchema.extend({ text: z.string().min(2).max(5).regex(/^[A-Z][A-Z0-9]{1,4}$/).describe("A recognizable 2-5 character uppercase abbreviation.") }),
|
|
65
|
-
preferred: keySuggestionValueSchema.describe("The key the model considers clearest without a category-specific naming constraint."),
|
|
66
|
-
fair: keySuggestionValueSchema.extend({ text: z.string().min(1).max(32).regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/).describe("A FAIR-by-design lowercase snake_case variable name.") }),
|
|
67
|
-
alternatives: z.array(keySuggestionValueSchema.extend({ category: keySuggestionCategorySchema })).max(2)
|
|
68
|
-
});
|
|
69
|
-
const labelSuggestionSchema = z.object({ suggestions: z.array(z.object({ text: z.string().min(1) })) });
|
|
70
|
-
const translationsSchema = z.object({ translations: z.record(z.string(), z.record(z.string(), z.string())) });
|
|
71
|
-
const clampLimit = (value, fallback, maximum) => Math.min(Math.max(1, value ?? fallback), maximum);
|
|
72
|
-
const sanitizeCodingKey = (value) => value.trim().replace(/[.\s-]+/g, "_").replace(/[^A-Za-z0-9_]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
|
|
73
|
-
const getCodingKeyIdentity = (value) => sanitizeCodingKey(value).toLocaleLowerCase();
|
|
74
|
-
const getNumberedKeyParts = (value) => {
|
|
75
|
-
const match = /^(.+?)_(\d+)$/.exec(getCodingKeyIdentity(value));
|
|
76
|
-
return match ? {
|
|
77
|
-
stem: match[1],
|
|
78
|
-
number: Number(match[2])
|
|
79
|
-
} : void 0;
|
|
80
|
-
};
|
|
81
|
-
const isUnsupportedFocusedItemSequence = (candidate, input, context) => {
|
|
82
|
-
const candidateParts = getNumberedKeyParts(candidate);
|
|
83
|
-
const focusItem = context.focus?.item;
|
|
84
|
-
if (!candidateParts || !focusItem) return false;
|
|
85
|
-
if (![
|
|
86
|
-
input.currentKey,
|
|
87
|
-
input.draftKey,
|
|
88
|
-
focusItem.key
|
|
89
|
-
].map(getNumberedKeyParts).find((parts) => parts?.stem === candidateParts.stem && parts.number < candidateParts.number)) return false;
|
|
90
|
-
return !context.naming?.keyExamples.some((example) => {
|
|
91
|
-
const exampleParts = getNumberedKeyParts(example.key);
|
|
92
|
-
return example.itemType === focusItem.itemType && exampleParts?.stem === candidateParts.stem;
|
|
93
|
-
});
|
|
94
|
-
};
|
|
95
|
-
const invocationInstruction = (mode) => mode === "background" ? "This is a background invocation. Be efficient, but do not relax task conventions, completeness, or output quality." : "This is an explicit user invocation. Prioritize quality and useful variation.";
|
|
96
|
-
const runSurveyAssistantSuggestItemKeyTask = async (input, options) => {
|
|
97
|
-
const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);
|
|
98
|
-
const result = await runSurveyAssistantTask({
|
|
99
|
-
...options,
|
|
100
|
-
taskId: "suggest-item-key",
|
|
101
|
-
input,
|
|
102
|
-
schema: keySuggestionSchema,
|
|
103
|
-
instructions: [
|
|
104
|
-
"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.",
|
|
105
|
-
"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.",
|
|
106
|
-
"For a group or other container, treat its own descendants as the primary evidence for what the container represents. Derive a descriptive group key from those children before considering generic default container names.",
|
|
107
|
-
"The input currentKey and draftKey, plus the focused item's key and fullKey in currentSurveyContext, identify the value being replaced. They may provide topic hints, but they are not evidence of an established naming or numbering pattern.",
|
|
108
|
-
"Use only currentSurveyContext.naming.keyExamples and sibling keys from other items to infer the survey's established naming pattern. Pay particular attention to prefixes, casing, separators, numeric sequences, and zero padding.",
|
|
109
|
-
"Treat a numeric pattern as established only when at least one other survey item supports it. For example, another item Q1_APPLES can support a topic-appropriate Q2_... key, while Q1_APPLES and Q2_ORANGES support Q3_.... The focused item's current key choice_1 by itself does not support choice_2 or a numeric suffix in other suggestions.",
|
|
110
|
-
"In particular, a focused group named group_1 is a default placeholder, not a group-numbering pattern. Do not propose group_2 (or another group_N key) from it unless another group/container in currentSurveyContext.naming.keyExamples independently uses the same group_N pattern. The group's children provide semantic context, not evidence of a group-numbering pattern.",
|
|
111
|
-
"Return one surveyPattern key that follows the strongest detected local pattern. Preserve that pattern's casing and increment a clear sequence rather than copying an existing number. If no meaningful pattern exists, use a consistent descriptive key.",
|
|
112
|
-
"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.",
|
|
113
|
-
"Return one preferred key: the key you consider clearest and most useful without category-specific naming constraints, while still using only letters, digits, and underscores.",
|
|
114
|
-
`Return one fair key following these FAIR-by-design rules: ${FAIR_ITEM_KEY_RULES_TEXT}. Meaning belongs in metadata, so do not turn it into a sentence.`,
|
|
115
|
-
`You may return up to ${Math.max(0, maxSuggestions - 4)} genuinely useful alternatives when another category has more than one strong candidate. Tag each alternative with its category.`,
|
|
116
|
-
"Never repeat the same suggestion, including case-only or punctuation-only variations.",
|
|
117
|
-
"Do not return the current key, a sibling key, or a semantically unrelated abbreviation.",
|
|
118
|
-
`Return between 4 and ${maxSuggestions} distinct suggestions in total.`,
|
|
119
|
-
invocationInstruction(options.mode)
|
|
120
|
-
]
|
|
121
|
-
});
|
|
122
|
-
const excluded = new Set([input.currentKey, ...input.siblingKeys].map(getCodingKeyIdentity).filter(Boolean));
|
|
123
|
-
const seen = /* @__PURE__ */ new Set();
|
|
124
|
-
return { suggestions: [
|
|
125
|
-
{
|
|
126
|
-
...result.surveyPattern,
|
|
127
|
-
category: "survey-pattern"
|
|
128
|
-
},
|
|
129
|
-
{
|
|
130
|
-
...result.compact,
|
|
131
|
-
category: "compact"
|
|
132
|
-
},
|
|
133
|
-
{
|
|
134
|
-
...result.preferred,
|
|
135
|
-
category: "preferred"
|
|
136
|
-
},
|
|
137
|
-
{
|
|
138
|
-
...result.fair,
|
|
139
|
-
category: "fair"
|
|
140
|
-
},
|
|
141
|
-
...result.alternatives
|
|
142
|
-
].flatMap((suggestion) => {
|
|
143
|
-
const text = sanitizeCodingKey(suggestion.text);
|
|
144
|
-
const identity = getCodingKeyIdentity(text);
|
|
145
|
-
if (!text || excluded.has(identity) || seen.has(identity) || isUnsupportedFocusedItemSequence(text, input, options.context)) return [];
|
|
146
|
-
seen.add(identity);
|
|
147
|
-
return [{
|
|
148
|
-
...suggestion,
|
|
149
|
-
text
|
|
150
|
-
}];
|
|
151
|
-
}).slice(0, maxSuggestions) };
|
|
152
|
-
};
|
|
153
|
-
const runSurveyAssistantSuggestItemLabelTask = async (input, options) => {
|
|
154
|
-
const maxSuggestions = clampLimit(input.maxSuggestions, 3, 10);
|
|
155
|
-
const locale = input.locale ?? options.context.survey.selectedLocale;
|
|
156
|
-
const result = await runSurveyAssistantTask({
|
|
157
|
-
...options,
|
|
158
|
-
taskId: "suggest-item-label",
|
|
159
|
-
input,
|
|
160
|
-
schema: labelSuggestionSchema,
|
|
161
|
-
instructions: [
|
|
162
|
-
"Suggest concise editor-only item labels, not coding keys and not respondent-facing question text.",
|
|
163
|
-
"Infer the item's purpose from its type, draft label, visible content, hierarchy, siblings, and descendants.",
|
|
164
|
-
"Use currentSurveyContext.naming.labelExamples to infer established capitalization, prefixes, abbreviations, delimiters, and typical length.",
|
|
165
|
-
"If existing label examples are available, the first suggestion must follow their dominant pattern while still describing the focused item accurately. Other suggestions may offer useful concise alternatives.",
|
|
166
|
-
"Do not copy the subject matter of an unrelated example merely to imitate its style, and do not return an existing unrelated label verbatim.",
|
|
167
|
-
`Write labels in locale ${locale}.`,
|
|
168
|
-
`Return at most ${maxSuggestions} distinct, specific, human-readable suggestions.`,
|
|
169
|
-
invocationInstruction(options.mode)
|
|
170
|
-
],
|
|
171
|
-
referenceTopics: ["core-rules"]
|
|
172
|
-
});
|
|
173
|
-
const normalizeLabel = (value) => value.trim().toLocaleLowerCase();
|
|
174
|
-
const excludedLabels = new Set([normalizeLabel(input.draftLabel), ...(options.context.naming?.labelExamples ?? []).map((example) => normalizeLabel(example.label))]);
|
|
175
|
-
const seen = /* @__PURE__ */ new Set();
|
|
176
|
-
return { suggestions: result.suggestions.flatMap((suggestion) => {
|
|
177
|
-
const text = suggestion.text.trim();
|
|
178
|
-
const normalizedText = normalizeLabel(text);
|
|
179
|
-
if (!text || excludedLabels.has(normalizedText) || seen.has(normalizedText)) return [];
|
|
180
|
-
seen.add(normalizedText);
|
|
181
|
-
return [{
|
|
182
|
-
...suggestion,
|
|
183
|
-
text
|
|
184
|
-
}];
|
|
185
|
-
}).slice(0, maxSuggestions) };
|
|
186
|
-
};
|
|
187
|
-
const getProtectedTokens = (value) => value.match(/\{\{[^{}]+\}\}|\{[^{}]+\}|\$\{[^{}]+\}|%\d*\$?[a-z]/gi) ?? [];
|
|
188
|
-
const runSurveyAssistantTranslateContentTask = async (input, options) => {
|
|
189
|
-
const result = await runSurveyAssistantTask({
|
|
190
|
-
...options,
|
|
191
|
-
taskId: "translate-content",
|
|
192
|
-
input,
|
|
193
|
-
schema: translationsSchema,
|
|
194
|
-
instructions: [
|
|
195
|
-
"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.",
|
|
196
|
-
`Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(", ")}.`,
|
|
197
|
-
"Use currentSurveyContext.translation.examples as a terminology and style reference when relevant. The supplied source entries remain authoritative.",
|
|
198
|
-
"Preserve meaning, register, survey terminology, punctuation, line breaks, response semantics, placeholders, interpolation tokens, URLs, and identifiers that should not be translated.",
|
|
199
|
-
"Keep repeated terminology consistent across all entries and target locales. Do not use a neighboring translation when its meaning differs.",
|
|
200
|
-
"Return plain strings keyed first by target locale and then by the original entry id. Return every requested locale and entry exactly once.",
|
|
201
|
-
invocationInstruction(options.mode)
|
|
202
|
-
],
|
|
203
|
-
referenceTopics: ["localization"]
|
|
204
|
-
});
|
|
205
|
-
const translations = {};
|
|
206
|
-
for (const locale of input.targetLocales) {
|
|
207
|
-
const entries = result.translations[locale];
|
|
208
|
-
if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);
|
|
209
|
-
const translatedEntries = {};
|
|
210
|
-
for (const entry of input.entries) {
|
|
211
|
-
const translation = entries[entry.id];
|
|
212
|
-
if (typeof translation !== "string" || translation.trim().length === 0) throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);
|
|
213
|
-
const sourceTokens = getProtectedTokens(entry.text).sort();
|
|
214
|
-
const translatedTokens = getProtectedTokens(translation).sort();
|
|
215
|
-
if (sourceTokens.join("\0") !== translatedTokens.join("\0")) throw new Error(`Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`);
|
|
216
|
-
translatedEntries[entry.id] = translation;
|
|
217
|
-
}
|
|
218
|
-
translations[locale] = translatedEntries;
|
|
219
|
-
}
|
|
220
|
-
return { translations };
|
|
221
|
-
};
|
|
222
|
-
const MAX_TASK_REQUEST_BYTES = 512 * 1024;
|
|
223
|
-
const DEFAULT_MAX_TASK_CONCURRENT_REQUESTS = 4;
|
|
224
|
-
const DEFAULT_MAX_TASK_DURATION_MS = 6e4;
|
|
225
|
-
const taskErrorResponse = (error) => {
|
|
226
|
-
const status = typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" ? error.status : error instanceof SyntaxError || error instanceof Error && error.name === "ZodError" ? 400 : 500;
|
|
227
|
-
const message = error instanceof SurveyAssistantRequestError ? error.message : status === 401 || status === 403 || status === 404 ? status === 404 ? "Survey assistant task not found." : "The survey assistant task is not authorized." : status >= 500 ? "The survey assistant task could not be completed." : "The survey assistant task request is invalid.";
|
|
228
|
-
return Response.json({
|
|
229
|
-
code: status === 401 || status === 403 || status === 404 ? "authorization_failed" : "request_failed",
|
|
230
|
-
error: message
|
|
231
|
-
}, { status });
|
|
232
|
-
};
|
|
233
|
-
const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError, isEnabled, maxConcurrentRequests = DEFAULT_MAX_TASK_CONCURRENT_REQUESTS, maxDurationMs = DEFAULT_MAX_TASK_DURATION_MS, onTaskMetrics, providerOptions, resolveModel }) => {
|
|
234
|
-
const concurrency = Number.isInteger(maxConcurrentRequests) && maxConcurrentRequests > 0 ? maxConcurrentRequests : DEFAULT_MAX_TASK_CONCURRENT_REQUESTS;
|
|
235
|
-
const duration = Number.isFinite(maxDurationMs) && maxDurationMs > 0 ? maxDurationMs : DEFAULT_MAX_TASK_DURATION_MS;
|
|
236
|
-
let activeRequests = 0;
|
|
237
|
-
return async (request) => {
|
|
238
|
-
if (activeRequests >= concurrency) return Response.json({
|
|
239
|
-
code: "rate_limited",
|
|
240
|
-
error: "The survey assistant is handling too many tasks. Try again shortly."
|
|
241
|
-
}, { status: 429 });
|
|
242
|
-
activeRequests += 1;
|
|
243
|
-
const startedAt = Date.now();
|
|
244
|
-
let metricsIdentity;
|
|
245
|
-
let metricsTaskId = "unknown";
|
|
246
|
-
let completed = false;
|
|
247
|
-
try {
|
|
248
|
-
if (isEnabled && !await isEnabled(request)) return Response.json({
|
|
249
|
-
code: "request_failed",
|
|
250
|
-
error: "Survey assistant is disabled."
|
|
251
|
-
}, { status: 404 });
|
|
252
|
-
const task = surveyAssistantTaskRequestSchema.parse(await readSurveyAssistantRequestJson(request, MAX_TASK_REQUEST_BYTES));
|
|
253
|
-
metricsTaskId = task.taskId;
|
|
254
|
-
const identity = await authorize({
|
|
255
|
-
request,
|
|
256
|
-
requestedResourceId: task.resourceId,
|
|
257
|
-
requestedSurveyId: task.surveyId
|
|
258
|
-
});
|
|
259
|
-
if (!identity?.resourceId?.trim() || identity.resourceId.trim().length > 240 || identity.surveyId !== void 0 && (!identity.surveyId.trim() || identity.surveyId.trim().length > 240)) throw Object.assign(/* @__PURE__ */ new Error("The host returned an invalid task identity."), { status: 500 });
|
|
260
|
-
metricsIdentity = {
|
|
261
|
-
resourceId: identity.resourceId.trim(),
|
|
262
|
-
...identity.surveyId?.trim() ? { surveyId: identity.surveyId.trim() } : {}
|
|
263
|
-
};
|
|
264
|
-
const readinessError = await getReadinessError?.(request);
|
|
265
|
-
if (readinessError) return Response.json({
|
|
266
|
-
code: "request_failed",
|
|
267
|
-
error: readinessError
|
|
268
|
-
}, { status: 503 });
|
|
269
|
-
const requestContext = new RequestContext();
|
|
270
|
-
let modelSelection;
|
|
271
|
-
if (resolveModel) {
|
|
272
|
-
modelSelection = await resolveModel({
|
|
273
|
-
identity: metricsIdentity,
|
|
274
|
-
request,
|
|
275
|
-
requestedModelId: task.modelId
|
|
276
|
-
}) ?? void 0;
|
|
277
|
-
if (!modelSelection) return Response.json({
|
|
278
|
-
code: "request_failed",
|
|
279
|
-
error: "The selected survey assistant model is unavailable."
|
|
280
|
-
}, { status: 400 });
|
|
281
|
-
requestContext.set("modelSelection", modelSelection);
|
|
282
|
-
}
|
|
283
|
-
const resolvedAgent = typeof agent === "function" ? await agent() : agent;
|
|
284
|
-
const runtime = {
|
|
285
|
-
abortSignal: AbortSignal.any([request.signal, AbortSignal.timeout(duration)]),
|
|
286
|
-
agent: resolvedAgent,
|
|
287
|
-
context: task.context,
|
|
288
|
-
mode: task.mode,
|
|
289
|
-
requestContext,
|
|
290
|
-
providerOptions: modelSelection?.providerOptions ?? providerOptions
|
|
291
|
-
};
|
|
292
|
-
const result = task.taskId === "suggest-item-key" ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime) : task.taskId === "suggest-item-label" ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime) : await runSurveyAssistantTranslateContentTask(task.input, runtime);
|
|
293
|
-
completed = true;
|
|
294
|
-
return Response.json(result);
|
|
295
|
-
} catch (error) {
|
|
296
|
-
return taskErrorResponse(error);
|
|
297
|
-
} finally {
|
|
298
|
-
activeRequests = Math.max(0, activeRequests - 1);
|
|
299
|
-
if (metricsIdentity) try {
|
|
300
|
-
onTaskMetrics?.({
|
|
301
|
-
durationMs: Date.now() - startedAt,
|
|
302
|
-
identity: metricsIdentity,
|
|
303
|
-
status: completed ? "completed" : "failed",
|
|
304
|
-
taskId: metricsTaskId
|
|
305
|
-
});
|
|
306
|
-
} catch {}
|
|
307
|
-
}
|
|
308
|
-
};
|
|
309
|
-
};
|
|
310
|
-
//#endregion
|
|
311
|
-
export { createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemKeyTask, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
|
|
312
|
-
|
|
313
|
-
//# sourceMappingURL=server-tasks.mjs.map
|
|
1
|
+
import { a as runSurveyAssistantSuggestResponseSettingsTask, i as runSurveyAssistantSuggestResponseNameTask, n as createSurveyAssistantTaskHandler, o as runSurveyAssistantTask, r as runSurveyAssistantSuggestItemLabelTask, s as runSurveyAssistantTranslateContentTask, t as createSurveyAssistantTaskAgent } from "./tasks-BZEiwgxA.mjs";
|
|
2
|
+
export { createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantSuggestResponseNameTask, runSurveyAssistantSuggestResponseSettingsTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
|
package/dist/server-tools.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-
|
|
1
|
+
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./index-r5riv4md.mjs";
|
|
2
2
|
export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
|
package/dist/server-tools.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-
|
|
1
|
+
import { i as surveyAuditTool, n as surveyAssistantTools, r as surveyAssetTool, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-CEsv-WoO.mjs";
|
|
2
2
|
export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
|
package/dist/server.d.mts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { a as
|
|
5
|
-
import {
|
|
6
|
-
import { _ as
|
|
1
|
+
import "./index-D7wT6P3t.mjs";
|
|
2
|
+
import { p as SurveyAssistantTurnTerminationReason } from "./lifecycle-Dm8u7QFh.mjs";
|
|
3
|
+
import { x as TurnSurveyDraft } from "./index-Ciq7vHIs.mjs";
|
|
4
|
+
import { C as SurveyAssistantRequestLimits, S as SurveyAssistantRequestError, T as validateSurveyAssistantMessages, _ as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, a as SurveyAssistantThreadDocumentContent, b as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, c as loadSurveyAssistantDocuments, d as removeHistoricalSurveyAssistantAttachments, f as replaceCurrentSurveyAssistantAttachmentsWithReferences, g as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, h as SURVEY_ASSISTANT_MAX_ATTACHMENTS, i as SurveyAssistantThreadDocument, l as loadSurveyAssistantThreadAttachments, m as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, n as SurveyAssistantLoadedDocument, o as SurveyAssistantThreadDocumentRepository, p as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, r as SurveyAssistantModelAttachment, s as getSurveyAssistantReplayableDocuments, t as SurveyAssistantAttachmentAccess, u as registerSurveyAssistantThreadAttachments, v as SURVEY_ASSISTANT_MAX_MESSAGES, w as readSurveyAssistantRequestJson, x as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, y as SURVEY_ASSISTANT_MAX_REQUEST_BYTES } from "./thread-documents-DrHbaXqP.mjs";
|
|
5
|
+
import { a as SurveyAssistantModelSelection, c as deriveSurveyAssistantDocumentTransition, d as parseSurveyAssistantSnapshot, f as requireSurveyAssistantTurnState, i as SurveyAssistantIdentityContext, l as parseSurveyAssistantPreviousApplyOutcome, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext, r as SurveyAssistantDocumentTransition, s as buildSurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID, u as parseSurveyAssistantPreviousSettledVersion } from "./constants-B6HzpEsx.mjs";
|
|
6
|
+
import { _ as describeSurveyAssistantStreamError, a as SurveyAssistantThreadRepository, c as SurveyAssistantAuthorizationInput, d as SurveyAssistantChatHandlerOptions, f as SurveyAssistantModelResolutionInput, g as createSurveyAssistantChatHandler, h as SurveyAssistantTurnMetrics, i as SurveyAssistantThreadIdentity, l as SurveyAssistantAuthorize, m as SurveyAssistantStreamErrorContext, n as SurveyAssistantStoredThread, o as createSurveyAssistantThreadHandlers, p as SurveyAssistantResolveModel, r as SurveyAssistantThreadErrorContext, s as SurveyAssistantAuthorizationError, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantAuthorizedIdentity, v as formatSurveyAssistantStreamError } from "./thread-handlers-Bef0td9N.mjs";
|
|
7
|
+
import { _ as surveyAuthoringReferenceTopics, a as SurveyAssistantTaskAuthorizationInput, g as formatSurveyAuthoringReferenceRoutingInstructions, h as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity, v as surveyAuthoringReferences } from "./tasks-B9h3LPam.mjs";
|
|
7
8
|
import { UIMessageChunk } from "ai";
|
|
8
9
|
import { MastraMemory } from "@mastra/core/memory";
|
|
9
|
-
|
|
10
10
|
//#region src/server/memory-thread-repository.d.ts
|
|
11
11
|
type ThreadMemory = Pick<MastraMemory, "createThread" | "deleteThread" | "getThreadById" | "listThreads" | "recall" | "updateThread">;
|
|
12
12
|
interface CreateMastraMemoryThreadRepositoryOptions {
|
|
@@ -17,15 +17,10 @@ interface CreateMastraMemoryThreadRepositoryOptions {
|
|
|
17
17
|
maxThreadsPerList?: number;
|
|
18
18
|
threadDocuments?: SurveyAssistantThreadDocumentRepository;
|
|
19
19
|
}
|
|
20
|
-
declare const createMastraMemoryThreadRepository: ({
|
|
21
|
-
getMemory,
|
|
22
|
-
maxMessagesPerTranscript,
|
|
23
|
-
maxThreadsPerList,
|
|
24
|
-
threadDocuments
|
|
25
|
-
}: CreateMastraMemoryThreadRepositoryOptions) => SurveyAssistantThreadRepository;
|
|
20
|
+
export declare const createMastraMemoryThreadRepository: ({ getMemory, maxMessagesPerTranscript, maxThreadsPerList, threadDocuments }: CreateMastraMemoryThreadRepositoryOptions) => SurveyAssistantThreadRepository;
|
|
26
21
|
//#endregion
|
|
27
22
|
//#region src/server/survey-lifecycle.d.ts
|
|
28
|
-
declare const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = "surveyId";
|
|
23
|
+
export declare const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = "surveyId";
|
|
29
24
|
type SurveyLifecycleMemory = Pick<MastraMemory, "deleteThread" | "getThreadById" | "listThreads" | "recall" | "createThread" | "updateThread">;
|
|
30
25
|
interface CreateSurveyAssistantSurveyLifecycleOptions {
|
|
31
26
|
getMemory(): SurveyLifecycleMemory | Promise<SurveyLifecycleMemory>;
|
|
@@ -81,10 +76,7 @@ interface SurveyAssistantSurveyLifecycle {
|
|
|
81
76
|
deleteSurveyThreads(input: DeleteSurveyAssistantSurveyThreadsInput): Promise<SurveyAssistantThreadCleanupResult>;
|
|
82
77
|
forSurvey(surveyId: string, resourceId: string): SurveyAssistantScopedSurvey;
|
|
83
78
|
}
|
|
84
|
-
declare const createSurveyAssistantSurveyThreadMetadata: ({
|
|
85
|
-
scopeMetadata,
|
|
86
|
-
surveyId
|
|
87
|
-
}: {
|
|
79
|
+
export declare const createSurveyAssistantSurveyThreadMetadata: ({ scopeMetadata, surveyId }: {
|
|
88
80
|
scopeMetadata: Record<string, string>;
|
|
89
81
|
surveyId: string;
|
|
90
82
|
}) => Record<string, string>;
|
|
@@ -94,12 +86,7 @@ declare const createSurveyAssistantSurveyThreadMetadata: ({
|
|
|
94
86
|
* new assistant activity and before completing (or from a durable retry of)
|
|
95
87
|
* survey deletion.
|
|
96
88
|
*/
|
|
97
|
-
declare const createSurveyAssistantSurveyLifecycle: ({
|
|
98
|
-
getMemory,
|
|
99
|
-
getThreadApi,
|
|
100
|
-
scopeMetadata,
|
|
101
|
-
threadDocuments
|
|
102
|
-
}: CreateSurveyAssistantSurveyLifecycleOptions) => SurveyAssistantSurveyLifecycle;
|
|
89
|
+
export declare const createSurveyAssistantSurveyLifecycle: ({ getMemory, getThreadApi, scopeMetadata, threadDocuments }: CreateSurveyAssistantSurveyLifecycleOptions) => SurveyAssistantSurveyLifecycle;
|
|
103
90
|
//#endregion
|
|
104
91
|
//#region src/server/turn-stream.d.ts
|
|
105
92
|
interface SurveyAssistantTurnStreamOptions {
|
|
@@ -113,17 +100,7 @@ interface SurveyAssistantTurnStreamOptions {
|
|
|
113
100
|
getAbortTerminationReason?: () => SurveyAssistantTurnTerminationReason | undefined;
|
|
114
101
|
turnStartedAt?: number;
|
|
115
102
|
}
|
|
116
|
-
declare const createSurveyAssistantTurnStream: ({
|
|
117
|
-
turnDraft,
|
|
118
|
-
getAbortErrorText,
|
|
119
|
-
getAbortTerminationReason,
|
|
120
|
-
onActivity,
|
|
121
|
-
onSettled,
|
|
122
|
-
onUnexpectedError,
|
|
123
|
-
signal,
|
|
124
|
-
stream,
|
|
125
|
-
turnStartedAt
|
|
126
|
-
}: SurveyAssistantTurnStreamOptions) => ReadableStream<UIMessageChunk>;
|
|
103
|
+
export declare const createSurveyAssistantTurnStream: ({ turnDraft, getAbortErrorText, getAbortTerminationReason, onActivity, onSettled, onUnexpectedError, signal, stream, turnStartedAt }: SurveyAssistantTurnStreamOptions) => ReadableStream<UIMessageChunk>;
|
|
127
104
|
//#endregion
|
|
128
|
-
export { type CreateMastraMemoryThreadRepositoryOptions, type CreateSurveyAssistantSurveyLifecycleOptions, type CreateSurveyAssistantThreadHandlersOptions, type DeleteSurveyAssistantSurveyThreadsInput, type DeleteSurveyAssistantSurveyThreadsResult, SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, SURVEY_ASSISTANT_AGENT_ID, SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, SURVEY_ASSISTANT_MAX_ATTACHMENTS, SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, SURVEY_ASSISTANT_MAX_MESSAGES, SURVEY_ASSISTANT_MAX_REQUEST_BYTES, SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES,
|
|
105
|
+
export { type CreateMastraMemoryThreadRepositoryOptions, type CreateSurveyAssistantSurveyLifecycleOptions, type CreateSurveyAssistantThreadHandlersOptions, type DeleteSurveyAssistantSurveyThreadsInput, type DeleteSurveyAssistantSurveyThreadsResult, SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, SURVEY_ASSISTANT_AGENT_ID, SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, SURVEY_ASSISTANT_MAX_ATTACHMENTS, SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, SURVEY_ASSISTANT_MAX_MESSAGES, SURVEY_ASSISTANT_MAX_REQUEST_BYTES, SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, SURVEY_ASSISTANT_TASK_AGENT_ID, type SurveyAssistantAttachmentAccess, SurveyAssistantAuthorizationError, type SurveyAssistantAuthorizationInput, type SurveyAssistantAuthorize, type SurveyAssistantAuthorizedIdentity, type SurveyAssistantChatHandlerOptions, type SurveyAssistantDocumentTransition, type SurveyAssistantIdentityContext, type SurveyAssistantLoadedDocument, type SurveyAssistantModelAttachment, type SurveyAssistantModelResolutionInput, type SurveyAssistantModelSelection, type SurveyAssistantRequestContext, SurveyAssistantRequestError, type SurveyAssistantRequestLimits, type SurveyAssistantResolveModel, type SurveyAssistantScopedSurvey, type SurveyAssistantStoredThread, type SurveyAssistantStreamErrorContext, type SurveyAssistantSurveyLifecycle, type SurveyAssistantSurveyPanelProps, type SurveyAssistantThreadCleanupResult, type SurveyAssistantThreadDocument, type SurveyAssistantThreadDocumentContent, type SurveyAssistantThreadDocumentRepository, type SurveyAssistantThreadErrorContext, type SurveyAssistantThreadIdentity, type SurveyAssistantThreadRepository, type SurveyAssistantTurnMetrics, type SurveyAssistantTurnStreamOptions, type SurveyAuthoringReferenceTopic, buildSurveyAssistantRequestContext, createSurveyAssistantChatHandler, createSurveyAssistantThreadHandlers, deriveSurveyAssistantDocumentTransition, describeSurveyAssistantStreamError, formatSurveyAssistantStreamError, formatSurveyAuthoringReferenceRoutingInstructions, getSurveyAssistantReplayableDocuments, loadSurveyAssistantDocuments, loadSurveyAssistantThreadAttachments, parseSurveyAssistantPreviousApplyOutcome, parseSurveyAssistantPreviousSettledVersion, parseSurveyAssistantSnapshot, readSurveyAssistantRequestJson, registerSurveyAssistantThreadAttachments, removeHistoricalSurveyAssistantAttachments, replaceCurrentSurveyAssistantAttachmentsWithReferences, requireSurveyAssistantTurnState, surveyAuthoringReferenceTopics, surveyAuthoringReferences, validateSurveyAssistantMessages };
|
|
129
106
|
//# sourceMappingURL=server.d.mts.map
|
package/dist/server.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/memory-thread-repository.ts","../src/server/survey-lifecycle.ts","../src/server/turn-stream.ts"],"mappings":";;;;;;;;;;KAKK,
|
|
1
|
+
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/memory-thread-repository.ts","../src/server/survey-lifecycle.ts","../src/server/turn-stream.ts"],"mappings":";;;;;;;;;;KAKK,eAAe,KAClB;UAIe;EACf,aAAa,eAAe,QAAQ;;EAEpC;;EAEA;EACA,kBAAkB;;qBAGP,uCAAsC,WAAA,0BAAA,mBAAA,mBAKhD,8CAA4C;;;qBCTlC;KAER,wBAAwB,KAC3B;UAIe;EACf,aAAa,wBAAwB,QAAQ;;EAE7C,cAAc;;;;;EAKd,eAAe;;;;;EAKf,iBAAiB;;UAGF;EACf;;EAEA;;UAGe;EACf;EACA;;KAGU,2CAA2C;UAEtC;EACf;EACA;EACA;;UAGe;;EAEf,eAAe;;EAEf,cACE,OAAO,wCACN;;EAEH,iBAAiB,QAAQ;;EAEzB,WACE,QAAQ,iDACP,UAAU;;EAEb,YAAY;EACZ;EACA;;EAEA,gBAAgB;;UAGD;;EAEf,eAAe,qBAAqB,QAAQ;;EAE5C,aAAa,mBAAmB,QAAQ;EACxC,oBACE,OAAO,0CACN,QAAQ;EACX,UAAU,kBAAkB,qBAAqB;;qBAmCtC,8CAA6C,eAAA;EAIxD,eAAe;EACf;MACE;;;;;;;qBAcS,yCAAwC,WAAA,cAAA,eAAA,mBAKlD,gDAA8C;;;UCnIhC;EACf,QAAQ,eAAe;EACvB,WAAW;EACX,SAAS;EACT,qBAAqB;EACrB;EACA;EACA;EACA,kCAAkC;EAClC;;qBAqBW,oCAAmC,WAAA,mBAAA,2BAAA,YAAA,WAAA,mBAAA,QAAA,QAAA,iBAU7C,qCAAmC,eAAe"}
|
package/dist/server.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-
|
|
2
|
-
import { a as
|
|
3
|
-
import { a as
|
|
4
|
-
import { a as
|
|
5
|
-
import { a as surveyAuthoringReferences, i as surveyAuthoringReferenceTopics, n as formatSurveyAuthoringReferenceRoutingInstructions } from "./authoring-references-
|
|
1
|
+
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-Ct-vv9cu.mjs";
|
|
2
|
+
import { a as describeSurveyAssistantStreamError, c as loadSurveyAssistantDocuments, d as removeHistoricalSurveyAssistantAttachments, f as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as createSurveyAssistantChatHandler, l as loadSurveyAssistantThreadAttachments, n as createSurveyAssistantThreadHandlers, o as formatSurveyAssistantStreamError, p as createSurveyAssistantTurnStream, r as SurveyAssistantAuthorizationError, s as getSurveyAssistantReplayableDocuments, t as createMastraMemoryThreadRepository, u as registerSurveyAssistantThreadAttachments } from "./memory-thread-repository-DAnOGIB3.mjs";
|
|
3
|
+
import { a as parseSurveyAssistantPreviousSettledVersion, i as parseSurveyAssistantPreviousApplyOutcome, n as deriveSurveyAssistantDocumentTransition, o as parseSurveyAssistantSnapshot, s as requireSurveyAssistantTurnState, t as buildSurveyAssistantRequestContext } from "./request-context-Dg4jSwN1.mjs";
|
|
4
|
+
import { a as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, c as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, d as readSurveyAssistantRequestJson, f as validateSurveyAssistantMessages, i as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, l as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, n as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS, o as SURVEY_ASSISTANT_MAX_MESSAGES, r as SURVEY_ASSISTANT_MAX_ATTACHMENTS, s as SURVEY_ASSISTANT_MAX_REQUEST_BYTES, t as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, u as SurveyAssistantRequestError } from "./request-guardrails-C0ugBOp0.mjs";
|
|
5
|
+
import { a as surveyAuthoringReferences, i as surveyAuthoringReferenceTopics, n as formatSurveyAuthoringReferenceRoutingInstructions } from "./authoring-references-DbuOKerg.mjs";
|
|
6
6
|
//#region src/server/survey-lifecycle.ts
|
|
7
7
|
const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = "surveyId";
|
|
8
8
|
const normalizeIdentifier = (value, label) => {
|
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","names":[],"sources":["../src/server/survey-lifecycle.ts"],"sourcesContent":["import type { MastraMemory } from \"@mastra/core/memory\";\nimport {\n SurveyAssistantAuthorizationError,\n type SurveyAssistantAuthorizationInput,\n type SurveyAssistantAuthorizedIdentity,\n type SurveyAssistantAuthorize,\n} from \"./handler\";\nimport { createMastraMemoryThreadRepository } from \"./memory-thread-repository\";\nimport type { SurveyAssistantThreadDocumentRepository } from \"./thread-documents\";\nimport type { SurveyAssistantStoredThread, SurveyAssistantThreadIdentity } from \"./thread-handlers\";\nimport type {\n SurveyAssistantTaskAuthorizationInput,\n SurveyAssistantTaskAuthorizedIdentity,\n} from \"./tasks\";\n\nexport const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = \"surveyId\";\n\ntype SurveyLifecycleMemory = Pick<\n MastraMemory,\n \"deleteThread\" | \"getThreadById\" | \"listThreads\" | \"recall\" | \"createThread\" | \"updateThread\"\n>;\n\nexport interface CreateSurveyAssistantSurveyLifecycleOptions {\n getMemory(): SurveyLifecycleMemory | Promise<SurveyLifecycleMemory>;\n /** Optionally derives the survey-scoped thread endpoint exposed in `panelProps`. */\n getThreadApi?(surveyId: string): string;\n /**\n * Stable host metadata that separates this assistant deployment from any\n * other application using the same Mastra storage.\n */\n scopeMetadata: Record<string, string>;\n /**\n * Pass the same repository used by the chat handler, or explicitly use\n * `false` when cross-turn attachment persistence/replay is disabled.\n */\n threadDocuments: SurveyAssistantThreadDocumentRepository | false;\n}\n\nexport interface DeleteSurveyAssistantSurveyThreadsInput {\n surveyId: string;\n /** Restrict cleanup to one user. Omit this when the survey itself is deleted. */\n resourceId?: string;\n}\n\nexport interface SurveyAssistantThreadCleanupResult {\n deletedThreadIds: string[];\n matchedThreadCount: number;\n}\n\nexport type DeleteSurveyAssistantSurveyThreadsResult = SurveyAssistantThreadCleanupResult;\n\nexport interface SurveyAssistantSurveyPanelProps {\n resourceId: string;\n surveyId: string;\n threadApi?: string;\n}\n\nexport interface SurveyAssistantScopedSurvey {\n /** Validates the requested ids and returns a trusted identity for the chat handler. */\n authorizeChat: SurveyAssistantAuthorize;\n /** Validates the requested survey/resource ids for the bounded task handler. */\n authorizeTask(\n input: SurveyAssistantTaskAuthorizationInput,\n ): SurveyAssistantTaskAuthorizedIdentity;\n /** Deletes this user's threads for the survey. */\n deleteThreads(): Promise<DeleteSurveyAssistantSurveyThreadsResult>;\n /** Returns true only for a thread in this exact deployment, survey, and user scope. */\n ownsThread(\n thread: SurveyAssistantStoredThread | null | undefined,\n ): thread is SurveyAssistantStoredThread;\n /** Props that can be passed directly to ConnectedSurveyAssistantPanel. */\n panelProps: SurveyAssistantSurveyPanelProps;\n resourceId: string;\n surveyId: string;\n /** Identity returned by the thread handler's authorize callback. */\n threadIdentity: SurveyAssistantThreadIdentity;\n}\n\nexport interface SurveyAssistantSurveyLifecycle {\n /** Deletes this resource's threads across every survey in this deployment scope. */\n deleteResource(resourceId: string): Promise<SurveyAssistantThreadCleanupResult>;\n /** Deletes every user's threads for a survey. */\n deleteSurvey(surveyId: string): Promise<SurveyAssistantThreadCleanupResult>;\n deleteSurveyThreads(\n input: DeleteSurveyAssistantSurveyThreadsInput,\n ): Promise<SurveyAssistantThreadCleanupResult>;\n forSurvey(surveyId: string, resourceId: string): SurveyAssistantScopedSurvey;\n}\n\nconst normalizeIdentifier = (value: string, label: string) => {\n const normalized = value.trim();\n if (!normalized || normalized.length > 240) {\n throw new Error(`${label} must contain between 1 and 240 characters.`);\n }\n return normalized;\n};\n\nconst normalizeScopeMetadata = (metadata: Record<string, string>) => {\n const entries = Object.entries(metadata);\n if (entries.length === 0) {\n throw new Error(\"Survey assistant lifecycle scope metadata must not be empty.\");\n }\n if (SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY in metadata) {\n throw new Error(\n `Survey assistant lifecycle scope metadata must not contain \"${SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY}\".`,\n );\n }\n\n return Object.fromEntries(\n entries.map(([key, value]) => [\n normalizeIdentifier(key, \"Survey assistant lifecycle metadata key\"),\n normalizeIdentifier(value, `Survey assistant lifecycle metadata \"${key}\"`),\n ]),\n );\n};\n\nconst hasMetadata = (\n threadMetadata: Record<string, unknown> | undefined,\n expected: Record<string, string>,\n) => Object.entries(expected).every(([key, value]) => threadMetadata?.[key] === value);\n\nexport const createSurveyAssistantSurveyThreadMetadata = ({\n scopeMetadata,\n surveyId,\n}: {\n scopeMetadata: Record<string, string>;\n surveyId: string;\n}): Record<string, string> => ({\n ...normalizeScopeMetadata(scopeMetadata),\n [SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY]: normalizeIdentifier(\n surveyId,\n \"Survey assistant survey id\",\n ),\n});\n\n/**\n * Creates an idempotent, server-only lifecycle service for removing every\n * assistant thread owned by a survey. Hosts should call this after preventing\n * new assistant activity and before completing (or from a durable retry of)\n * survey deletion.\n */\nexport const createSurveyAssistantSurveyLifecycle = ({\n getMemory,\n getThreadApi,\n scopeMetadata,\n threadDocuments,\n}: CreateSurveyAssistantSurveyLifecycleOptions): SurveyAssistantSurveyLifecycle => {\n const normalizedScopeMetadata = Object.freeze(normalizeScopeMetadata(scopeMetadata));\n const repository = createMastraMemoryThreadRepository({\n getMemory,\n threadDocuments: threadDocuments || undefined,\n });\n\n const deleteMatchingThreads = async ({\n metadata,\n resourceId,\n }: {\n metadata: Record<string, string>;\n resourceId?: string;\n }): Promise<DeleteSurveyAssistantSurveyThreadsResult> => {\n const memory = await getMemory();\n const result = await memory.listThreads({\n filter: {\n metadata,\n ...(resourceId ? { resourceId } : {}),\n },\n orderBy: { field: \"createdAt\", direction: \"ASC\" },\n perPage: false,\n });\n const matchedThreads = result.threads.filter(\n (thread) =>\n (!resourceId || thread.resourceId === resourceId) && hasMetadata(thread.metadata, metadata),\n );\n const deletedThreadIds: string[] = [];\n\n for (const listedThread of matchedThreads) {\n // Re-check the current record so a concurrently reassigned thread is not\n // deleted from a stale list result.\n const currentThread = await memory.getThreadById({ threadId: listedThread.id });\n if (\n !currentThread ||\n (resourceId && currentThread.resourceId !== resourceId) ||\n !hasMetadata(currentThread.metadata, metadata)\n ) {\n continue;\n }\n await repository.delete(currentThread.id);\n deletedThreadIds.push(currentThread.id);\n }\n\n return {\n deletedThreadIds,\n matchedThreadCount: matchedThreads.length,\n };\n };\n\n const deleteSurveyThreads = async ({\n resourceId,\n surveyId,\n }: DeleteSurveyAssistantSurveyThreadsInput): Promise<DeleteSurveyAssistantSurveyThreadsResult> => {\n const normalizedResourceId = resourceId\n ? normalizeIdentifier(resourceId, \"Survey assistant resource id\")\n : undefined;\n return deleteMatchingThreads({\n metadata: createSurveyAssistantSurveyThreadMetadata({\n scopeMetadata: normalizedScopeMetadata,\n surveyId,\n }),\n resourceId: normalizedResourceId,\n });\n };\n\n const deleteSurvey = (surveyId: string) => deleteSurveyThreads({ surveyId });\n const deleteResource = (resourceId: string) =>\n deleteMatchingThreads({\n metadata: normalizedScopeMetadata,\n resourceId: normalizeIdentifier(resourceId, \"Survey assistant resource id\"),\n });\n\n const forSurvey = (surveyId: string, resourceId: string): SurveyAssistantScopedSurvey => {\n const normalizedSurveyId = normalizeIdentifier(surveyId, \"Survey assistant survey id\");\n const normalizedResourceId = normalizeIdentifier(resourceId, \"Survey assistant resource id\");\n const metadata = Object.freeze(\n createSurveyAssistantSurveyThreadMetadata({\n scopeMetadata: normalizedScopeMetadata,\n surveyId: normalizedSurveyId,\n }),\n );\n const threadApi = getThreadApi?.(normalizedSurveyId)?.trim();\n if (getThreadApi && !threadApi) {\n throw new Error(\"Survey assistant thread API must not be empty.\");\n }\n const panelProps: SurveyAssistantSurveyPanelProps = Object.freeze({\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n ...(threadApi ? { threadApi } : {}),\n });\n const threadIdentity: SurveyAssistantThreadIdentity = Object.freeze({\n metadata,\n resourceId: normalizedResourceId,\n });\n const ownsThread = (\n thread: SurveyAssistantStoredThread | null | undefined,\n ): thread is SurveyAssistantStoredThread =>\n Boolean(\n thread &&\n thread.resourceId === normalizedResourceId &&\n hasMetadata(thread.metadata, metadata),\n );\n const authorizeChat = async ({\n requestedResourceId,\n requestedSurveyId,\n requestedThreadId,\n }: SurveyAssistantAuthorizationInput): Promise<SurveyAssistantAuthorizedIdentity> => {\n if (\n requestedResourceId !== normalizedResourceId ||\n requestedSurveyId !== normalizedSurveyId ||\n !requestedThreadId\n ) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant chat not found.\", 404);\n }\n const memory = await getMemory();\n const thread = await memory.getThreadById({ threadId: requestedThreadId });\n if (!ownsThread(thread)) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant chat not found.\", 404);\n }\n return {\n authority: \"authenticated-host\",\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n threadId: thread.id,\n };\n };\n const authorizeTask = ({\n requestedResourceId,\n requestedSurveyId,\n }: SurveyAssistantTaskAuthorizationInput): SurveyAssistantTaskAuthorizedIdentity => {\n if (\n requestedResourceId !== normalizedResourceId ||\n requestedSurveyId !== normalizedSurveyId\n ) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant task not found.\", 404);\n }\n return {\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n };\n };\n\n return Object.freeze({\n authorizeChat,\n authorizeTask,\n deleteThreads: () =>\n deleteSurveyThreads({\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n }),\n ownsThread,\n panelProps,\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n threadIdentity,\n });\n };\n\n return Object.freeze({ deleteResource, deleteSurvey, deleteSurveyThreads, forSurvey });\n};\n"],"mappings":";;;;;;AAeA,MAAa,0CAA0C;AA0EvD,MAAM,uBAAuB,OAAe,UAAkB;CAC5D,MAAM,aAAa,MAAM,MAAM;AAC/B,KAAI,CAAC,cAAc,WAAW,SAAS,IACrC,OAAM,IAAI,MAAM,GAAG,MAAM,6CAA6C;AAExE,QAAO;;AAGT,MAAM,0BAA0B,aAAqC;CACnE,MAAM,UAAU,OAAO,QAAQ,SAAS;AACxC,KAAI,QAAQ,WAAW,EACrB,OAAM,IAAI,MAAM,+DAA+D;AAEjF,KAAA,cAA+C,SAC7C,OAAM,IAAI,MACR,+DAA+D,wCAAwC,IACxG;AAGH,QAAO,OAAO,YACZ,QAAQ,KAAK,CAAC,KAAK,WAAW,CAC5B,oBAAoB,KAAK,0CAA0C,EACnE,oBAAoB,OAAO,wCAAwC,IAAI,GAAG,CAC3E,CAAC,CACH;;AAGH,MAAM,eACJ,gBACA,aACG,OAAO,QAAQ,SAAS,CAAC,OAAO,CAAC,KAAK,WAAW,iBAAiB,SAAS,MAAM;AAEtF,MAAa,6CAA6C,EACxD,eACA,gBAI6B;CAC7B,GAAG,uBAAuB,cAAc;EACvC,0CAA0C,oBACzC,UACA,6BACD;CACF;;;;;;;AAQD,MAAa,wCAAwC,EACnD,WACA,cACA,eACA,sBACiF;CAC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le.ts"],"sourcesContent":["import type { MastraMemory } from \"@mastra/core/memory\";\nimport {\n SurveyAssistantAuthorizationError,\n type SurveyAssistantAuthorizationInput,\n type SurveyAssistantAuthorizedIdentity,\n type SurveyAssistantAuthorize,\n} from \"./handler\";\nimport { createMastraMemoryThreadRepository } from \"./memory-thread-repository\";\nimport type { SurveyAssistantThreadDocumentRepository } from \"./thread-documents\";\nimport type { SurveyAssistantStoredThread, SurveyAssistantThreadIdentity } from \"./thread-handlers\";\nimport type {\n SurveyAssistantTaskAuthorizationInput,\n SurveyAssistantTaskAuthorizedIdentity,\n} from \"./tasks\";\n\nexport const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = \"surveyId\";\n\ntype SurveyLifecycleMemory = Pick<\n MastraMemory,\n \"deleteThread\" | \"getThreadById\" | \"listThreads\" | \"recall\" | \"createThread\" | \"updateThread\"\n>;\n\nexport interface CreateSurveyAssistantSurveyLifecycleOptions {\n getMemory(): SurveyLifecycleMemory | Promise<SurveyLifecycleMemory>;\n /** Optionally derives the survey-scoped thread endpoint exposed in `panelProps`. */\n getThreadApi?(surveyId: string): string;\n /**\n * Stable host metadata that separates this assistant deployment from any\n * other application using the same Mastra storage.\n */\n scopeMetadata: Record<string, string>;\n /**\n * Pass the same repository used by the chat handler, or explicitly use\n * `false` when cross-turn attachment persistence/replay is disabled.\n */\n threadDocuments: SurveyAssistantThreadDocumentRepository | false;\n}\n\nexport interface DeleteSurveyAssistantSurveyThreadsInput {\n surveyId: string;\n /** Restrict cleanup to one user. Omit this when the survey itself is deleted. */\n resourceId?: string;\n}\n\nexport interface SurveyAssistantThreadCleanupResult {\n deletedThreadIds: string[];\n matchedThreadCount: number;\n}\n\nexport type DeleteSurveyAssistantSurveyThreadsResult = SurveyAssistantThreadCleanupResult;\n\nexport interface SurveyAssistantSurveyPanelProps {\n resourceId: string;\n surveyId: string;\n threadApi?: string;\n}\n\nexport interface SurveyAssistantScopedSurvey {\n /** Validates the requested ids and returns a trusted identity for the chat handler. */\n authorizeChat: SurveyAssistantAuthorize;\n /** Validates the requested survey/resource ids for the bounded task handler. */\n authorizeTask(\n input: SurveyAssistantTaskAuthorizationInput,\n ): SurveyAssistantTaskAuthorizedIdentity;\n /** Deletes this user's threads for the survey. */\n deleteThreads(): Promise<DeleteSurveyAssistantSurveyThreadsResult>;\n /** Returns true only for a thread in this exact deployment, survey, and user scope. */\n ownsThread(\n thread: SurveyAssistantStoredThread | null | undefined,\n ): thread is SurveyAssistantStoredThread;\n /** Props that can be passed directly to ConnectedSurveyAssistantPanel. */\n panelProps: SurveyAssistantSurveyPanelProps;\n resourceId: string;\n surveyId: string;\n /** Identity returned by the thread handler's authorize callback. */\n threadIdentity: SurveyAssistantThreadIdentity;\n}\n\nexport interface SurveyAssistantSurveyLifecycle {\n /** Deletes this resource's threads across every survey in this deployment scope. */\n deleteResource(resourceId: string): Promise<SurveyAssistantThreadCleanupResult>;\n /** Deletes every user's threads for a survey. */\n deleteSurvey(surveyId: string): Promise<SurveyAssistantThreadCleanupResult>;\n deleteSurveyThreads(\n input: DeleteSurveyAssistantSurveyThreadsInput,\n ): Promise<SurveyAssistantThreadCleanupResult>;\n forSurvey(surveyId: string, resourceId: string): SurveyAssistantScopedSurvey;\n}\n\nconst normalizeIdentifier = (value: string, label: string) => {\n const normalized = value.trim();\n if (!normalized || normalized.length > 240) {\n throw new Error(`${label} must contain between 1 and 240 characters.`);\n }\n return normalized;\n};\n\nconst normalizeScopeMetadata = (metadata: Record<string, string>) => {\n const entries = Object.entries(metadata);\n if (entries.length === 0) {\n throw new Error(\"Survey assistant lifecycle scope metadata must not be empty.\");\n }\n if (SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY in metadata) {\n throw new Error(\n `Survey assistant lifecycle scope metadata must not contain \"${SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY}\".`,\n );\n }\n\n return Object.fromEntries(\n entries.map(([key, value]) => [\n normalizeIdentifier(key, \"Survey assistant lifecycle metadata key\"),\n normalizeIdentifier(value, `Survey assistant lifecycle metadata \"${key}\"`),\n ]),\n );\n};\n\nconst hasMetadata = (\n threadMetadata: Record<string, unknown> | undefined,\n expected: Record<string, string>,\n) => Object.entries(expected).every(([key, value]) => threadMetadata?.[key] === value);\n\nexport const createSurveyAssistantSurveyThreadMetadata = ({\n scopeMetadata,\n surveyId,\n}: {\n scopeMetadata: Record<string, string>;\n surveyId: string;\n}): Record<string, string> => ({\n ...normalizeScopeMetadata(scopeMetadata),\n [SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY]: normalizeIdentifier(\n surveyId,\n \"Survey assistant survey id\",\n ),\n});\n\n/**\n * Creates an idempotent, server-only lifecycle service for removing every\n * assistant thread owned by a survey. Hosts should call this after preventing\n * new assistant activity and before completing (or from a durable retry of)\n * survey deletion.\n */\nexport const createSurveyAssistantSurveyLifecycle = ({\n getMemory,\n getThreadApi,\n scopeMetadata,\n threadDocuments,\n}: CreateSurveyAssistantSurveyLifecycleOptions): SurveyAssistantSurveyLifecycle => {\n const normalizedScopeMetadata = Object.freeze(normalizeScopeMetadata(scopeMetadata));\n const repository = createMastraMemoryThreadRepository({\n getMemory,\n threadDocuments: threadDocuments || undefined,\n });\n\n const deleteMatchingThreads = async ({\n metadata,\n resourceId,\n }: {\n metadata: Record<string, string>;\n resourceId?: string;\n }): Promise<DeleteSurveyAssistantSurveyThreadsResult> => {\n const memory = await getMemory();\n const result = await memory.listThreads({\n filter: {\n metadata,\n ...(resourceId ? { resourceId } : {}),\n },\n orderBy: { field: \"createdAt\", direction: \"ASC\" },\n perPage: false,\n });\n const matchedThreads = result.threads.filter(\n (thread) =>\n (!resourceId || thread.resourceId === resourceId) && hasMetadata(thread.metadata, metadata),\n );\n const deletedThreadIds: string[] = [];\n\n for (const listedThread of matchedThreads) {\n // Re-check the current record so a concurrently reassigned thread is not\n // deleted from a stale list result.\n const currentThread = await memory.getThreadById({ threadId: listedThread.id });\n if (\n !currentThread ||\n (resourceId && currentThread.resourceId !== resourceId) ||\n !hasMetadata(currentThread.metadata, metadata)\n ) {\n continue;\n }\n await repository.delete(currentThread.id);\n deletedThreadIds.push(currentThread.id);\n }\n\n return {\n deletedThreadIds,\n matchedThreadCount: matchedThreads.length,\n };\n };\n\n const deleteSurveyThreads = async ({\n resourceId,\n surveyId,\n }: DeleteSurveyAssistantSurveyThreadsInput): Promise<DeleteSurveyAssistantSurveyThreadsResult> => {\n const normalizedResourceId = resourceId\n ? normalizeIdentifier(resourceId, \"Survey assistant resource id\")\n : undefined;\n return deleteMatchingThreads({\n metadata: createSurveyAssistantSurveyThreadMetadata({\n scopeMetadata: normalizedScopeMetadata,\n surveyId,\n }),\n resourceId: normalizedResourceId,\n });\n };\n\n const deleteSurvey = (surveyId: string) => deleteSurveyThreads({ surveyId });\n const deleteResource = (resourceId: string) =>\n deleteMatchingThreads({\n metadata: normalizedScopeMetadata,\n resourceId: normalizeIdentifier(resourceId, \"Survey assistant resource id\"),\n });\n\n const forSurvey = (surveyId: string, resourceId: string): SurveyAssistantScopedSurvey => {\n const normalizedSurveyId = normalizeIdentifier(surveyId, \"Survey assistant survey id\");\n const normalizedResourceId = normalizeIdentifier(resourceId, \"Survey assistant resource id\");\n const metadata = Object.freeze(\n createSurveyAssistantSurveyThreadMetadata({\n scopeMetadata: normalizedScopeMetadata,\n surveyId: normalizedSurveyId,\n }),\n );\n const threadApi = getThreadApi?.(normalizedSurveyId)?.trim();\n if (getThreadApi && !threadApi) {\n throw new Error(\"Survey assistant thread API must not be empty.\");\n }\n const panelProps: SurveyAssistantSurveyPanelProps = Object.freeze({\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n ...(threadApi ? { threadApi } : {}),\n });\n const threadIdentity: SurveyAssistantThreadIdentity = Object.freeze({\n metadata,\n resourceId: normalizedResourceId,\n });\n const ownsThread = (\n thread: SurveyAssistantStoredThread | null | undefined,\n ): thread is SurveyAssistantStoredThread =>\n Boolean(\n thread &&\n thread.resourceId === normalizedResourceId &&\n hasMetadata(thread.metadata, metadata),\n );\n const authorizeChat = async ({\n requestedResourceId,\n requestedSurveyId,\n requestedThreadId,\n }: SurveyAssistantAuthorizationInput): Promise<SurveyAssistantAuthorizedIdentity> => {\n if (\n requestedResourceId !== normalizedResourceId ||\n requestedSurveyId !== normalizedSurveyId ||\n !requestedThreadId\n ) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant chat not found.\", 404);\n }\n const memory = await getMemory();\n const thread = await memory.getThreadById({ threadId: requestedThreadId });\n if (!ownsThread(thread)) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant chat not found.\", 404);\n }\n return {\n authority: \"authenticated-host\",\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n threadId: thread.id,\n };\n };\n const authorizeTask = ({\n requestedResourceId,\n requestedSurveyId,\n }: SurveyAssistantTaskAuthorizationInput): SurveyAssistantTaskAuthorizedIdentity => {\n if (\n requestedResourceId !== normalizedResourceId ||\n requestedSurveyId !== normalizedSurveyId\n ) {\n throw new SurveyAssistantAuthorizationError(\"Survey assistant task not found.\", 404);\n }\n return {\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n };\n };\n\n return Object.freeze({\n authorizeChat,\n authorizeTask,\n deleteThreads: () =>\n deleteSurveyThreads({\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n }),\n ownsThread,\n panelProps,\n resourceId: normalizedResourceId,\n surveyId: normalizedSurveyId,\n threadIdentity,\n });\n };\n\n return Object.freeze({ deleteResource, deleteSurvey, deleteSurveyThreads, forSurvey });\n};\n"],"mappings":";;;;;;AAeA,MAAa,0CAA0C;AA0EvD,MAAM,uBAAuB,OAAe,UAAkB;CAC5D,MAAM,aAAa,MAAM,KAAK;CAC9B,IAAI,CAAC,cAAc,WAAW,SAAS,KACrC,MAAM,IAAI,MAAM,GAAG,MAAM,4CAA4C;CAEvE,OAAO;AACT;AAEA,MAAM,0BAA0B,aAAqC;CACnE,MAAM,UAAU,OAAO,QAAQ,QAAQ;CACvC,IAAI,Q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IAAI,CAAC,WAAW,MAAM,GACpB,MAAM,IAAI,kCAAkC,oCAAoC,GAAG;GAErF,OAAO;IACL,WAAW;IACX,YAAY;IACZ,UAAU;IACV,UAAU,OAAO;GACnB;EACF;EACA,MAAM,iBAAiB,EACrB,qBACA,wBACkF;GAClF,IACE,wBAAwB,wBACxB,sBAAsB,oBAEtB,MAAM,IAAI,kCAAkC,oCAAoC,GAAG;GAErF,OAAO;IACL,YAAY;IACZ,UAAU;GACZ;EACF;EAEA,OAAO,OAAO,OAAO;GACnB;GACA;GACA,qBACE,oBAAoB;IAClB,YAAY;IACZ,UAAU;GACZ,CAAC;GACH;GACA;GACA,YAAY;GACZ,UAAU;GACV;EACF,CAAC;CACH;CAEA,OAAO,OAAO,OAAO;EAAE;EAAgB;EAAc;EAAqB;CAAU,CAAC;AACvF"}
|
|
@@ -1,47 +1,31 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { o as SurveyAssistantThreadDocumentRepository } from "./thread-documents-DrHbaXqP.mjs";
|
|
2
2
|
import { PostgresStore, PostgresStoreConfig } from "@mastra/pg";
|
|
3
|
-
|
|
4
3
|
//#region src/storage/postgres.d.ts
|
|
5
|
-
declare const SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENTS_PER_THREAD = 100;
|
|
6
|
-
declare const SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENT_BYTES_PER_THREAD: number;
|
|
7
|
-
interface InitializeSurveyAssistantPostgresStorageOptions {
|
|
4
|
+
export declare const SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENTS_PER_THREAD = 100;
|
|
5
|
+
export declare const SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENT_BYTES_PER_THREAD: number;
|
|
6
|
+
export interface InitializeSurveyAssistantPostgresStorageOptions {
|
|
8
7
|
ensureObservationalMemory?: boolean;
|
|
9
8
|
schemaName?: string;
|
|
10
9
|
}
|
|
11
|
-
declare const initializeSurveyAssistantPostgresStorage: (storage: PostgresStore, {
|
|
12
|
-
|
|
13
|
-
schemaName
|
|
14
|
-
}?: InitializeSurveyAssistantPostgresStorageOptions) => Promise<PostgresStore>;
|
|
15
|
-
interface CreateSurveyAssistantPostgresThreadDocumentRepositoryOptions {
|
|
10
|
+
export declare const initializeSurveyAssistantPostgresStorage: (storage: PostgresStore, { ensureObservationalMemory, schemaName }?: InitializeSurveyAssistantPostgresStorageOptions) => Promise<PostgresStore>;
|
|
11
|
+
export interface CreateSurveyAssistantPostgresThreadDocumentRepositoryOptions {
|
|
16
12
|
getStorage(): PostgresStore | Promise<PostgresStore>;
|
|
17
13
|
maxStoredAttachmentsPerThread?: number;
|
|
18
14
|
maxStoredBytesPerThread?: number;
|
|
19
15
|
schemaName?: string;
|
|
20
16
|
}
|
|
21
|
-
declare const createSurveyAssistantPostgresThreadDocumentRepository: ({
|
|
22
|
-
|
|
23
|
-
maxStoredAttachmentsPerThread,
|
|
24
|
-
maxStoredBytesPerThread,
|
|
25
|
-
schemaName
|
|
26
|
-
}: CreateSurveyAssistantPostgresThreadDocumentRepositoryOptions) => SurveyAssistantThreadDocumentRepository;
|
|
27
|
-
interface CreateSurveyAssistantPostgresRuntimeOptions {
|
|
17
|
+
export declare const createSurveyAssistantPostgresThreadDocumentRepository: ({ getStorage, maxStoredAttachmentsPerThread, maxStoredBytesPerThread, schemaName }: CreateSurveyAssistantPostgresThreadDocumentRepositoryOptions) => SurveyAssistantThreadDocumentRepository;
|
|
18
|
+
export interface CreateSurveyAssistantPostgresRuntimeOptions {
|
|
28
19
|
ensureObservationalMemory?: boolean;
|
|
29
20
|
maxStoredAttachmentsPerThread?: number;
|
|
30
21
|
maxStoredBytesPerThread?: number;
|
|
31
22
|
schemaName?: string;
|
|
32
23
|
store: PostgresStore | PostgresStoreConfig;
|
|
33
24
|
}
|
|
34
|
-
declare const createSurveyAssistantPostgresRuntime: ({
|
|
35
|
-
ensureObservationalMemory,
|
|
36
|
-
maxStoredAttachmentsPerThread,
|
|
37
|
-
maxStoredBytesPerThread,
|
|
38
|
-
schemaName,
|
|
39
|
-
store: storeOrConfig
|
|
40
|
-
}: CreateSurveyAssistantPostgresRuntimeOptions) => {
|
|
25
|
+
export declare const createSurveyAssistantPostgresRuntime: ({ ensureObservationalMemory, maxStoredAttachmentsPerThread, maxStoredBytesPerThread, schemaName, store: storeOrConfig }: CreateSurveyAssistantPostgresRuntimeOptions) => {
|
|
41
26
|
storage: PostgresStore;
|
|
42
27
|
getStorage: () => Promise<PostgresStore>;
|
|
43
28
|
threadDocuments: SurveyAssistantThreadDocumentRepository;
|
|
44
29
|
};
|
|
45
30
|
//#endregion
|
|
46
|
-
export { CreateSurveyAssistantPostgresRuntimeOptions, CreateSurveyAssistantPostgresThreadDocumentRepositoryOptions, InitializeSurveyAssistantPostgresStorageOptions, SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENTS_PER_THREAD, SURVEY_ASSISTANT_DEFAULT_MAX_STORED_ATTACHMENT_BYTES_PER_THREAD, createSurveyAssistantPostgresRuntime, createSurveyAssistantPostgresThreadDocumentRepository, initializeSurveyAssistantPostgresStorage };
|
|
47
31
|
//# sourceMappingURL=storage-postgres.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-postgres.d.mts","names":[],"sources":["../src/storage/postgres.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"storage-postgres.d.mts","names":[],"sources":["../src/storage/postgres.ts"],"mappings":";;;qBAWa;qBACA;iBA0GI;EACf;EACA;;qBAGW,2CACX,SAAS,iBACT,2BAAA,eAGG,oDAAoD,QAAA;iBAwBxC;EACf,cAAc,gBAAgB,QAAQ;EACtC;EACA;EACA;;qBAGW,0DAAyD,YAAA,+BAAA,yBAAA,cAKnE,iEAA+D;iBA2FjD;EACf;EACA;EACA;EACA;EACA,OAAO,gBAAgB;;qBAGZ,yCAAwC,2BAAA,+BAAA,yBAAA,YAAA,OAAA,iBAMlD"}
|