@case-framework/survey-assistant 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -11
- package/dist/{authoring-references-X6uRaWuf.mjs → authoring-references-DYuOAdVx.mjs} +26 -2
- package/dist/authoring-references-DYuOAdVx.mjs.map +1 -0
- package/dist/{capabilities-B6tvE7fK.mjs → capabilities-DZ0a_o2y.mjs} +2 -2
- package/dist/{capabilities-B6tvE7fK.mjs.map → capabilities-DZ0a_o2y.mjs.map} +1 -1
- package/dist/{capabilities-DvSKtjAw.d.mts → capabilities-DlC1l6qy.d.mts} +4 -1
- package/dist/capabilities-DlC1l6qy.d.mts.map +1 -0
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +6 -3
- package/dist/capabilities-default.mjs.map +1 -1
- package/dist/{constants-Jw0k8ojS.d.mts → constants-56jf_4ls.d.mts} +36 -9
- package/dist/constants-56jf_4ls.d.mts.map +1 -0
- package/dist/{controller-proxy-BRDusFiO.d.mts → controller-proxy-2VH0b_5E.d.mts} +29 -4
- package/dist/controller-proxy-2VH0b_5E.d.mts.map +1 -0
- package/dist/{controller-proxy-Duxo2IFE.mjs → controller-proxy-ClsY4lFI.mjs} +74 -5
- package/dist/controller-proxy-ClsY4lFI.mjs.map +1 -0
- package/dist/{digest-BsoVq49o.d.mts → digest-BvXpeWcR.d.mts} +2 -2
- package/dist/{digest-BsoVq49o.d.mts.map → digest-BvXpeWcR.d.mts.map} +1 -1
- package/dist/digest.d.mts +1 -1
- package/dist/{engine-sPvuixWg.mjs → engine-DQrCO_ur.mjs} +392 -50
- package/dist/engine-DQrCO_ur.mjs.map +1 -0
- package/dist/engine.d.mts +2 -2
- package/dist/engine.mjs +2 -2
- package/dist/{index-MpEMQzTm.d.mts → index-B_x2IYi7.d.mts} +5 -1
- package/dist/index-B_x2IYi7.d.mts.map +1 -0
- package/dist/{index-BWNHkpkh.d.mts → index-C_x686M7.d.mts} +27 -5
- package/dist/index-C_x686M7.d.mts.map +1 -0
- package/dist/{index-TFtvBiSQ.d.mts → index-DVxVyhAu.d.mts} +31 -9
- package/dist/index-DVxVyhAu.d.mts.map +1 -0
- package/dist/{index-CUqbBjkc.d.mts → index-DZ6KBwVR.d.mts} +16 -3
- package/dist/index-DZ6KBwVR.d.mts.map +1 -0
- package/dist/{memory-thread-repository-CJkkVE2-.mjs → memory-thread-repository-Cm1BJyRw.mjs} +110 -41
- package/dist/memory-thread-repository-Cm1BJyRw.mjs.map +1 -0
- package/dist/{protocol-DV0ka9WT.mjs → protocol-7EEgcYja.mjs} +70 -97
- package/dist/protocol-7EEgcYja.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +2 -2
- package/dist/{react-VuYe-cPh.mjs → react-B_5smfiK.mjs} +145 -38
- package/dist/react-B_5smfiK.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 +6 -0
- package/dist/references/core-rules.md +6 -0
- package/dist/references/embedded-forms.md +21 -14
- package/dist/references/expressions.md +3 -0
- package/dist/references/item-types.md +37 -10
- package/dist/references/source-material-surveys.md +9 -1
- package/dist/references/survey-data-model.md +13 -0
- package/dist/request-context-BDBw4-Gw.mjs +79 -0
- package/dist/request-context-BDBw4-Gw.mjs.map +1 -0
- package/dist/request-guardrails-h4t6u8mP.mjs +129 -0
- package/dist/request-guardrails-h4t6u8mP.mjs.map +1 -0
- package/dist/server-agent.d.mts +6 -2
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +39 -24
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +21 -5
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +98 -32
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +2 -78
- package/dist/server-tasks.mjs +103 -46
- package/dist/server-tasks.mjs.map +1 -1
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +89 -21
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +136 -5
- package/dist/server.mjs.map +1 -0
- package/dist/storage-postgres.d.mts +12 -2
- package/dist/storage-postgres.d.mts.map +1 -1
- package/dist/storage-postgres.mjs +11 -6
- package/dist/storage-postgres.mjs.map +1 -1
- package/dist/tasks-COQnhSeT.d.mts +140 -0
- package/dist/tasks-COQnhSeT.d.mts.map +1 -0
- package/dist/{thread-documents-DamIq9Od.d.mts → thread-documents-BlxNjc7S.d.mts} +21 -5
- package/dist/thread-documents-BlxNjc7S.d.mts.map +1 -0
- package/dist/{thread-handlers-DpynUc64.d.mts → thread-handlers-l79JBl5m.d.mts} +38 -5
- package/dist/thread-handlers-l79JBl5m.d.mts.map +1 -0
- package/dist/{tools-Hz2p7vyv.mjs → tools-DDXaJ8Za.mjs} +257 -38
- package/dist/tools-DDXaJ8Za.mjs.map +1 -0
- package/dist/ui.d.mts +5 -3
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +91 -12
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +234 -0
- package/package.json +9 -7
- package/dist/authoring-references-Cy8J-DWt.d.mts +0 -48
- package/dist/authoring-references-Cy8J-DWt.d.mts.map +0 -1
- package/dist/authoring-references-X6uRaWuf.mjs.map +0 -1
- package/dist/capabilities-DvSKtjAw.d.mts.map +0 -1
- package/dist/constants-Jw0k8ojS.d.mts.map +0 -1
- package/dist/controller-proxy-BRDusFiO.d.mts.map +0 -1
- package/dist/controller-proxy-Duxo2IFE.mjs.map +0 -1
- package/dist/engine-sPvuixWg.mjs.map +0 -1
- package/dist/index-BWNHkpkh.d.mts.map +0 -1
- package/dist/index-CUqbBjkc.d.mts.map +0 -1
- package/dist/index-MpEMQzTm.d.mts.map +0 -1
- package/dist/index-TFtvBiSQ.d.mts.map +0 -1
- package/dist/memory-thread-repository-CJkkVE2-.mjs.map +0 -1
- package/dist/protocol-DV0ka9WT.mjs.map +0 -1
- package/dist/react-VuYe-cPh.mjs.map +0 -1
- package/dist/request-context-jcmXT_Q2.mjs +0 -44
- package/dist/request-context-jcmXT_Q2.mjs.map +0 -1
- package/dist/request-guardrails-C59IWnH8.mjs +0 -73
- package/dist/request-guardrails-C59IWnH8.mjs.map +0 -1
- package/dist/server-tasks.d.mts.map +0 -1
- package/dist/thread-documents-DamIq9Od.d.mts.map +0 -1
- package/dist/thread-handlers-DpynUc64.d.mts.map +0 -1
- package/dist/tools-Hz2p7vyv.mjs.map +0 -1
package/dist/server-tasks.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { C as surveyAssistantTaskRequestSchema } from "./protocol-
|
|
1
|
+
import { C as surveyAssistantTaskRequestSchema } from "./protocol-7EEgcYja.mjs";
|
|
2
2
|
import { n as SURVEY_ASSISTANT_TASK_AGENT_ID } from "./constants-CFUWrRtl.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { d as readSurveyAssistantRequestJson, u as SurveyAssistantRequestError } from "./request-guardrails-h4t6u8mP.mjs";
|
|
4
|
+
import { r as surveyAuthoringReferences } from "./authoring-references-DYuOAdVx.mjs";
|
|
4
5
|
import { z } from "zod";
|
|
5
6
|
import { RequestContext } from "@mastra/core/request-context";
|
|
6
7
|
import { Agent } from "@mastra/core/agent";
|
|
@@ -68,6 +69,27 @@ const translationsSchema = z.object({ translations: z.record(z.string(), z.recor
|
|
|
68
69
|
const clampLimit = (value, fallback, maximum) => Math.min(Math.max(1, value ?? fallback), maximum);
|
|
69
70
|
const sanitizeCodingKey = (value) => value.trim().replace(/[.\s-]+/g, "_").replace(/[^A-Za-z0-9_]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
|
|
70
71
|
const getCodingKeyIdentity = (value) => sanitizeCodingKey(value).toLocaleLowerCase();
|
|
72
|
+
const getNumberedKeyParts = (value) => {
|
|
73
|
+
const match = /^(.+?)_(\d+)$/.exec(getCodingKeyIdentity(value));
|
|
74
|
+
return match ? {
|
|
75
|
+
stem: match[1],
|
|
76
|
+
number: Number(match[2])
|
|
77
|
+
} : void 0;
|
|
78
|
+
};
|
|
79
|
+
const isUnsupportedFocusedItemSequence = (candidate, input, context) => {
|
|
80
|
+
const candidateParts = getNumberedKeyParts(candidate);
|
|
81
|
+
const focusItem = context.focus?.item;
|
|
82
|
+
if (!candidateParts || !focusItem) return false;
|
|
83
|
+
if (![
|
|
84
|
+
input.currentKey,
|
|
85
|
+
input.draftKey,
|
|
86
|
+
focusItem.key
|
|
87
|
+
].map(getNumberedKeyParts).find((parts) => parts?.stem === candidateParts.stem && parts.number < candidateParts.number)) return false;
|
|
88
|
+
return !context.naming?.keyExamples.some((example) => {
|
|
89
|
+
const exampleParts = getNumberedKeyParts(example.key);
|
|
90
|
+
return example.itemType === focusItem.itemType && exampleParts?.stem === candidateParts.stem;
|
|
91
|
+
});
|
|
92
|
+
};
|
|
71
93
|
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.";
|
|
72
94
|
const runSurveyAssistantSuggestItemKeyTask = async (input, options) => {
|
|
73
95
|
const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);
|
|
@@ -79,9 +101,11 @@ const runSurveyAssistantSuggestItemKeyTask = async (input, options) => {
|
|
|
79
101
|
instructions: [
|
|
80
102
|
"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.",
|
|
81
103
|
"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.",
|
|
104
|
+
"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.",
|
|
82
105
|
"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.",
|
|
83
106
|
"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.",
|
|
84
107
|
"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.",
|
|
108
|
+
"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.",
|
|
85
109
|
"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.",
|
|
86
110
|
"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.",
|
|
87
111
|
"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.",
|
|
@@ -116,7 +140,7 @@ const runSurveyAssistantSuggestItemKeyTask = async (input, options) => {
|
|
|
116
140
|
].flatMap((suggestion) => {
|
|
117
141
|
const text = sanitizeCodingKey(suggestion.text);
|
|
118
142
|
const identity = getCodingKeyIdentity(text);
|
|
119
|
-
if (!text || excluded.has(identity) || seen.has(identity)) return [];
|
|
143
|
+
if (!text || excluded.has(identity) || seen.has(identity) || isUnsupportedFocusedItemSequence(text, input, options.context)) return [];
|
|
120
144
|
seen.add(identity);
|
|
121
145
|
return [{
|
|
122
146
|
...suggestion,
|
|
@@ -194,58 +218,91 @@ const runSurveyAssistantTranslateContentTask = async (input, options) => {
|
|
|
194
218
|
return { translations };
|
|
195
219
|
};
|
|
196
220
|
const MAX_TASK_REQUEST_BYTES = 512 * 1024;
|
|
221
|
+
const DEFAULT_MAX_TASK_CONCURRENT_REQUESTS = 4;
|
|
222
|
+
const DEFAULT_MAX_TASK_DURATION_MS = 6e4;
|
|
197
223
|
const taskErrorResponse = (error) => {
|
|
198
|
-
const status = typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" ? error.status : 400;
|
|
199
|
-
const message = error instanceof
|
|
224
|
+
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;
|
|
225
|
+
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.";
|
|
200
226
|
return Response.json({
|
|
201
|
-
code: status === 401 || status === 403 ? "authorization_failed" : "request_failed",
|
|
227
|
+
code: status === 401 || status === 403 || status === 404 ? "authorization_failed" : "request_failed",
|
|
202
228
|
error: message
|
|
203
229
|
}, { status });
|
|
204
230
|
};
|
|
205
|
-
const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError, isEnabled, providerOptions, resolveModel }) =>
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
identity,
|
|
231
|
+
const createSurveyAssistantTaskHandler = ({ agent, authorize, getReadinessError, isEnabled, maxConcurrentRequests = DEFAULT_MAX_TASK_CONCURRENT_REQUESTS, maxDurationMs = DEFAULT_MAX_TASK_DURATION_MS, onTaskMetrics, providerOptions, resolveModel }) => {
|
|
232
|
+
const concurrency = Number.isInteger(maxConcurrentRequests) && maxConcurrentRequests > 0 ? maxConcurrentRequests : DEFAULT_MAX_TASK_CONCURRENT_REQUESTS;
|
|
233
|
+
const duration = Number.isFinite(maxDurationMs) && maxDurationMs > 0 ? maxDurationMs : DEFAULT_MAX_TASK_DURATION_MS;
|
|
234
|
+
let activeRequests = 0;
|
|
235
|
+
return async (request) => {
|
|
236
|
+
if (activeRequests >= concurrency) return Response.json({
|
|
237
|
+
code: "rate_limited",
|
|
238
|
+
error: "The survey assistant is handling too many tasks. Try again shortly."
|
|
239
|
+
}, { status: 429 });
|
|
240
|
+
activeRequests += 1;
|
|
241
|
+
const startedAt = Date.now();
|
|
242
|
+
let metricsIdentity;
|
|
243
|
+
let metricsTaskId = "unknown";
|
|
244
|
+
let completed = false;
|
|
245
|
+
try {
|
|
246
|
+
if (isEnabled && !await isEnabled(request)) return Response.json({
|
|
247
|
+
code: "request_failed",
|
|
248
|
+
error: "Survey assistant is disabled."
|
|
249
|
+
}, { status: 404 });
|
|
250
|
+
const task = surveyAssistantTaskRequestSchema.parse(await readSurveyAssistantRequestJson(request, MAX_TASK_REQUEST_BYTES));
|
|
251
|
+
metricsTaskId = task.taskId;
|
|
252
|
+
const identity = await authorize({
|
|
228
253
|
request,
|
|
229
|
-
|
|
254
|
+
requestedResourceId: task.resourceId,
|
|
255
|
+
requestedSurveyId: task.surveyId
|
|
230
256
|
});
|
|
231
|
-
if (!
|
|
257
|
+
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 });
|
|
258
|
+
metricsIdentity = {
|
|
259
|
+
resourceId: identity.resourceId.trim(),
|
|
260
|
+
...identity.surveyId?.trim() ? { surveyId: identity.surveyId.trim() } : {}
|
|
261
|
+
};
|
|
262
|
+
const readinessError = await getReadinessError?.(request);
|
|
263
|
+
if (readinessError) return Response.json({
|
|
232
264
|
code: "request_failed",
|
|
233
|
-
error:
|
|
234
|
-
}, { status:
|
|
235
|
-
requestContext
|
|
265
|
+
error: readinessError
|
|
266
|
+
}, { status: 503 });
|
|
267
|
+
const requestContext = new RequestContext();
|
|
268
|
+
if (resolveModel) {
|
|
269
|
+
const modelSelection = await resolveModel({
|
|
270
|
+
identity: metricsIdentity,
|
|
271
|
+
request,
|
|
272
|
+
requestedModelId: task.modelId
|
|
273
|
+
});
|
|
274
|
+
if (!modelSelection) return Response.json({
|
|
275
|
+
code: "request_failed",
|
|
276
|
+
error: "The selected survey assistant model is unavailable."
|
|
277
|
+
}, { status: 400 });
|
|
278
|
+
requestContext.set("modelSelection", modelSelection);
|
|
279
|
+
}
|
|
280
|
+
const resolvedAgent = typeof agent === "function" ? await agent() : agent;
|
|
281
|
+
const runtime = {
|
|
282
|
+
abortSignal: AbortSignal.any([request.signal, AbortSignal.timeout(duration)]),
|
|
283
|
+
agent: resolvedAgent,
|
|
284
|
+
context: task.context,
|
|
285
|
+
mode: task.mode,
|
|
286
|
+
requestContext,
|
|
287
|
+
providerOptions
|
|
288
|
+
};
|
|
289
|
+
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);
|
|
290
|
+
completed = true;
|
|
291
|
+
return Response.json(result);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return taskErrorResponse(error);
|
|
294
|
+
} finally {
|
|
295
|
+
activeRequests = Math.max(0, activeRequests - 1);
|
|
296
|
+
if (metricsIdentity) try {
|
|
297
|
+
onTaskMetrics?.({
|
|
298
|
+
durationMs: Date.now() - startedAt,
|
|
299
|
+
identity: metricsIdentity,
|
|
300
|
+
status: completed ? "completed" : "failed",
|
|
301
|
+
taskId: metricsTaskId
|
|
302
|
+
});
|
|
303
|
+
} catch {}
|
|
236
304
|
}
|
|
237
|
-
|
|
238
|
-
agent: typeof agent === "function" ? await agent() : agent,
|
|
239
|
-
context: task.context,
|
|
240
|
-
mode: task.mode,
|
|
241
|
-
requestContext,
|
|
242
|
-
providerOptions
|
|
243
|
-
};
|
|
244
|
-
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);
|
|
245
|
-
return Response.json(result);
|
|
246
|
-
} catch (error) {
|
|
247
|
-
return taskErrorResponse(error);
|
|
248
|
-
}
|
|
305
|
+
};
|
|
249
306
|
};
|
|
250
307
|
//#endregion
|
|
251
308
|
export { createSurveyAssistantTaskAgent, createSurveyAssistantTaskHandler, runSurveyAssistantSuggestItemKeyTask, runSurveyAssistantSuggestItemLabelTask, runSurveyAssistantTask, runSurveyAssistantTranslateContentTask };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-tasks.mjs","names":[],"sources":["../src/server/tasks.ts"],"sourcesContent":["import { Agent, type AgentConfig, type AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport { surveyAssistantTaskRequestSchema } from \"../protocol\";\nimport type {\n SurveyAssistantSuggestItemKeyInput,\n SurveyAssistantSuggestItemKeyResult,\n SurveyAssistantKeySuggestionCategory,\n SurveyAssistantSuggestItemLabelInput,\n SurveyAssistantSuggestItemLabelResult,\n SurveyAssistantTaskInvocationMode,\n SurveyAssistantTaskContext,\n SurveyAssistantTranslateContentInput,\n SurveyAssistantTranslateContentResult,\n} from \"../protocol\";\nimport {\n surveyAuthoringReferences,\n type SurveyAuthoringReferenceTopic,\n} from \"./authoring-references\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport { SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\n\ntype SurveyAssistantTaskAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n>;\n\nexport interface CreateSurveyAssistantTaskAgentOptions {\n model: SurveyAssistantTaskAgentConfig[\"model\"];\n}\n\nexport const createSurveyAssistantTaskAgent = ({ model }: CreateSurveyAssistantTaskAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_TASK_AGENT_ID,\n name: \"Survey Assistant Tasks\",\n instructions:\n \"Perform the supplied bounded survey-authoring task and return only its requested structured output.\",\n model,\n });\n\nexport interface RunSurveyAssistantTaskOptions<TSchema extends z.ZodType> {\n agent: Pick<Agent, \"generate\">;\n taskId: string;\n input: unknown;\n context: SurveyAssistantTaskContext;\n schema: TSchema;\n instructions: readonly string[];\n referenceTopics?: readonly SurveyAuthoringReferenceTopic[];\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst BASE_TASK_INSTRUCTIONS = [\n \"You perform one bounded CASE Survey Editor AI task and return only the requested structured result.\",\n \"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.\",\n \"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.\",\n \"Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.\",\n] as const;\n\nexport const runSurveyAssistantTask = async <TSchema extends z.ZodType>({\n agent,\n taskId,\n input,\n context,\n schema,\n instructions,\n referenceTopics = [],\n requestContext,\n providerOptions,\n abortSignal,\n}: RunSurveyAssistantTaskOptions<TSchema>): Promise<z.output<TSchema>> => {\n const references = referenceTopics.map((topic) => ({\n topic,\n title: surveyAuthoringReferences[topic].title,\n content: surveyAuthoringReferences[topic].content,\n }));\n const response = await agent.generate(\n JSON.stringify({ taskId, input, currentSurveyContext: context }),\n {\n instructions: [\n ...BASE_TASK_INSTRUCTIONS,\n ...instructions,\n ...references.map((entry) => `Reference: ${entry.title}\\n${entry.content}`),\n ],\n activeTools: [],\n inputProcessors: [],\n maxSteps: 1,\n structuredOutput: {\n schema,\n errorStrategy: \"strict\",\n },\n ...(requestContext ? { requestContext } : {}),\n ...(providerOptions ? { providerOptions } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n },\n );\n\n return schema.parse(response.object);\n};\n\nconst keySuggestionValueSchema = z.object({\n text: z.string().min(1),\n rationale: z.string().optional(),\n});\n\nconst keySuggestionCategorySchema = z.enum([\"survey-pattern\", \"compact\", \"preferred\", \"fair\"]);\n\nconst keySuggestionSchema = z.object({\n surveyPattern: keySuggestionValueSchema.describe(\n \"A key that follows the strongest naming and numbering pattern in the current survey.\",\n ),\n compact: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(2)\n .max(5)\n .regex(/^[A-Z][A-Z0-9]{1,4}$/)\n .describe(\"A recognizable 2-5 character uppercase abbreviation.\"),\n }),\n preferred: keySuggestionValueSchema.describe(\n \"The key the model considers clearest without a category-specific naming constraint.\",\n ),\n fair: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(1)\n .max(32)\n .regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/)\n .describe(\"A FAIR-by-design lowercase snake_case variable name.\"),\n }),\n alternatives: z\n .array(\n keySuggestionValueSchema.extend({\n category: keySuggestionCategorySchema,\n }),\n )\n .max(2),\n});\n\nconst labelSuggestionSchema = z.object({\n suggestions: z.array(\n z.object({\n text: z.string().min(1),\n }),\n ),\n});\n\nconst translationsSchema = z.object({\n translations: z.record(z.string(), z.record(z.string(), z.string())),\n});\n\nexport interface RunSurveyAssistantBuiltInTaskOptions {\n agent: Pick<Agent, \"generate\">;\n context: SurveyAssistantTaskContext;\n mode?: SurveyAssistantTaskInvocationMode;\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst clampLimit = (value: number | undefined, fallback: number, maximum: number) =>\n Math.min(Math.max(1, value ?? fallback), maximum);\n\nconst sanitizeCodingKey = (value: string) =>\n value\n .trim()\n .replace(/[.\\s-]+/g, \"_\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst getCodingKeyIdentity = (value: string) => sanitizeCodingKey(value).toLocaleLowerCase();\n\nconst invocationInstruction = (mode: SurveyAssistantTaskInvocationMode | undefined) =>\n mode === \"background\"\n ? \"This is a background invocation. Be efficient, but do not relax task conventions, completeness, or output quality.\"\n : \"This is an explicit user invocation. Prioritize quality and useful variation.\";\n\nexport const runSurveyAssistantSuggestItemKeyTask = async (\n input: SurveyAssistantSuggestItemKeyInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemKeyResult> => {\n const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-key\",\n input,\n schema: keySuggestionSchema,\n instructions: [\n \"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.\",\n \"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.\",\n \"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.\",\n \"Return one fair key following these FAIR-by-design rules: start with a letter; use lowercase ASCII letters, digits, and underscores only; use lowercase snake_case; stay at or below 32 characters; avoid programming/database reserved words; prefer a stable, language-neutral English concept name; use established instrument prefixes and sortable item numbers when applicable; distinguish raw from derived variables. Meaning belongs in metadata, so do not turn it into a sentence.\",\n `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.`,\n \"Never repeat the same suggestion, including case-only or punctuation-only variations.\",\n \"Do not return the current key, a sibling key, or a semantically unrelated abbreviation.\",\n `Return between 4 and ${maxSuggestions} distinct suggestions in total.`,\n invocationInstruction(options.mode),\n ],\n });\n\n const excluded = new Set(\n [input.currentKey, ...input.siblingKeys].map(getCodingKeyIdentity).filter(Boolean),\n );\n const seen = new Set<string>();\n const categorizedSuggestions: Array<{\n text: string;\n rationale?: string;\n category: SurveyAssistantKeySuggestionCategory;\n }> = [\n { ...result.surveyPattern, category: \"survey-pattern\" },\n { ...result.compact, category: \"compact\" },\n { ...result.preferred, category: \"preferred\" },\n { ...result.fair, category: \"fair\" },\n ...result.alternatives,\n ];\n const suggestions = categorizedSuggestions\n .flatMap((suggestion) => {\n const text = sanitizeCodingKey(suggestion.text);\n const identity = getCodingKeyIdentity(text);\n if (!text || excluded.has(identity) || seen.has(identity)) return [];\n seen.add(identity);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions);\n return { suggestions };\n};\n\nexport const runSurveyAssistantSuggestItemLabelTask = async (\n input: SurveyAssistantSuggestItemLabelInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemLabelResult> => {\n const maxSuggestions = clampLimit(input.maxSuggestions, 3, 10);\n const locale = input.locale ?? options.context.survey.selectedLocale;\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-label\",\n input,\n schema: labelSuggestionSchema,\n instructions: [\n \"Suggest concise editor-only item labels, not coding keys and not respondent-facing question text.\",\n \"Infer the item's purpose from its type, draft label, visible content, hierarchy, siblings, and descendants.\",\n \"Use currentSurveyContext.naming.labelExamples to infer established capitalization, prefixes, abbreviations, delimiters, and typical length.\",\n \"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.\",\n \"Do not copy the subject matter of an unrelated example merely to imitate its style, and do not return an existing unrelated label verbatim.\",\n `Write labels in locale ${locale}.`,\n `Return at most ${maxSuggestions} distinct, specific, human-readable suggestions.`,\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"core-rules\"],\n });\n\n const normalizeLabel = (value: string) => value.trim().toLocaleLowerCase();\n const excludedLabels = new Set([\n normalizeLabel(input.draftLabel),\n ...(options.context.naming?.labelExamples ?? []).map((example) =>\n normalizeLabel(example.label),\n ),\n ]);\n const seen = new Set<string>();\n return {\n suggestions: result.suggestions\n .flatMap((suggestion) => {\n const text = suggestion.text.trim();\n const normalizedText = normalizeLabel(text);\n if (!text || excludedLabels.has(normalizedText) || seen.has(normalizedText)) return [];\n seen.add(normalizedText);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions),\n };\n};\n\nconst getProtectedTokens = (value: string) =>\n value.match(/\\{\\{[^{}]+\\}\\}|\\{[^{}]+\\}|\\$\\{[^{}]+\\}|%\\d*\\$?[a-z]/gi) ?? [];\n\nexport const runSurveyAssistantTranslateContentTask = async (\n input: SurveyAssistantTranslateContentInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantTranslateContentResult> => {\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"translate-content\",\n input,\n schema: translationsSchema,\n instructions: [\n \"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.\",\n `Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(\", \")}.`,\n \"Use currentSurveyContext.translation.examples as a terminology and style reference when relevant. The supplied source entries remain authoritative.\",\n \"Preserve meaning, register, survey terminology, punctuation, line breaks, response semantics, placeholders, interpolation tokens, URLs, and identifiers that should not be translated.\",\n \"Keep repeated terminology consistent across all entries and target locales. Do not use a neighboring translation when its meaning differs.\",\n \"Return plain strings keyed first by target locale and then by the original entry id. Return every requested locale and entry exactly once.\",\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"localization\"],\n });\n\n const translations: SurveyAssistantTranslateContentResult[\"translations\"] = {};\n for (const locale of input.targetLocales) {\n const entries = result.translations[locale];\n if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);\n const translatedEntries: Record<string, string> = {};\n for (const entry of input.entries) {\n const translation = entries[entry.id];\n if (typeof translation !== \"string\" || translation.trim().length === 0) {\n throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);\n }\n const sourceTokens = getProtectedTokens(entry.text).sort();\n const translatedTokens = getProtectedTokens(translation).sort();\n if (sourceTokens.join(\"\\u0000\") !== translatedTokens.join(\"\\u0000\")) {\n throw new Error(\n `Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`,\n );\n }\n translatedEntries[entry.id] = translation;\n }\n translations[locale] = translatedEntries;\n }\n return { translations };\n};\n\nconst MAX_TASK_REQUEST_BYTES = 512 * 1024;\n\nexport interface SurveyAssistantTaskAuthorizedIdentity {\n resourceId: string;\n}\n\nexport interface SurveyAssistantTaskModelResolutionInput {\n identity: SurveyAssistantTaskAuthorizedIdentity;\n request: Request;\n requestedModelId?: string;\n}\n\nexport interface CreateSurveyAssistantTaskHandlerOptions {\n agent:\n | Pick<Agent, \"generate\">\n | (() => Pick<Agent, \"generate\"> | Promise<Pick<Agent, \"generate\">>);\n authorize(\n request: Request,\n ): SurveyAssistantTaskAuthorizedIdentity | Promise<SurveyAssistantTaskAuthorizedIdentity>;\n getReadinessError?(request: Request): string | null | Promise<string | null>;\n isEnabled?(request: Request): boolean | Promise<boolean>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel?(\n input: SurveyAssistantTaskModelResolutionInput,\n ):\n | SurveyAssistantModelSelection\n | null\n | undefined\n | Promise<SurveyAssistantModelSelection | null | undefined>;\n}\n\nconst taskErrorResponse = (error: unknown) => {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : 400;\n const message =\n error instanceof Error ? error.message : \"The survey assistant task could not be completed.\";\n return Response.json(\n {\n code: status === 401 || status === 403 ? \"authorization_failed\" : \"request_failed\",\n error: message,\n },\n { status },\n );\n};\n\nexport const createSurveyAssistantTaskHandler =\n ({\n agent,\n authorize,\n getReadinessError,\n isEnabled,\n providerOptions,\n resolveModel,\n }: CreateSurveyAssistantTaskHandlerOptions) =>\n async (request: Request): Promise<Response> => {\n try {\n if (isEnabled && !(await isEnabled(request))) {\n return Response.json(\n { code: \"request_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n const identity = await authorize(request);\n if (!identity?.resourceId?.trim()) {\n throw Object.assign(new Error(\"The host returned an invalid task identity.\"), {\n status: 500,\n });\n }\n\n const readinessError = await getReadinessError?.(request);\n if (readinessError) {\n return Response.json({ code: \"request_failed\", error: readinessError }, { status: 503 });\n }\n\n const text = await request.text();\n if (new TextEncoder().encode(text).byteLength > MAX_TASK_REQUEST_BYTES) {\n return Response.json(\n { code: \"request_failed\", error: \"The survey assistant task request is too large.\" },\n { status: 413 },\n );\n }\n const task = surveyAssistantTaskRequestSchema.parse(JSON.parse(text));\n\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n if (resolveModel) {\n const modelSelection = await resolveModel({\n identity,\n request,\n requestedModelId: task.modelId,\n });\n if (!modelSelection) {\n return Response.json(\n {\n code: \"request_failed\",\n error: \"The selected survey assistant model is unavailable.\",\n },\n { status: 400 },\n );\n }\n requestContext.set(\"modelSelection\", modelSelection);\n }\n\n const resolvedAgent = typeof agent === \"function\" ? await agent() : agent;\n const runtime: RunSurveyAssistantBuiltInTaskOptions = {\n agent: resolvedAgent,\n context: task.context,\n mode: task.mode,\n requestContext,\n providerOptions,\n };\n const result =\n task.taskId === \"suggest-item-key\"\n ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime)\n : task.taskId === \"suggest-item-label\"\n ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime)\n : await runSurveyAssistantTranslateContentTask(task.input, runtime);\n return Response.json(result);\n } catch (error) {\n return taskErrorResponse(error);\n }\n };\n"],"mappings":";;;;;;;AAoCA,MAAa,kCAAkC,EAAE,YAC/C,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cACE;CACF;CACD,CAAC;AAeJ,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD;AAED,MAAa,yBAAyB,OAAkC,EACtE,OACA,QACA,OACA,SACA,QACA,cACA,kBAAkB,EAAE,EACpB,gBACA,iBACA,kBACwE;CACxE,MAAM,aAAa,gBAAgB,KAAK,WAAW;EACjD;EACA,OAAO,0BAA0B,OAAO;EACxC,SAAS,0BAA0B,OAAO;EAC3C,EAAE;CACH,MAAM,WAAW,MAAM,MAAM,SAC3B,KAAK,UAAU;EAAE;EAAQ;EAAO,sBAAsB;EAAS,CAAC,EAChE;EACE,cAAc;GACZ,GAAG;GACH,GAAG;GACH,GAAG,WAAW,KAAK,UAAU,cAAc,MAAM,MAAM,IAAI,MAAM,UAAU;GAC5E;EACD,aAAa,EAAE;EACf,iBAAiB,EAAE;EACnB,UAAU;EACV,kBAAkB;GAChB;GACA,eAAe;GAChB;EACD,GAAI,iBAAiB,EAAE,gBAAgB,GAAG,EAAE;EAC5C,GAAI,kBAAkB,EAAE,iBAAiB,GAAG,EAAE;EAC9C,GAAI,cAAc,EAAE,aAAa,GAAG,EAAE;EACvC,CACF;AAED,QAAO,OAAO,MAAM,SAAS,OAAO;;AAGtC,MAAM,2BAA2B,EAAE,OAAO;CACxC,MAAM,EAAE,QAAQ,CAAC,IAAI,EAAE;CACvB,WAAW,EAAE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E,EAAE,QAAQ,KAAK,CAAC;EAG1F,MAAM,OAAO,MAAM,QAAQ,MAAM;AACjC,MAAI,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC,aAAa,uBAC9C,QAAO,SAAS,KACd;GAAE,MAAM;GAAkB,OAAO;GAAmD,EACpF,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,iCAAiC,MAAM,KAAK,MAAM,KAAK,CAAC;EAErE,MAAM,iBAAiB,IAAI,gBAA+C;AAC1E,MAAI,cAAc;GAChB,MAAM,iBAAiB,MAAM,aAAa;IACxC;IACA;IACA,kBAAkB,KAAK;IACxB,CAAC;AACF,OAAI,CAAC,eACH,QAAO,SAAS,KACd;IACE,MAAM;IACN,OAAO;IACR,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,kBAAe,IAAI,kBAAkB,eAAe;;EAItD,MAAM,UAAgD;GACpD,OAFoB,OAAO,UAAU,aAAa,MAAM,OAAO,GAAG;GAGlE,SAAS,KAAK;GACd,MAAM,KAAK;GACX;GACA;GACD;EACD,MAAM,SACJ,KAAK,WAAW,qBACZ,MAAM,qCAAqC,KAAK,OAAO,QAAQ,GAC/D,KAAK,WAAW,uBACd,MAAM,uCAAuC,KAAK,OAAO,QAAQ,GACjE,MAAM,uCAAuC,KAAK,OAAO,QAAQ;AACzE,SAAO,SAAS,KAAK,OAAO;UACrB,OAAO;AACd,SAAO,kBAAkB,MAAM"}
|
|
1
|
+
{"version":3,"file":"server-tasks.mjs","names":[],"sources":["../src/server/tasks.ts"],"sourcesContent":["import { Agent, type AgentConfig, type AgentExecutionOptions } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { z } from \"zod\";\nimport { surveyAssistantTaskRequestSchema } from \"../protocol\";\nimport type {\n SurveyAssistantSuggestItemKeyInput,\n SurveyAssistantSuggestItemKeyResult,\n SurveyAssistantKeySuggestionCategory,\n SurveyAssistantSuggestItemLabelInput,\n SurveyAssistantSuggestItemLabelResult,\n SurveyAssistantTaskInvocationMode,\n SurveyAssistantTaskContext,\n SurveyAssistantTranslateContentInput,\n SurveyAssistantTranslateContentResult,\n} from \"../protocol\";\nimport {\n surveyAuthoringReferences,\n type SurveyAuthoringReferenceTopic,\n} from \"./authoring-references\";\nimport type {\n SurveyAssistantModelSelection,\n SurveyAssistantRequestContext,\n} from \"./request-context\";\nimport { SURVEY_ASSISTANT_TASK_AGENT_ID } from \"./constants\";\nimport { readSurveyAssistantRequestJson, SurveyAssistantRequestError } from \"./request-guardrails\";\n\ntype SurveyAssistantTaskAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n>;\n\nexport interface CreateSurveyAssistantTaskAgentOptions {\n model: SurveyAssistantTaskAgentConfig[\"model\"];\n}\n\nexport const createSurveyAssistantTaskAgent = ({ model }: CreateSurveyAssistantTaskAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_TASK_AGENT_ID,\n Record<string, never>,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_TASK_AGENT_ID,\n name: \"Survey Assistant Tasks\",\n instructions:\n \"Perform the supplied bounded survey-authoring task and return only its requested structured output.\",\n model,\n });\n\nexport interface RunSurveyAssistantTaskOptions<TSchema extends z.ZodType> {\n agent: Pick<Agent, \"generate\">;\n taskId: string;\n input: unknown;\n context: SurveyAssistantTaskContext;\n schema: TSchema;\n instructions: readonly string[];\n referenceTopics?: readonly SurveyAuthoringReferenceTopic[];\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst BASE_TASK_INSTRUCTIONS = [\n \"You perform one bounded CASE Survey Editor AI task and return only the requested structured result.\",\n \"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.\",\n \"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.\",\n \"Keep generated respondent-facing wording neutral, concise, and consistent with the requested locale and surrounding survey content.\",\n] as const;\n\nexport const runSurveyAssistantTask = async <TSchema extends z.ZodType>({\n agent,\n taskId,\n input,\n context,\n schema,\n instructions,\n referenceTopics = [],\n requestContext,\n providerOptions,\n abortSignal,\n}: RunSurveyAssistantTaskOptions<TSchema>): Promise<z.output<TSchema>> => {\n const references = referenceTopics.map((topic) => ({\n topic,\n title: surveyAuthoringReferences[topic].title,\n content: surveyAuthoringReferences[topic].content,\n }));\n const response = await agent.generate(\n JSON.stringify({ taskId, input, currentSurveyContext: context }),\n {\n instructions: [\n ...BASE_TASK_INSTRUCTIONS,\n ...instructions,\n ...references.map((entry) => `Reference: ${entry.title}\\n${entry.content}`),\n ],\n activeTools: [],\n inputProcessors: [],\n maxSteps: 1,\n structuredOutput: {\n schema,\n errorStrategy: \"strict\",\n },\n ...(requestContext ? { requestContext } : {}),\n ...(providerOptions ? { providerOptions } : {}),\n ...(abortSignal ? { abortSignal } : {}),\n },\n );\n\n return schema.parse(response.object);\n};\n\nconst keySuggestionValueSchema = z.object({\n text: z.string().min(1),\n rationale: z.string().optional(),\n});\n\nconst keySuggestionCategorySchema = z.enum([\"survey-pattern\", \"compact\", \"preferred\", \"fair\"]);\n\nconst keySuggestionSchema = z.object({\n surveyPattern: keySuggestionValueSchema.describe(\n \"A key that follows the strongest naming and numbering pattern in the current survey.\",\n ),\n compact: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(2)\n .max(5)\n .regex(/^[A-Z][A-Z0-9]{1,4}$/)\n .describe(\"A recognizable 2-5 character uppercase abbreviation.\"),\n }),\n preferred: keySuggestionValueSchema.describe(\n \"The key the model considers clearest without a category-specific naming constraint.\",\n ),\n fair: keySuggestionValueSchema.extend({\n text: z\n .string()\n .min(1)\n .max(32)\n .regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/)\n .describe(\"A FAIR-by-design lowercase snake_case variable name.\"),\n }),\n alternatives: z\n .array(\n keySuggestionValueSchema.extend({\n category: keySuggestionCategorySchema,\n }),\n )\n .max(2),\n});\n\nconst labelSuggestionSchema = z.object({\n suggestions: z.array(\n z.object({\n text: z.string().min(1),\n }),\n ),\n});\n\nconst translationsSchema = z.object({\n translations: z.record(z.string(), z.record(z.string(), z.string())),\n});\n\nexport interface RunSurveyAssistantBuiltInTaskOptions {\n agent: Pick<Agent, \"generate\">;\n context: SurveyAssistantTaskContext;\n mode?: SurveyAssistantTaskInvocationMode;\n requestContext?: RequestContext<SurveyAssistantRequestContext>;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n abortSignal?: AbortSignal;\n}\n\nconst clampLimit = (value: number | undefined, fallback: number, maximum: number) =>\n Math.min(Math.max(1, value ?? fallback), maximum);\n\nconst sanitizeCodingKey = (value: string) =>\n value\n .trim()\n .replace(/[.\\s-]+/g, \"_\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst getCodingKeyIdentity = (value: string) => sanitizeCodingKey(value).toLocaleLowerCase();\n\nconst getNumberedKeyParts = (value: string) => {\n const match = /^(.+?)_(\\d+)$/.exec(getCodingKeyIdentity(value));\n return match ? { stem: match[1], number: Number(match[2]) } : undefined;\n};\n\nconst isUnsupportedFocusedItemSequence = (\n candidate: string,\n input: SurveyAssistantSuggestItemKeyInput,\n context: SurveyAssistantTaskContext,\n) => {\n const candidateParts = getNumberedKeyParts(candidate);\n const focusItem = context.focus?.item;\n if (!candidateParts || !focusItem) return false;\n\n const focusedKeyParts = [input.currentKey, input.draftKey, focusItem.key]\n .map(getNumberedKeyParts)\n .find((parts) => parts?.stem === candidateParts.stem && parts.number < candidateParts.number);\n if (!focusedKeyParts) return false;\n\n return !context.naming?.keyExamples.some((example) => {\n const exampleParts = getNumberedKeyParts(example.key);\n return example.itemType === focusItem.itemType && exampleParts?.stem === candidateParts.stem;\n });\n};\n\nconst invocationInstruction = (mode: SurveyAssistantTaskInvocationMode | undefined) =>\n mode === \"background\"\n ? \"This is a background invocation. Be efficient, but do not relax task conventions, completeness, or output quality.\"\n : \"This is an explicit user invocation. Prioritize quality and useful variation.\";\n\nexport const runSurveyAssistantSuggestItemKeyTask = async (\n input: SurveyAssistantSuggestItemKeyInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemKeyResult> => {\n const maxSuggestions = Math.min(Math.max(4, input.maxSuggestions ?? 6), 6);\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-key\",\n input,\n schema: keySuggestionSchema,\n instructions: [\n \"Generate coding keys for the focused survey item, not editor labels or respondent-facing text.\",\n \"Infer the dominant topic from the focused item's visible text, descendants, hierarchy, and draft key.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"Return one compact key: a recognizable 2-5 character uppercase abbreviation using only A-Z and digits.\",\n \"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.\",\n \"Return one fair key following these FAIR-by-design rules: start with a letter; use lowercase ASCII letters, digits, and underscores only; use lowercase snake_case; stay at or below 32 characters; avoid programming/database reserved words; prefer a stable, language-neutral English concept name; use established instrument prefixes and sortable item numbers when applicable; distinguish raw from derived variables. Meaning belongs in metadata, so do not turn it into a sentence.\",\n `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.`,\n \"Never repeat the same suggestion, including case-only or punctuation-only variations.\",\n \"Do not return the current key, a sibling key, or a semantically unrelated abbreviation.\",\n `Return between 4 and ${maxSuggestions} distinct suggestions in total.`,\n invocationInstruction(options.mode),\n ],\n });\n\n const excluded = new Set(\n [input.currentKey, ...input.siblingKeys].map(getCodingKeyIdentity).filter(Boolean),\n );\n const seen = new Set<string>();\n const categorizedSuggestions: Array<{\n text: string;\n rationale?: string;\n category: SurveyAssistantKeySuggestionCategory;\n }> = [\n { ...result.surveyPattern, category: \"survey-pattern\" },\n { ...result.compact, category: \"compact\" },\n { ...result.preferred, category: \"preferred\" },\n { ...result.fair, category: \"fair\" },\n ...result.alternatives,\n ];\n const suggestions = categorizedSuggestions\n .flatMap((suggestion) => {\n const text = sanitizeCodingKey(suggestion.text);\n const identity = getCodingKeyIdentity(text);\n if (\n !text ||\n excluded.has(identity) ||\n seen.has(identity) ||\n isUnsupportedFocusedItemSequence(text, input, options.context)\n ) {\n return [];\n }\n seen.add(identity);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions);\n return { suggestions };\n};\n\nexport const runSurveyAssistantSuggestItemLabelTask = async (\n input: SurveyAssistantSuggestItemLabelInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantSuggestItemLabelResult> => {\n const maxSuggestions = clampLimit(input.maxSuggestions, 3, 10);\n const locale = input.locale ?? options.context.survey.selectedLocale;\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"suggest-item-label\",\n input,\n schema: labelSuggestionSchema,\n instructions: [\n \"Suggest concise editor-only item labels, not coding keys and not respondent-facing question text.\",\n \"Infer the item's purpose from its type, draft label, visible content, hierarchy, siblings, and descendants.\",\n \"Use currentSurveyContext.naming.labelExamples to infer established capitalization, prefixes, abbreviations, delimiters, and typical length.\",\n \"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.\",\n \"Do not copy the subject matter of an unrelated example merely to imitate its style, and do not return an existing unrelated label verbatim.\",\n `Write labels in locale ${locale}.`,\n `Return at most ${maxSuggestions} distinct, specific, human-readable suggestions.`,\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"core-rules\"],\n });\n\n const normalizeLabel = (value: string) => value.trim().toLocaleLowerCase();\n const excludedLabels = new Set([\n normalizeLabel(input.draftLabel),\n ...(options.context.naming?.labelExamples ?? []).map((example) =>\n normalizeLabel(example.label),\n ),\n ]);\n const seen = new Set<string>();\n return {\n suggestions: result.suggestions\n .flatMap((suggestion) => {\n const text = suggestion.text.trim();\n const normalizedText = normalizeLabel(text);\n if (!text || excludedLabels.has(normalizedText) || seen.has(normalizedText)) return [];\n seen.add(normalizedText);\n return [{ ...suggestion, text }];\n })\n .slice(0, maxSuggestions),\n };\n};\n\nconst getProtectedTokens = (value: string) =>\n value.match(/\\{\\{[^{}]+\\}\\}|\\{[^{}]+\\}|\\$\\{[^{}]+\\}|%\\d*\\$?[a-z]/gi) ?? [];\n\nexport const runSurveyAssistantTranslateContentTask = async (\n input: SurveyAssistantTranslateContentInput,\n options: RunSurveyAssistantBuiltInTaskOptions,\n): Promise<SurveyAssistantTranslateContentResult> => {\n const result = await runSurveyAssistantTask({\n ...options,\n taskId: \"translate-content\",\n input,\n schema: translationsSchema,\n instructions: [\n \"Translate every supplied survey-content entry faithfully without adding explanations or omitting content.\",\n `Translate from ${input.sourceLocale} into exactly these target locales: ${input.targetLocales.join(\", \")}.`,\n \"Use currentSurveyContext.translation.examples as a terminology and style reference when relevant. The supplied source entries remain authoritative.\",\n \"Preserve meaning, register, survey terminology, punctuation, line breaks, response semantics, placeholders, interpolation tokens, URLs, and identifiers that should not be translated.\",\n \"Keep repeated terminology consistent across all entries and target locales. Do not use a neighboring translation when its meaning differs.\",\n \"Return plain strings keyed first by target locale and then by the original entry id. Return every requested locale and entry exactly once.\",\n invocationInstruction(options.mode),\n ],\n referenceTopics: [\"localization\"],\n });\n\n const translations: SurveyAssistantTranslateContentResult[\"translations\"] = {};\n for (const locale of input.targetLocales) {\n const entries = result.translations[locale];\n if (!entries) throw new Error(`Translation result is missing locale ${locale}.`);\n const translatedEntries: Record<string, string> = {};\n for (const entry of input.entries) {\n const translation = entries[entry.id];\n if (typeof translation !== \"string\" || translation.trim().length === 0) {\n throw new Error(`Translation result is missing entry ${entry.id} for locale ${locale}.`);\n }\n const sourceTokens = getProtectedTokens(entry.text).sort();\n const translatedTokens = getProtectedTokens(translation).sort();\n if (sourceTokens.join(\"\\u0000\") !== translatedTokens.join(\"\\u0000\")) {\n throw new Error(\n `Translation result changed protected tokens in entry ${entry.id} for locale ${locale}.`,\n );\n }\n translatedEntries[entry.id] = translation;\n }\n translations[locale] = translatedEntries;\n }\n return { translations };\n};\n\nconst MAX_TASK_REQUEST_BYTES = 512 * 1024;\nconst DEFAULT_MAX_TASK_CONCURRENT_REQUESTS = 4;\nconst DEFAULT_MAX_TASK_DURATION_MS = 60_000;\n\nexport interface SurveyAssistantTaskAuthorizedIdentity {\n resourceId: string;\n surveyId?: string;\n}\n\nexport interface SurveyAssistantTaskAuthorizationInput {\n request: Request;\n requestedResourceId?: string;\n requestedSurveyId?: string;\n}\n\nexport interface SurveyAssistantTaskModelResolutionInput {\n identity: SurveyAssistantTaskAuthorizedIdentity;\n request: Request;\n requestedModelId?: string;\n}\n\nexport interface CreateSurveyAssistantTaskHandlerOptions {\n agent:\n | Pick<Agent, \"generate\">\n | (() => Pick<Agent, \"generate\"> | Promise<Pick<Agent, \"generate\">>);\n authorize(\n input: SurveyAssistantTaskAuthorizationInput,\n ): SurveyAssistantTaskAuthorizedIdentity | Promise<SurveyAssistantTaskAuthorizedIdentity>;\n getReadinessError?(request: Request): string | null | Promise<string | null>;\n isEnabled?(request: Request): boolean | Promise<boolean>;\n maxConcurrentRequests?: number;\n maxDurationMs?: number;\n onTaskMetrics?(input: {\n durationMs: number;\n identity: SurveyAssistantTaskAuthorizedIdentity;\n status: \"completed\" | \"failed\";\n taskId: string;\n }): void;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n resolveModel?(\n input: SurveyAssistantTaskModelResolutionInput,\n ):\n | SurveyAssistantModelSelection\n | null\n | undefined\n | Promise<SurveyAssistantModelSelection | null | undefined>;\n}\n\nconst taskErrorResponse = (error: unknown) => {\n const status =\n typeof error === \"object\" &&\n error !== null &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ? error.status\n : error instanceof SyntaxError || (error instanceof Error && error.name === \"ZodError\")\n ? 400\n : 500;\n const message =\n error instanceof SurveyAssistantRequestError\n ? error.message\n : status === 401 || status === 403 || status === 404\n ? status === 404\n ? \"Survey assistant task not found.\"\n : \"The survey assistant task is not authorized.\"\n : status >= 500\n ? \"The survey assistant task could not be completed.\"\n : \"The survey assistant task request is invalid.\";\n return Response.json(\n {\n code:\n status === 401 || status === 403 || status === 404\n ? \"authorization_failed\"\n : \"request_failed\",\n error: message,\n },\n { status },\n );\n};\n\nexport const createSurveyAssistantTaskHandler = ({\n agent,\n authorize,\n getReadinessError,\n isEnabled,\n maxConcurrentRequests = DEFAULT_MAX_TASK_CONCURRENT_REQUESTS,\n maxDurationMs = DEFAULT_MAX_TASK_DURATION_MS,\n onTaskMetrics,\n providerOptions,\n resolveModel,\n}: CreateSurveyAssistantTaskHandlerOptions) => {\n const concurrency =\n Number.isInteger(maxConcurrentRequests) && maxConcurrentRequests > 0\n ? maxConcurrentRequests\n : DEFAULT_MAX_TASK_CONCURRENT_REQUESTS;\n const duration =\n Number.isFinite(maxDurationMs) && maxDurationMs > 0\n ? maxDurationMs\n : DEFAULT_MAX_TASK_DURATION_MS;\n let activeRequests = 0;\n\n return async (request: Request): Promise<Response> => {\n if (activeRequests >= concurrency) {\n return Response.json(\n {\n code: \"rate_limited\",\n error: \"The survey assistant is handling too many tasks. Try again shortly.\",\n },\n { status: 429 },\n );\n }\n activeRequests += 1;\n const startedAt = Date.now();\n let metricsIdentity: SurveyAssistantTaskAuthorizedIdentity | undefined;\n let metricsTaskId = \"unknown\";\n let completed = false;\n try {\n if (isEnabled && !(await isEnabled(request))) {\n return Response.json(\n { code: \"request_failed\", error: \"Survey assistant is disabled.\" },\n { status: 404 },\n );\n }\n const task = surveyAssistantTaskRequestSchema.parse(\n await readSurveyAssistantRequestJson(request, MAX_TASK_REQUEST_BYTES),\n );\n metricsTaskId = task.taskId;\n const identity = await authorize({\n request,\n requestedResourceId: task.resourceId,\n requestedSurveyId: task.surveyId,\n });\n if (\n !identity?.resourceId?.trim() ||\n identity.resourceId.trim().length > 240 ||\n (identity.surveyId !== undefined &&\n (!identity.surveyId.trim() || identity.surveyId.trim().length > 240))\n ) {\n throw Object.assign(new Error(\"The host returned an invalid task identity.\"), {\n status: 500,\n });\n }\n metricsIdentity = {\n resourceId: identity.resourceId.trim(),\n ...(identity.surveyId?.trim() ? { surveyId: identity.surveyId.trim() } : {}),\n };\n\n const readinessError = await getReadinessError?.(request);\n if (readinessError) {\n return Response.json({ code: \"request_failed\", error: readinessError }, { status: 503 });\n }\n\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n if (resolveModel) {\n const modelSelection = await resolveModel({\n identity: metricsIdentity,\n request,\n requestedModelId: task.modelId,\n });\n if (!modelSelection) {\n return Response.json(\n {\n code: \"request_failed\",\n error: \"The selected survey assistant model is unavailable.\",\n },\n { status: 400 },\n );\n }\n requestContext.set(\"modelSelection\", modelSelection);\n }\n\n const resolvedAgent = typeof agent === \"function\" ? await agent() : agent;\n const runtime: RunSurveyAssistantBuiltInTaskOptions = {\n abortSignal: AbortSignal.any([request.signal, AbortSignal.timeout(duration)]),\n agent: resolvedAgent,\n context: task.context,\n mode: task.mode,\n requestContext,\n providerOptions,\n };\n const result =\n task.taskId === \"suggest-item-key\"\n ? await runSurveyAssistantSuggestItemKeyTask(task.input, runtime)\n : task.taskId === \"suggest-item-label\"\n ? await runSurveyAssistantSuggestItemLabelTask(task.input, runtime)\n : await runSurveyAssistantTranslateContentTask(task.input, runtime);\n completed = true;\n return Response.json(result);\n } catch (error) {\n return taskErrorResponse(error);\n } finally {\n activeRequests = Math.max(0, activeRequests - 1);\n if (metricsIdentity) {\n try {\n onTaskMetrics?.({\n durationMs: Date.now() - startedAt,\n identity: metricsIdentity,\n status: completed ? \"completed\" : \"failed\",\n taskId: metricsTaskId,\n });\n } catch {\n // Host metrics must not change the task response.\n }\n }\n }\n };\n};\n"],"mappings":";;;;;;;;AAqCA,MAAa,kCAAkC,EAAE,YAC/C,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cACE;CACF;CACD,CAAC;AAeJ,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD;AAED,MAAa,yBAAyB,OAAkC,EACtE,OACA,QACA,OACA,SACA,QACA,cACA,kBAAkB,EAAE,EACpB,gBACA,iBACA,kBACwE;CACxE,MAAM,aAAa,gBAAgB,KAAK,WAAW;EACjD;EACA,OAAO,0BAA0B,OAAO;EACxC,SAAS,0BAA0B,OAAO;EAC3C,EAAE;CACH,MAAM,WAAW,MAAM,MAAM,SAC3B,KAAK,UAAU;EAAE;EAAQ;EAAO,sBAAsB;EAAS,CAAC,EAChE;EACE,cAAc;GACZ,GAAG;GACH,GAAG;GACH,GAAG,WAAW,KAAK,UAAU,cAAc,MAAM,MAAM,IAAI,MAAM,UAAU;GAC5E;EACD,aAAa,EAAE;EACf,iBAAiB,EAAE;EACnB,UAAU;EACV,kBAAkB;GAChB;GACA,eAAe;GAChB;EACD,GAAI,iBAAiB,EAAE,gBAAgB,GAAG,EAAE;EAC5C,GAAI,kBAAkB,EAAE,iBA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AM,uCAAuC,KAAK,OAAO,QAAQ,GACjE,MAAM,uCAAuC,KAAK,OAAO,QAAQ;AACzE,eAAY;AACZ,UAAO,SAAS,KAAK,OAAO;WACrB,OAAO;AACd,UAAO,kBAAkB,MAAM;YACvB;AACR,oBAAiB,KAAK,IAAI,GAAG,iBAAiB,EAAE;AAChD,OAAI,gBACF,KAAI;AACF,oBAAgB;KACd,YAAY,KAAK,KAAK,GAAG;KACzB,UAAU;KACV,QAAQ,YAAY,cAAc;KAClC,QAAQ;KACT,CAAC;WACI"}
|
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-B_x2IYi7.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-DDXaJ8Za.mjs";
|
|
2
2
|
export { SURVEY_ASSISTANT_TOOL_IDS, surveyAssetTool, surveyAssistantTools, surveyAuditTool };
|
package/dist/server.d.mts
CHANGED
|
@@ -1,36 +1,104 @@
|
|
|
1
|
-
import { g as TurnChangeCollector } from "./index-
|
|
2
|
-
import { a as SurveyAssistantThreadDocumentRepository, c as loadSurveyAssistantThreadAttachments, i as SurveyAssistantThreadDocumentContent, l as registerSurveyAssistantThreadAttachments, n as SurveyAssistantModelAttachment, o as getSurveyAssistantReplayableDocuments, r as SurveyAssistantThreadDocument, s as loadSurveyAssistantDocuments, t as SurveyAssistantAttachmentAccess, u as removeHistoricalSurveyAssistantAttachments } from "./thread-documents-
|
|
3
|
-
import { a as
|
|
4
|
-
import { _ as formatSurveyAssistantStreamError, a as createSurveyAssistantThreadHandlers, c as SurveyAssistantAuthorize, d as SurveyAssistantModelResolutionInput, f as SurveyAssistantResolveModel, g as describeSurveyAssistantStreamError, h as createSurveyAssistantChatHandler, i as SurveyAssistantThreadRepository, l as SurveyAssistantAuthorizedIdentity, m as SurveyAssistantTurnMetrics, n as SurveyAssistantStoredThread, o as SurveyAssistantAuthorizationError, p as SurveyAssistantStreamErrorContext, r as SurveyAssistantThreadIdentity, s as SurveyAssistantAuthorizationInput, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions } from "./thread-handlers-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import { g as TurnChangeCollector } from "./index-DZ6KBwVR.mjs";
|
|
2
|
+
import { a as SurveyAssistantThreadDocumentRepository, c as loadSurveyAssistantThreadAttachments, d as replaceCurrentSurveyAssistantAttachmentsWithReferences, i as SurveyAssistantThreadDocumentContent, l as registerSurveyAssistantThreadAttachments, n as SurveyAssistantModelAttachment, o as getSurveyAssistantReplayableDocuments, r as SurveyAssistantThreadDocument, s as loadSurveyAssistantDocuments, t as SurveyAssistantAttachmentAccess, u as removeHistoricalSurveyAssistantAttachments } from "./thread-documents-BlxNjc7S.mjs";
|
|
3
|
+
import { a as SurveyAssistantModelSelection, c as deriveSurveyAssistantDocumentTransition, d as requireSurveyAssistantTurnState, i as SurveyAssistantIdentityContext, l as parseSurveyAssistantPreviousSettledVersion, n as SURVEY_ASSISTANT_TASK_AGENT_ID, o as SurveyAssistantRequestContext, r as SurveyAssistantDocumentTransition, s as buildSurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID, u as parseSurveyAssistantSnapshot } from "./constants-56jf_4ls.mjs";
|
|
4
|
+
import { A as validateSurveyAssistantMessages, C as SURVEY_ASSISTANT_MAX_MESSAGES, D as SurveyAssistantRequestError, E as SURVEY_ASSISTANT_MAX_TOTAL_ATTACHMENT_BYTES, O as SurveyAssistantRequestLimits, S as SURVEY_ASSISTANT_MAX_ATTACHMENT_NAME_CHARS, T as SURVEY_ASSISTANT_MAX_TEXT_PART_CHARS, _ as formatSurveyAssistantStreamError, a as createSurveyAssistantThreadHandlers, b as SURVEY_ASSISTANT_MAX_ATTACHMENTS, c as SurveyAssistantAuthorize, d as SurveyAssistantModelResolutionInput, f as SurveyAssistantResolveModel, g as describeSurveyAssistantStreamError, h as createSurveyAssistantChatHandler, i as SurveyAssistantThreadRepository, k as readSurveyAssistantRequestJson, l as SurveyAssistantAuthorizedIdentity, m as SurveyAssistantTurnMetrics, n as SurveyAssistantStoredThread, o as SurveyAssistantAuthorizationError, p as SurveyAssistantStreamErrorContext, r as SurveyAssistantThreadIdentity, s as SurveyAssistantAuthorizationInput, t as CreateSurveyAssistantThreadHandlersOptions, u as SurveyAssistantChatHandlerOptions, v as SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, w as SURVEY_ASSISTANT_MAX_REQUEST_BYTES, x as SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, y as SURVEY_ASSISTANT_DEFAULT_REQUEST_LIMITS } from "./thread-handlers-l79JBl5m.mjs";
|
|
5
|
+
import { a as SurveyAssistantTaskAuthorizationInput, g as surveyAuthoringReferences, h as surveyAuthoringReferenceTopics, m as SurveyAuthoringReferenceTopic, o as SurveyAssistantTaskAuthorizedIdentity } from "./tasks-COQnhSeT.mjs";
|
|
6
|
+
import { UIMessageChunk } from "ai";
|
|
7
7
|
import { MastraMemory } from "@mastra/core/memory";
|
|
8
8
|
|
|
9
9
|
//#region src/server/memory-thread-repository.d.ts
|
|
10
10
|
type ThreadMemory = Pick<MastraMemory, "createThread" | "deleteThread" | "getThreadById" | "listThreads" | "recall" | "updateThread">;
|
|
11
11
|
interface CreateMastraMemoryThreadRepositoryOptions {
|
|
12
12
|
getMemory(): ThreadMemory | Promise<ThreadMemory>;
|
|
13
|
+
/** Maximum recent messages returned when hydrating a transcript. */
|
|
14
|
+
maxMessagesPerTranscript?: number;
|
|
15
|
+
/** Maximum recent threads returned by the history endpoint. */
|
|
16
|
+
maxThreadsPerList?: number;
|
|
13
17
|
threadDocuments?: SurveyAssistantThreadDocumentRepository;
|
|
14
18
|
}
|
|
15
19
|
declare const createMastraMemoryThreadRepository: ({
|
|
16
20
|
getMemory,
|
|
21
|
+
maxMessagesPerTranscript,
|
|
22
|
+
maxThreadsPerList,
|
|
17
23
|
threadDocuments
|
|
18
24
|
}: CreateMastraMemoryThreadRepositoryOptions) => SurveyAssistantThreadRepository;
|
|
19
25
|
//#endregion
|
|
20
|
-
//#region src/server/
|
|
21
|
-
declare const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
26
|
+
//#region src/server/survey-lifecycle.d.ts
|
|
27
|
+
declare const SURVEY_ASSISTANT_SURVEY_ID_METADATA_KEY = "surveyId";
|
|
28
|
+
type SurveyLifecycleMemory = Pick<MastraMemory, "deleteThread" | "getThreadById" | "listThreads" | "recall" | "createThread" | "updateThread">;
|
|
29
|
+
interface CreateSurveyAssistantSurveyLifecycleOptions {
|
|
30
|
+
getMemory(): SurveyLifecycleMemory | Promise<SurveyLifecycleMemory>;
|
|
31
|
+
/** Optionally derives the survey-scoped thread endpoint exposed in `panelProps`. */
|
|
32
|
+
getThreadApi?(surveyId: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* Stable host metadata that separates this assistant deployment from any
|
|
35
|
+
* other application using the same Mastra storage.
|
|
36
|
+
*/
|
|
37
|
+
scopeMetadata: Record<string, string>;
|
|
38
|
+
/**
|
|
39
|
+
* Pass the same repository used by the chat handler, or explicitly use
|
|
40
|
+
* `false` when cross-turn attachment persistence/replay is disabled.
|
|
41
|
+
*/
|
|
42
|
+
threadDocuments: SurveyAssistantThreadDocumentRepository | false;
|
|
43
|
+
}
|
|
44
|
+
interface DeleteSurveyAssistantSurveyThreadsInput {
|
|
45
|
+
surveyId: string;
|
|
46
|
+
/** Restrict cleanup to one user. Omit this when the survey itself is deleted. */
|
|
47
|
+
resourceId?: string;
|
|
48
|
+
}
|
|
49
|
+
interface SurveyAssistantThreadCleanupResult {
|
|
50
|
+
deletedThreadIds: string[];
|
|
51
|
+
matchedThreadCount: number;
|
|
52
|
+
}
|
|
53
|
+
type DeleteSurveyAssistantSurveyThreadsResult = SurveyAssistantThreadCleanupResult;
|
|
54
|
+
interface SurveyAssistantSurveyPanelProps {
|
|
55
|
+
resourceId: string;
|
|
56
|
+
surveyId: string;
|
|
57
|
+
threadApi?: string;
|
|
58
|
+
}
|
|
59
|
+
interface SurveyAssistantScopedSurvey {
|
|
60
|
+
/** Validates the requested ids and returns a trusted identity for the chat handler. */
|
|
61
|
+
authorizeChat: SurveyAssistantAuthorize;
|
|
62
|
+
/** Validates the requested survey/resource ids for the bounded task handler. */
|
|
63
|
+
authorizeTask(input: SurveyAssistantTaskAuthorizationInput): SurveyAssistantTaskAuthorizedIdentity;
|
|
64
|
+
/** Deletes this user's threads for the survey. */
|
|
65
|
+
deleteThreads(): Promise<DeleteSurveyAssistantSurveyThreadsResult>;
|
|
66
|
+
/** Returns true only for a thread in this exact deployment, survey, and user scope. */
|
|
67
|
+
ownsThread(thread: SurveyAssistantStoredThread | null | undefined): thread is SurveyAssistantStoredThread;
|
|
68
|
+
/** Props that can be passed directly to ConnectedSurveyAssistantPanel. */
|
|
69
|
+
panelProps: SurveyAssistantSurveyPanelProps;
|
|
70
|
+
resourceId: string;
|
|
71
|
+
surveyId: string;
|
|
72
|
+
/** Identity returned by the thread handler's authorize callback. */
|
|
73
|
+
threadIdentity: SurveyAssistantThreadIdentity;
|
|
74
|
+
}
|
|
75
|
+
interface SurveyAssistantSurveyLifecycle {
|
|
76
|
+
/** Deletes this resource's threads across every survey in this deployment scope. */
|
|
77
|
+
deleteResource(resourceId: string): Promise<SurveyAssistantThreadCleanupResult>;
|
|
78
|
+
/** Deletes every user's threads for a survey. */
|
|
79
|
+
deleteSurvey(surveyId: string): Promise<SurveyAssistantThreadCleanupResult>;
|
|
80
|
+
deleteSurveyThreads(input: DeleteSurveyAssistantSurveyThreadsInput): Promise<SurveyAssistantThreadCleanupResult>;
|
|
81
|
+
forSurvey(surveyId: string, resourceId: string): SurveyAssistantScopedSurvey;
|
|
82
|
+
}
|
|
83
|
+
declare const createSurveyAssistantSurveyThreadMetadata: ({
|
|
84
|
+
scopeMetadata,
|
|
85
|
+
surveyId
|
|
86
|
+
}: {
|
|
87
|
+
scopeMetadata: Record<string, string>;
|
|
88
|
+
surveyId: string;
|
|
89
|
+
}) => Record<string, string>;
|
|
90
|
+
/**
|
|
91
|
+
* Creates an idempotent, server-only lifecycle service for removing every
|
|
92
|
+
* assistant thread owned by a survey. Hosts should call this after preventing
|
|
93
|
+
* new assistant activity and before completing (or from a durable retry of)
|
|
94
|
+
* survey deletion.
|
|
95
|
+
*/
|
|
96
|
+
declare const createSurveyAssistantSurveyLifecycle: ({
|
|
97
|
+
getMemory,
|
|
98
|
+
getThreadApi,
|
|
99
|
+
scopeMetadata,
|
|
100
|
+
threadDocuments
|
|
101
|
+
}: CreateSurveyAssistantSurveyLifecycleOptions) => SurveyAssistantSurveyLifecycle;
|
|
34
102
|
//#endregion
|
|
35
103
|
//#region src/server/turn-stream.d.ts
|
|
36
104
|
interface SurveyAssistantTurnStreamOptions {
|
|
@@ -48,5 +116,5 @@ declare const createSurveyAssistantTurnStream: ({
|
|
|
48
116
|
stream
|
|
49
117
|
}: SurveyAssistantTurnStreamOptions) => ReadableStream<UIMessageChunk>;
|
|
50
118
|
//#endregion
|
|
51
|
-
export { type CreateMastraMemoryThreadRepositoryOptions, type CreateSurveyAssistantThreadHandlersOptions, SURVEY_ASSISTANT_ACCEPTED_ATTACHMENT_TYPES, SURVEY_ASSISTANT_AGENT_ID, SURVEY_ASSISTANT_MAX_ATTACHMENTS, SURVEY_ASSISTANT_MAX_ATTACHMENT_BYTES, 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 SurveyAssistantIdentityContext, type SurveyAssistantModelAttachment, type SurveyAssistantModelResolutionInput, type SurveyAssistantModelSelection, type SurveyAssistantRequestContext, SurveyAssistantRequestError, type SurveyAssistantResolveModel, type
|
|
119
|
+
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_SURVEY_ID_METADATA_KEY, SURVEY_ASSISTANT_TASK_AGENT_ID, type SurveyAssistantAttachmentAccess, SurveyAssistantAuthorizationError, type SurveyAssistantAuthorizationInput, type SurveyAssistantAuthorize, type SurveyAssistantAuthorizedIdentity, type SurveyAssistantChatHandlerOptions, type SurveyAssistantDocumentTransition, type SurveyAssistantIdentityContext, 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 SurveyAssistantThreadIdentity, type SurveyAssistantThreadRepository, type SurveyAssistantTurnMetrics, type SurveyAssistantTurnStreamOptions, type SurveyAuthoringReferenceTopic, buildSurveyAssistantRequestContext, createMastraMemoryThreadRepository, createSurveyAssistantChatHandler, createSurveyAssistantSurveyLifecycle, createSurveyAssistantSurveyThreadMetadata, createSurveyAssistantThreadHandlers, createSurveyAssistantTurnStream, deriveSurveyAssistantDocumentTransition, describeSurveyAssistantStreamError, formatSurveyAssistantStreamError, getSurveyAssistantReplayableDocuments, loadSurveyAssistantDocuments, loadSurveyAssistantThreadAttachments, parseSurveyAssistantPreviousSettledVersion, parseSurveyAssistantSnapshot, readSurveyAssistantRequestJson, registerSurveyAssistantThreadAttachments, removeHistoricalSurveyAssistantAttachments, replaceCurrentSurveyAssistantAttachmentsWithReferences, requireSurveyAssistantTurnState, surveyAuthoringReferenceTopics, surveyAuthoringReferences, validateSurveyAssistantMessages };
|
|
52
120
|
//# 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/
|
|
1
|
+
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/memory-th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