@case-framework/survey-assistant 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +212 -0
- package/dist/authoring-references-Cy8J-DWt.d.mts +48 -0
- package/dist/authoring-references-Cy8J-DWt.d.mts.map +1 -0
- package/dist/authoring-references-X6uRaWuf.mjs +68 -0
- package/dist/authoring-references-X6uRaWuf.mjs.map +1 -0
- package/dist/capabilities-B6tvE7fK.mjs +66 -0
- package/dist/capabilities-B6tvE7fK.mjs.map +1 -0
- package/dist/capabilities-DvSKtjAw.d.mts +182 -0
- package/dist/capabilities-DvSKtjAw.d.mts.map +1 -0
- package/dist/capabilities-default.d.mts +15 -0
- package/dist/capabilities-default.d.mts.map +1 -0
- package/dist/capabilities-default.mjs +347 -0
- package/dist/capabilities-default.mjs.map +1 -0
- package/dist/constants-CFUWrRtl.mjs +7 -0
- package/dist/constants-CFUWrRtl.mjs.map +1 -0
- package/dist/constants-Jw0k8ojS.d.mts +67 -0
- package/dist/constants-Jw0k8ojS.d.mts.map +1 -0
- package/dist/controller-proxy-BRDusFiO.d.mts +57 -0
- package/dist/controller-proxy-BRDusFiO.d.mts.map +1 -0
- package/dist/controller-proxy-Duxo2IFE.mjs +92 -0
- package/dist/controller-proxy-Duxo2IFE.mjs.map +1 -0
- package/dist/digest-BsoVq49o.d.mts +9 -0
- package/dist/digest-BsoVq49o.d.mts.map +1 -0
- package/dist/digest.d.mts +2 -0
- package/dist/digest.mjs +20 -0
- package/dist/digest.mjs.map +1 -0
- package/dist/engine-sPvuixWg.mjs +4857 -0
- package/dist/engine-sPvuixWg.mjs.map +1 -0
- package/dist/engine.d.mts +3 -0
- package/dist/engine.mjs +4 -0
- package/dist/index-BWNHkpkh.d.mts +187 -0
- package/dist/index-BWNHkpkh.d.mts.map +1 -0
- package/dist/index-CUqbBjkc.d.mts +641 -0
- package/dist/index-CUqbBjkc.d.mts.map +1 -0
- package/dist/index-MpEMQzTm.d.mts +123 -0
- package/dist/index-MpEMQzTm.d.mts.map +1 -0
- package/dist/index-TFtvBiSQ.d.mts +1149 -0
- package/dist/index-TFtvBiSQ.d.mts.map +1 -0
- package/dist/memory-thread-repository-CJkkVE2-.mjs +718 -0
- package/dist/memory-thread-repository-CJkkVE2-.mjs.map +1 -0
- package/dist/protocol-DV0ka9WT.mjs +1032 -0
- package/dist/protocol-DV0ka9WT.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -0
- package/dist/protocol.mjs +2 -0
- package/dist/react-VuYe-cPh.mjs +521 -0
- package/dist/react-VuYe-cPh.mjs.map +1 -0
- package/dist/react-integration.d.mts +2 -0
- package/dist/react-integration.mjs +3 -0
- package/dist/react.d.mts +3 -0
- package/dist/react.mjs +4 -0
- package/dist/references/assistant-operations.md +287 -0
- package/dist/references/core-rules.md +11 -0
- package/dist/references/embedded-forms.md +80 -0
- package/dist/references/expressions.md +301 -0
- package/dist/references/item-types.md +364 -0
- package/dist/references/localization.md +25 -0
- package/dist/references/rich-text-content.md +193 -0
- package/dist/references/source-material-surveys.md +60 -0
- package/dist/references/survey-data-model.md +109 -0
- package/dist/references/survey-quality.md +23 -0
- package/dist/request-context-jcmXT_Q2.mjs +44 -0
- package/dist/request-context-jcmXT_Q2.mjs.map +1 -0
- package/dist/request-guardrails-C59IWnH8.mjs +73 -0
- package/dist/request-guardrails-C59IWnH8.mjs.map +1 -0
- package/dist/server-agent.d.mts +131 -0
- package/dist/server-agent.d.mts.map +1 -0
- package/dist/server-agent.mjs +229 -0
- package/dist/server-agent.mjs.map +1 -0
- package/dist/server-runtime.d.mts +123 -0
- package/dist/server-runtime.d.mts.map +1 -0
- package/dist/server-runtime.mjs +296 -0
- package/dist/server-runtime.mjs.map +1 -0
- package/dist/server-tasks.d.mts +78 -0
- package/dist/server-tasks.d.mts.map +1 -0
- package/dist/server-tasks.mjs +253 -0
- package/dist/server-tasks.mjs.map +1 -0
- package/dist/server-tools.d.mts +2 -0
- package/dist/server-tools.mjs +2 -0
- package/dist/server.d.mts +52 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +6 -0
- package/dist/storage-postgres.d.mts +37 -0
- package/dist/storage-postgres.d.mts.map +1 -0
- package/dist/storage-postgres.mjs +167 -0
- package/dist/storage-postgres.mjs.map +1 -0
- package/dist/thread-documents-DamIq9Od.d.mts +91 -0
- package/dist/thread-documents-DamIq9Od.d.mts.map +1 -0
- package/dist/thread-handlers-DpynUc64.d.mts +112 -0
- package/dist/thread-handlers-DpynUc64.d.mts.map +1 -0
- package/dist/tools-Hz2p7vyv.mjs +1879 -0
- package/dist/tools-Hz2p7vyv.mjs.map +1 -0
- package/dist/ui.css +2 -0
- package/dist/ui.d.mts +63 -0
- package/dist/ui.d.mts.map +1 -0
- package/dist/ui.mjs +2238 -0
- package/dist/ui.mjs.map +1 -0
- package/package.json +166 -0
- package/ui.css.d.ts +3 -0
|
@@ -0,0 +1,1879 @@
|
|
|
1
|
+
import { W as assistantItemTypeManifestSchema, gt as surveyOperationSchema, u as surveyChangeSetSchema } from "./protocol-DV0ka9WT.mjs";
|
|
2
|
+
import { a as getDeterministicCreateItemTypes, o as inspectAssistantItem, s as resolveAssistantCapabilityReference } from "./capabilities-B6tvE7fK.mjs";
|
|
3
|
+
import { A as getRawSurvey, B as resolveItemSummary, C as clampLimit, F as mapKeyIndexById, H as summarizeFocusItemNode, I as mapOutlineById, J as translationEntrySchema, K as summarizeOutlineNode, L as mapRawItemsById, M as itemConfigDetailsSchema, N as itemMatchesQuery, P as itemSummarySchema, R as normalizeText, U as summarizeItemById, V as sliceWithCursor, W as summarizeKeyIndexEntries, Y as unique, _ as buildConfigSearchText, a as SURVEY_CHANGE_CONTINUATION_MODES, b as buildItemTranslationEntries, d as normalizeSurveyChangeOperations, f as buildExpressionMutationPatches, i as SURVEY_CHANGE_CONTINUATION_DESCRIPTION, j as getRawSurveyItems, k as getKeyIndexEntries, l as createSurveyChangeSet, p as expressionMutationSchema, q as summarizeRawItem, t as auditSurvey, v as buildEmbeddedFormDetails, w as findDirectChildrenByFullKey, y as buildItemConfigDetails } from "./engine-sPvuixWg.mjs";
|
|
4
|
+
import { r as requireSurveyAssistantTurnState } from "./request-context-jcmXT_Q2.mjs";
|
|
5
|
+
import { n as surveyAuthoringReferences, t as surveyAuthoringReferenceTopics } from "./authoring-references-X6uRaWuf.mjs";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { JsonPatchError, encodeJsonPointerSegment, getAssetUsagesFromContent, getValueAtJsonPointer } from "@case-framework/survey-core";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { createTool, isValidationError } from "@mastra/core/tools";
|
|
10
|
+
//#region src/server/tools/tool-model-output.ts
|
|
11
|
+
const FALLBACK_MODEL_TEXT = "The tool returned no model-readable output. Review the tool arguments and retry with valid values.";
|
|
12
|
+
const unwrapToolOutput$1 = (value) => value && typeof value === "object" && "output" in value && value.output !== void 0 ? value.output : value;
|
|
13
|
+
const createTextModelOutput = (text) => ({
|
|
14
|
+
type: "content",
|
|
15
|
+
value: [{
|
|
16
|
+
type: "text",
|
|
17
|
+
text: typeof text === "string" && text.trim().length > 0 ? text : FALLBACK_MODEL_TEXT
|
|
18
|
+
}]
|
|
19
|
+
});
|
|
20
|
+
const toTextModelOutput = (value, summarize) => {
|
|
21
|
+
const output = unwrapToolOutput$1(value);
|
|
22
|
+
if (isValidationError(output)) return createTextModelOutput(output.message);
|
|
23
|
+
try {
|
|
24
|
+
return createTextModelOutput(summarize(output));
|
|
25
|
+
} catch {
|
|
26
|
+
return createTextModelOutput(void 0);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/server/tools/survey-authoring-reference-tool.ts
|
|
31
|
+
const TOOL_ID$10 = "survey_authoring_reference";
|
|
32
|
+
const topicSchema = z.string().min(1).max(120);
|
|
33
|
+
const surveyAuthoringReferenceTool = createTool({
|
|
34
|
+
id: TOOL_ID$10,
|
|
35
|
+
description: "Load one narrow CASE survey authoring reference or an installed item capability's reference. For a capability-owned reference, provide both itemType and the reference topic advertised in the capability manifest.",
|
|
36
|
+
inputSchema: z.object({
|
|
37
|
+
topic: topicSchema.describe("The narrow authoring reference to load."),
|
|
38
|
+
itemType: z.string().min(1).max(120).optional().describe("Installed custom item type that owns this reference, when applicable."),
|
|
39
|
+
reason: z.string().max(500).optional().describe("Short reason this reference is needed.")
|
|
40
|
+
}),
|
|
41
|
+
outputSchema: z.object({
|
|
42
|
+
ok: z.boolean(),
|
|
43
|
+
topic: topicSchema,
|
|
44
|
+
itemType: z.string().optional(),
|
|
45
|
+
title: z.string(),
|
|
46
|
+
content: z.string()
|
|
47
|
+
}),
|
|
48
|
+
mcp: { annotations: {
|
|
49
|
+
title: "Read authoring reference",
|
|
50
|
+
readOnlyHint: true,
|
|
51
|
+
destructiveHint: false,
|
|
52
|
+
idempotentHint: true,
|
|
53
|
+
openWorldHint: false
|
|
54
|
+
} },
|
|
55
|
+
execute: async (inputData, context) => {
|
|
56
|
+
const builtInEntry = surveyAuthoringReferenceTopics.includes(inputData.topic) ? surveyAuthoringReferences[inputData.topic] : void 0;
|
|
57
|
+
const engineContext = context?.requestContext?.get("engineContext");
|
|
58
|
+
const capability = inputData.itemType ? engineContext?.trustedCapabilities?.byItemType.get(inputData.itemType) : void 0;
|
|
59
|
+
const capabilityReference = inputData.itemType ? resolveAssistantCapabilityReference({
|
|
60
|
+
capabilities: engineContext?.trustedCapabilities,
|
|
61
|
+
itemType: inputData.itemType,
|
|
62
|
+
topic: inputData.topic
|
|
63
|
+
}) : void 0;
|
|
64
|
+
const entry = capabilityReference ? {
|
|
65
|
+
title: capabilityReference.title ?? `${capability?.manifest.displayName} authoring`,
|
|
66
|
+
content: capabilityReference.markdown
|
|
67
|
+
} : builtInEntry;
|
|
68
|
+
if (!entry) return {
|
|
69
|
+
ok: false,
|
|
70
|
+
topic: inputData.topic,
|
|
71
|
+
itemType: inputData.itemType,
|
|
72
|
+
title: "Reference unavailable",
|
|
73
|
+
content: inputData.itemType ? `No reference named "${inputData.topic}" is installed for item type "${inputData.itemType}".` : `No built-in reference named "${inputData.topic}" is available.`
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
ok: true,
|
|
77
|
+
topic: inputData.topic,
|
|
78
|
+
itemType: inputData.itemType,
|
|
79
|
+
title: entry.title,
|
|
80
|
+
content: entry.content
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
toModelOutput: (value) => toTextModelOutput(value, (output) => `# ${output.title}\n\n${output.content}`)
|
|
84
|
+
});
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/server/tools/survey-change-tool.ts
|
|
87
|
+
const TOOL_ID$9 = "survey_change";
|
|
88
|
+
const inputSchema$9 = z.object({
|
|
89
|
+
intent: z.string().min(1).max(500).describe("The concrete survey change requested by the user."),
|
|
90
|
+
summary: z.string().min(1).max(500).describe("Short user-facing summary of the intended survey change."),
|
|
91
|
+
operations: z.array(z.unknown()).min(1).max(200).describe("Assistant operation objects to validate and package as one undoable change. Every operation uses the exact discriminator field \"kind\", never \"type\". Canonical create shape: { kind: \"create-item\", target: { parentItemId, index? }, item: { id, key, itemType, config }, translations?: [{ locale, contentKey, plainText } | { locale, contentKey, content }] }. Put parentItemId in target, respondent content in top-level translations, and item-type settings in item.config. When creating a new item that contains an imported or external image, put the complete richText content including its image block directly in create-item.translations[].content in the same call; never create a placeholder and then call update-placed-image because the new item is absent from the immutable snapshot. When deleting referenced images and their assets, include all reference-removal operations and remove-image-asset in this same operations array, with remove-image-asset last; do not split that dependency across survey_change and survey_asset. For a choice item, config.options entries use id and optional key/embeddedForm only; option labels are top-level translations at options.<optionId>.label. Canonical presentation shapes are { kind: \"update-item-label\", itemId, itemLabel } for the editor-only label and { kind: \"update-item-color\", itemId, color } for a supported editor swatch. Across editor views, unqualified labels for items/questions mean update-item-label; question titles and option/field labels are respondent-visible translations. Canonical item config shape: { kind: \"patch-item-config\", itemId, patches: [{ op, path, value? }] }, where paths are relative to that item config root. Inspect the item and load its capability reference first. Canonical add-choice-option shape: { kind: \"add-choice-option\", itemId, locale?, index?, option: { id?, key?, label: \"visible text\" } }; label is a plain string, and this operation creates its translation. Canonical text-update shape: { kind: \"update-item-translation\", itemId, locale, contentKey, plainText } for ordinary text; content is only a structured Content object for meaningful formatting. To edit one image already placed in rich text, use { kind: \"update-placed-image\", itemId, locale, contentKey, imageIndex, expectedAssetId?, changes } where imageIndex counts only image blocks from zero. changes can set a local asset source or an external URL and can update alt, caption, width, height, maxWidth, maxHeight, and alignment; null removes an optional property. This changes the rendered placement, while update-image-asset-metadata changes only global asset metadata. Canonical raw shape: { kind: \"survey-json-patch\", patches: [{ op, path, value? }] }; it must be the only operation and all related raw edits belong in its plural patches array, never patch. Patch paths are rooted at the survey, for example /surveyItems/<index>/config or /translations/<locale>. Keep proposals bounded; if validation says there are too many operations, split the same work into independent smaller change calls. Use compact typed operations for common edits, patch-item-config for item-local config, and one survey-json-patch operation for survey-wide raw edits."),
|
|
92
|
+
continuationMode: z.enum(SURVEY_CHANGE_CONTINUATION_MODES).nullish().transform((value) => value ?? void 0).describe(`${SURVEY_CHANGE_CONTINUATION_DESCRIPTION} Omit this field instead of sending null.`),
|
|
93
|
+
inspectedContext: z.array(z.string().max(240)).max(20).nullish().transform((value) => value ?? void 0).describe("Optional item ids, paths, or references inspected before proposing this change."),
|
|
94
|
+
notes: z.string().max(1e3).nullish().transform((value) => value ?? void 0).describe("Optional implementation notes for validation/debugging; not shown as persisted survey content.")
|
|
95
|
+
});
|
|
96
|
+
const rejectedOperationParseEvent = ({ issueText, summary, turnId }) => ({
|
|
97
|
+
protocolVersion: 1,
|
|
98
|
+
id: randomUUID(),
|
|
99
|
+
turnId,
|
|
100
|
+
status: "rejected",
|
|
101
|
+
summary,
|
|
102
|
+
operations: [],
|
|
103
|
+
validation: {
|
|
104
|
+
valid: false,
|
|
105
|
+
issues: [{
|
|
106
|
+
severity: "error",
|
|
107
|
+
code: "invalid-operation-shape",
|
|
108
|
+
message: issueText
|
|
109
|
+
}],
|
|
110
|
+
warnings: [],
|
|
111
|
+
normalizedOperations: []
|
|
112
|
+
},
|
|
113
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
114
|
+
});
|
|
115
|
+
const describeOperationTarget = (operation) => {
|
|
116
|
+
switch (operation.kind) {
|
|
117
|
+
case "update-item-translation": return `${operation.kind} ${operation.locale}:${operation.itemId}:${operation.contentKey}`;
|
|
118
|
+
case "update-placed-image": return `${operation.kind} ${operation.locale}:${operation.itemId}:${operation.contentKey}#${operation.imageIndex}`;
|
|
119
|
+
case "update-item-label":
|
|
120
|
+
case "update-item-color":
|
|
121
|
+
case "update-item-key":
|
|
122
|
+
case "patch-item-config":
|
|
123
|
+
case "remove-item":
|
|
124
|
+
case "move-item": return `${operation.kind} ${operation.itemId}`;
|
|
125
|
+
case "upsert-form-field-group": return `${operation.kind} ${operation.target.itemId}:${operation.group.id}`;
|
|
126
|
+
case "remove-form-field-group": return `${operation.kind} ${operation.target.itemId}:${operation.groupId}`;
|
|
127
|
+
case "reorder-form-field-groups": return `${operation.kind} ${operation.target.itemId}`;
|
|
128
|
+
case "upsert-form-field": return `${operation.kind} ${operation.target.itemId}:${operation.field.id}`;
|
|
129
|
+
case "remove-form-field":
|
|
130
|
+
case "move-form-field": return `${operation.kind} ${operation.target.itemId}:${operation.fieldId}`;
|
|
131
|
+
case "set-embedded-form":
|
|
132
|
+
case "remove-embedded-form": return `${operation.kind} ${operation.itemId}:${operation.optionId}`;
|
|
133
|
+
case "add-choice-option": return `${operation.kind} ${operation.itemId}:${operation.option.id ?? operation.option.key ?? operation.option.label}`;
|
|
134
|
+
case "update-choice-option-label":
|
|
135
|
+
case "remove-choice-option": return `${operation.kind} ${operation.itemId}:${operation.optionId}`;
|
|
136
|
+
case "reorder-choice-options": return `${operation.kind} ${operation.itemId}`;
|
|
137
|
+
case "reorder-items": return `${operation.kind} ${operation.parentItemId}`;
|
|
138
|
+
case "update-survey-metadata":
|
|
139
|
+
case "update-survey-pagination": return operation.kind;
|
|
140
|
+
case "update-survey-translation": return `${operation.kind} ${operation.locale}:${operation.surface}:${operation.contentKey}`;
|
|
141
|
+
case "remove-survey-locale": return `${operation.kind} ${operation.locale}`;
|
|
142
|
+
case "set-image-asset":
|
|
143
|
+
case "update-image-asset-metadata":
|
|
144
|
+
case "remove-image-asset": return `${operation.kind} ${operation.assetId}`;
|
|
145
|
+
case "create-item": return `${operation.kind} ${operation.item.id ?? operation.item.key ?? operation.item.itemType}`;
|
|
146
|
+
case "survey-json-patch": return `${operation.kind} ${operation.patches.map((patch) => patch.path).join(", ")}`;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const summarizeValidation = (event) => {
|
|
150
|
+
const lines = [`${event.status === "validated" ? "Validated" : "Rejected"} survey change: ${event.summary}`, `Change id: ${event.id}`];
|
|
151
|
+
if (event.operations.length > 0) lines.push(`Operations: ${event.operations.map((operation) => operation.kind).join(", ")}`);
|
|
152
|
+
if (event.status === "rejected") {
|
|
153
|
+
lines.push("Apply status: this turn is blocked and will authorize no survey changes unless a later complete proposal validates with continuationMode \"replace\".");
|
|
154
|
+
if (event.operations.length > 0) {
|
|
155
|
+
const checklist = event.operations.slice(0, 24).map(describeOperationTarget);
|
|
156
|
+
lines.push(`Unapplied target sample (${checklist.length} of ${event.operations.length}):\n${checklist.map((target) => `- ${target}`).join("\n")}`);
|
|
157
|
+
if (event.operations.length > checklist.length) lines.push(`The sample omits ${event.operations.length - checklist.length} additional operation target(s). The original tool input is authoritative; preserve its complete requested scope when retrying.`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (event.status === "validated") {
|
|
161
|
+
lines.push("Lifecycle: this candidate is registered, not live. Do not target its new ids again in this response; successful turn completion authorizes the collector's final candidate ids for browser apply.");
|
|
162
|
+
if (event.supersedesChangeIds?.length) lines.push(`Queue: replaces ${event.supersedesChangeIds.length} earlier survey_change proposal(s) from this response.`);
|
|
163
|
+
}
|
|
164
|
+
if (event.supersedesChangeIds?.length && event.status === "rejected") lines.push(`Queue: discarded ${event.supersedesChangeIds.length} earlier candidate proposal(s); their work is not retained or authorized. Include that discarded work in the complete replacement before claiming the request is complete.`);
|
|
165
|
+
if (event.validation.issues.length > 0) {
|
|
166
|
+
lines.push("Issues:");
|
|
167
|
+
for (const issue of event.validation.issues) lines.push(`- ${issue.code}: ${issue.message}`);
|
|
168
|
+
const issueCodes = new Set(event.validation.issues.map((issue) => issue.code));
|
|
169
|
+
if (issueCodes.has("missing-create-content") || issueCodes.has("missing-field-groups-wrapper") || issueCodes.has("missing-choice-options") || issueCodes.has("missing-choice-option-labels")) lines.push("Recovery hint: load the assistant-operations reference, then retry the complete create-item proposal with continuationMode \"replace\". Put visible text in top-level translations[] beside item, config inside item.config, choice options in item.config.options, and form fields inside item.config.fieldGroups[].fields. Every choice option id needs a matching top-level translation whose contentKey is options.<optionId>.label.");
|
|
170
|
+
if (issueCodes.has("too-many-operations")) lines.push("Recovery hint: keep the same inspected survey context and immediately split these edits into smaller survey_change calls. Use continuationMode \"replace\" on the first repaired chunk, then \"append\" on every later independent chunk. Do not claim that a new snapshot is needed unless a tool explicitly reported a missing snapshot.");
|
|
171
|
+
if (issueCodes.has("change-mode-required")) lines.push("Recovery hint: retry the complete intended proposal with continuationMode \"append\" for independent additional work or \"replace\" for a correction. Nothing from the ambiguous sequence is currently authorized.");
|
|
172
|
+
if (issueCodes.has("change-mode-repair-required")) lines.push("Recovery hint: the turn remains blocked. Retry the complete intended proposal with continuationMode \"replace\". Only a validated replacement clears the block; after that, use \"append\" for later independent chunks.");
|
|
173
|
+
}
|
|
174
|
+
if (event.validation.warnings.length > 0) {
|
|
175
|
+
lines.push("Warnings:");
|
|
176
|
+
for (const warning of event.validation.warnings) lines.push(`- ${warning.code}: ${warning.message}`);
|
|
177
|
+
}
|
|
178
|
+
return lines.join("\n");
|
|
179
|
+
};
|
|
180
|
+
const surveyChangeTool = createTool({
|
|
181
|
+
id: TOOL_ID$9,
|
|
182
|
+
description: "Validate and queue one final, bounded, undoable survey change. This is not a dry run and does not mutate the live snapshot during the response. Put related operations and newly created dependencies in one call, in dependency order; embed expressions on new dependent items. Omit continuationMode only on the first mutation call in a turn; every later mutation call must use \"append\" for independent additional work or \"replace\" for a correction. Every operation uses \"kind\". A create-item has top-level target, item, and translations.",
|
|
183
|
+
inputSchema: inputSchema$9,
|
|
184
|
+
outputSchema: surveyChangeSetSchema,
|
|
185
|
+
mcp: { annotations: {
|
|
186
|
+
title: "Prepare survey change",
|
|
187
|
+
readOnlyHint: true,
|
|
188
|
+
destructiveHint: false,
|
|
189
|
+
idempotentHint: false,
|
|
190
|
+
openWorldHint: false
|
|
191
|
+
} },
|
|
192
|
+
execute: async (inputData, context) => {
|
|
193
|
+
const { changeCollector, turnId } = requireSurveyAssistantTurnState(context?.requestContext);
|
|
194
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
195
|
+
const defaultLocale = snapshot?.ui.selectedLocale ?? snapshot?.inspection.locales[0] ?? "en";
|
|
196
|
+
const continuationMode = inputData.continuationMode ?? void 0;
|
|
197
|
+
const operationsParse = z.array(surveyOperationSchema).safeParse(normalizeSurveyChangeOperations(inputData.operations, defaultLocale));
|
|
198
|
+
if (!operationsParse.success) return changeCollector.register(rejectedOperationParseEvent({
|
|
199
|
+
summary: inputData.summary,
|
|
200
|
+
turnId,
|
|
201
|
+
issueText: operationsParse.error.issues.slice(0, 8).map((issue) => `${issue.path.join(".") || "operation"}: ${issue.message}`).join("; ")
|
|
202
|
+
}), { continuationMode });
|
|
203
|
+
const event = createSurveyChangeSet({
|
|
204
|
+
operations: operationsParse.data,
|
|
205
|
+
snapshot,
|
|
206
|
+
summary: inputData.summary,
|
|
207
|
+
turnId
|
|
208
|
+
});
|
|
209
|
+
return changeCollector.register(event, { continuationMode });
|
|
210
|
+
},
|
|
211
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeValidation)
|
|
212
|
+
});
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/server/tools/survey-expression-tool.ts
|
|
215
|
+
const TOOL_ID$8 = "survey_expression";
|
|
216
|
+
const contextActionSchema = z.object({
|
|
217
|
+
action: z.literal("context"),
|
|
218
|
+
reason: z.string().max(500).optional(),
|
|
219
|
+
itemIds: z.array(z.string().min(1).max(240)).max(12).optional(),
|
|
220
|
+
includeRawLocations: z.boolean().optional()
|
|
221
|
+
});
|
|
222
|
+
const continuationModeSchema = z.enum(SURVEY_CHANGE_CONTINUATION_MODES).optional().describe(SURVEY_CHANGE_CONTINUATION_DESCRIPTION);
|
|
223
|
+
const prepareActionSchema = z.object({
|
|
224
|
+
action: z.literal("prepare"),
|
|
225
|
+
intent: z.string().min(1).max(500),
|
|
226
|
+
summary: z.string().min(1).max(500),
|
|
227
|
+
mutations: z.array(expressionMutationSchema).min(1).max(40),
|
|
228
|
+
continuationMode: continuationModeSchema,
|
|
229
|
+
inspectedContext: z.array(z.string().max(240)).max(20).optional()
|
|
230
|
+
});
|
|
231
|
+
const inputSchema$8 = z.object({
|
|
232
|
+
action: z.enum(["context", "prepare"]).describe("Use context to inspect expression refs; use prepare to create expression edits."),
|
|
233
|
+
reason: z.string().max(500).optional(),
|
|
234
|
+
itemIds: z.array(z.string().min(1).max(240)).max(12).optional().describe("For context: optional item ids/keys to focus existing expression locations."),
|
|
235
|
+
includeRawLocations: z.boolean().optional().describe("For context: include existing expression locations by raw item."),
|
|
236
|
+
intent: z.string().min(1).max(500).optional().describe("For prepare: requested expression edit."),
|
|
237
|
+
summary: z.string().min(1).max(500).optional().describe("For prepare: user-facing summary."),
|
|
238
|
+
mutations: z.array(z.record(z.string(), z.unknown())).min(1).max(40).optional().describe("For prepare: expression mutation objects using kebab-case kind names. Item visibility shape: { kind: \"set-item-display-condition\", itemId: \"<existing-item-id>\", expression: { type: \"function\", functionName: \"eq\", arguments: [...] } }. expression is always CASE expression JSON, never a string or expression-language snippet. Other supported kinds set/clear component display/disabled conditions, validation expressions, prefills, and template values."),
|
|
239
|
+
continuationMode: continuationModeSchema,
|
|
240
|
+
inspectedContext: z.array(z.string().max(240)).max(20).optional()
|
|
241
|
+
}).superRefine((value, ctx) => {
|
|
242
|
+
if (value.action !== "prepare") return;
|
|
243
|
+
if (!value.intent) ctx.addIssue({
|
|
244
|
+
code: z.ZodIssueCode.custom,
|
|
245
|
+
path: ["intent"],
|
|
246
|
+
message: "Required for prepare."
|
|
247
|
+
});
|
|
248
|
+
if (!value.summary) ctx.addIssue({
|
|
249
|
+
code: z.ZodIssueCode.custom,
|
|
250
|
+
path: ["summary"],
|
|
251
|
+
message: "Required for prepare."
|
|
252
|
+
});
|
|
253
|
+
if (!value.mutations?.length) ctx.addIssue({
|
|
254
|
+
code: z.ZodIssueCode.custom,
|
|
255
|
+
path: ["mutations"],
|
|
256
|
+
message: "At least one mutation is required for prepare."
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
const contextOutputSchema = z.object({
|
|
260
|
+
ok: z.boolean(),
|
|
261
|
+
action: z.literal("context"),
|
|
262
|
+
modelSummary: z.string(),
|
|
263
|
+
responseSlots: z.array(z.object({
|
|
264
|
+
ref: z.string(),
|
|
265
|
+
valueType: z.string().optional()
|
|
266
|
+
})),
|
|
267
|
+
expressionLocations: z.array(z.object({
|
|
268
|
+
itemId: z.string(),
|
|
269
|
+
key: z.string(),
|
|
270
|
+
itemType: z.string(),
|
|
271
|
+
rawIndex: z.number().int().nonnegative(),
|
|
272
|
+
locations: z.array(z.string())
|
|
273
|
+
})).optional()
|
|
274
|
+
});
|
|
275
|
+
const outputSchema$7 = z.union([contextOutputSchema, surveyChangeSetSchema]);
|
|
276
|
+
const createIssue = ({ severity = "error", ...input }) => ({
|
|
277
|
+
severity,
|
|
278
|
+
...input
|
|
279
|
+
});
|
|
280
|
+
const buildResponseSlotTypes = (snapshot) => snapshot.responseSlotTypes;
|
|
281
|
+
const rejectedEvent = ({ issues, summary, turnId, warnings = [] }) => ({
|
|
282
|
+
protocolVersion: 1,
|
|
283
|
+
id: randomUUID(),
|
|
284
|
+
turnId,
|
|
285
|
+
status: "rejected",
|
|
286
|
+
summary,
|
|
287
|
+
operations: [],
|
|
288
|
+
validation: {
|
|
289
|
+
valid: false,
|
|
290
|
+
issues,
|
|
291
|
+
warnings,
|
|
292
|
+
normalizedOperations: []
|
|
293
|
+
},
|
|
294
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
295
|
+
});
|
|
296
|
+
const summarizeDraftEvent = (event) => {
|
|
297
|
+
const lines = [`${event.status === "validated" ? "Validated" : "Rejected"} expression change: ${event.summary}`, `Change id: ${event.id}`];
|
|
298
|
+
if (event.operations.length > 0) lines.push(`Operations: ${event.operations.map((operation) => operation.kind).join(", ")}`);
|
|
299
|
+
if (event.status === "rejected") lines.push("Apply status: this turn is blocked and will authorize no survey changes unless a later complete proposal validates with continuationMode \"replace\".");
|
|
300
|
+
if (event.supersedesChangeIds?.length) lines.push(event.status === "validated" ? `Queue: replaces ${event.supersedesChangeIds.length} earlier candidate proposal(s) from this response.` : `Queue: discarded ${event.supersedesChangeIds.length} earlier candidate proposal(s); their work is not retained or authorized.`);
|
|
301
|
+
if (event.validation.issues.length > 0) {
|
|
302
|
+
lines.push("Issues:");
|
|
303
|
+
for (const issue of event.validation.issues) lines.push(`- ${issue.code}: ${issue.message}`);
|
|
304
|
+
const issueCodes = new Set(event.validation.issues.map((issue) => issue.code));
|
|
305
|
+
if (issueCodes.has("change-mode-required")) lines.push("Recovery hint: retry the complete intended proposal with continuationMode \"append\" for independent additional work or \"replace\" for a correction. Nothing from the ambiguous sequence is currently authorized.");
|
|
306
|
+
if (issueCodes.has("change-mode-repair-required")) lines.push("Recovery hint: the turn remains blocked. Retry the complete intended proposal with continuationMode \"replace\". Only a validated replacement clears the block; after that, use \"append\" for later independent chunks.");
|
|
307
|
+
}
|
|
308
|
+
if (event.validation.warnings.length > 0) {
|
|
309
|
+
lines.push("Warnings:");
|
|
310
|
+
for (const warning of event.validation.warnings) lines.push(`- ${warning.code}: ${warning.message}`);
|
|
311
|
+
}
|
|
312
|
+
return lines.join("\n");
|
|
313
|
+
};
|
|
314
|
+
const buildContextOutput = (snapshot, input) => {
|
|
315
|
+
const rawItems = getRawSurveyItems(snapshot);
|
|
316
|
+
const responseSlotTypes = buildResponseSlotTypes(snapshot);
|
|
317
|
+
const responseSlots = Object.entries(responseSlotTypes).map(([ref, valueType]) => ({
|
|
318
|
+
ref,
|
|
319
|
+
...valueType ? { valueType } : {}
|
|
320
|
+
}));
|
|
321
|
+
const itemFilter = input.action === "context" && input.itemIds?.length ? new Set(input.itemIds) : void 0;
|
|
322
|
+
const expressionLocations = input.action === "context" && input.includeRawLocations === true ? rawItems.map((item, rawIndex) => {
|
|
323
|
+
if (itemFilter && !itemFilter.has(item.id) && !itemFilter.has(item.key)) return;
|
|
324
|
+
const locations = [
|
|
325
|
+
item.displayConditions?.root ? "displayConditions.root" : void 0,
|
|
326
|
+
...Object.keys(item.displayConditions?.components ?? {}).map((componentId) => `displayConditions.components.${componentId}`),
|
|
327
|
+
...Object.keys(item.disabledConditions?.components ?? {}).map((componentId) => `disabledConditions.components.${componentId}`),
|
|
328
|
+
...Object.keys(item.validations ?? {}).map((validationKey) => `validations.${validationKey}`),
|
|
329
|
+
...(item.prefills ?? []).map((prefill) => `prefills.${prefill.id}`)
|
|
330
|
+
].filter((location) => Boolean(location));
|
|
331
|
+
return {
|
|
332
|
+
itemId: item.id,
|
|
333
|
+
key: item.key,
|
|
334
|
+
itemType: item.itemType,
|
|
335
|
+
rawIndex,
|
|
336
|
+
locations
|
|
337
|
+
};
|
|
338
|
+
}).filter((entry) => Boolean(entry)) : void 0;
|
|
339
|
+
return {
|
|
340
|
+
ok: true,
|
|
341
|
+
action: "context",
|
|
342
|
+
modelSummary: [
|
|
343
|
+
"Expression capability loaded.",
|
|
344
|
+
"Use prepare mutations for display conditions, disabled conditions, validations, prefills, and template values.",
|
|
345
|
+
"Display, disabled, validation, and prefill.when expressions must return boolean.",
|
|
346
|
+
"Use response refs exactly as listed and check their value types before choosing functions.",
|
|
347
|
+
"For choice options: use eq(response reference, reference const) when the slot type is reference; use list_contains(response reference[], reference const) only when the slot type is reference[].",
|
|
348
|
+
`Response slots (${responseSlots.length}): ${responseSlots.slice(0, 80).map((slot) => `${slot.ref}${slot.valueType ? `:${slot.valueType}` : ""}`).join(", ")}`,
|
|
349
|
+
responseSlots.length > 80 ? "Response slot list truncated in summary; inspect context result for more." : void 0,
|
|
350
|
+
"Functions: and, or, not, eq, gt, gte, lt, lte, in_range, list_contains, sum, min, max, str_eq, date_eq.",
|
|
351
|
+
expressionLocations ? `Existing expression locations: ${expressionLocations.filter((entry) => entry.locations.length > 0).map((entry) => `${entry.key}(${entry.itemId}) -> ${entry.locations.join("|")}`).join("; ") || "none"}` : void 0
|
|
352
|
+
].filter((line) => Boolean(line)).join("\n"),
|
|
353
|
+
responseSlots,
|
|
354
|
+
...expressionLocations ? { expressionLocations } : {}
|
|
355
|
+
};
|
|
356
|
+
};
|
|
357
|
+
const surveyExpressionTool = createTool({
|
|
358
|
+
id: TOOL_ID$8,
|
|
359
|
+
description: "Inspect response refs or queue expression edits for CASE survey items already present in the live snapshot. Covers display and disabled conditions, validations, prefills, and template values. Newly proposed items are not visible until the response ends; embed their expressions in the same survey_change call that creates them. For prepare, omit continuationMode only on the first mutation call in a turn; every later mutation call must use \"append\" or \"replace\".",
|
|
360
|
+
inputSchema: inputSchema$8,
|
|
361
|
+
outputSchema: outputSchema$7,
|
|
362
|
+
mcp: { annotations: {
|
|
363
|
+
title: "Work with expressions",
|
|
364
|
+
readOnlyHint: false,
|
|
365
|
+
destructiveHint: false,
|
|
366
|
+
idempotentHint: false,
|
|
367
|
+
openWorldHint: false
|
|
368
|
+
} },
|
|
369
|
+
execute: async (inputData, context) => {
|
|
370
|
+
const input = inputData;
|
|
371
|
+
const requestContext = context?.requestContext;
|
|
372
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
373
|
+
if (!snapshot) {
|
|
374
|
+
if (input.action === "context") return {
|
|
375
|
+
ok: false,
|
|
376
|
+
action: "context",
|
|
377
|
+
modelSummary: "No live editor snapshot is available for expression work.",
|
|
378
|
+
responseSlots: []
|
|
379
|
+
};
|
|
380
|
+
const { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);
|
|
381
|
+
return changeCollector.register(rejectedEvent({
|
|
382
|
+
summary: input.summary ?? "Expression change",
|
|
383
|
+
turnId,
|
|
384
|
+
issues: [createIssue({
|
|
385
|
+
code: "missing-snapshot",
|
|
386
|
+
message: "No live editor snapshot is available for expression work."
|
|
387
|
+
})]
|
|
388
|
+
}), { continuationMode: input.continuationMode });
|
|
389
|
+
}
|
|
390
|
+
if (input.action === "context") {
|
|
391
|
+
const contextParse = contextActionSchema.safeParse(inputData);
|
|
392
|
+
return buildContextOutput(snapshot, contextParse.success ? contextParse.data : input);
|
|
393
|
+
}
|
|
394
|
+
const { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);
|
|
395
|
+
const register = (event) => changeCollector.register(event, { continuationMode: input.continuationMode });
|
|
396
|
+
const prepareParse = prepareActionSchema.safeParse(inputData);
|
|
397
|
+
if (!prepareParse.success) return register(rejectedEvent({
|
|
398
|
+
summary: input.summary ?? "Expression change",
|
|
399
|
+
turnId,
|
|
400
|
+
issues: [createIssue({
|
|
401
|
+
code: "invalid-expression-mutation-shape",
|
|
402
|
+
message: prepareParse.error.issues.slice(0, 8).map((issue) => `${issue.path.join(".") || "input"}: ${issue.message}`).join("; ")
|
|
403
|
+
})]
|
|
404
|
+
}));
|
|
405
|
+
const prepareInput = prepareParse.data;
|
|
406
|
+
const issues = [];
|
|
407
|
+
const patches = [];
|
|
408
|
+
const responseSlotTypes = buildResponseSlotTypes(snapshot);
|
|
409
|
+
prepareInput.mutations.forEach((mutation, operationIndex) => {
|
|
410
|
+
buildExpressionMutationPatches({
|
|
411
|
+
mutation,
|
|
412
|
+
operationIndex,
|
|
413
|
+
issues,
|
|
414
|
+
patches,
|
|
415
|
+
responseSlotTypes,
|
|
416
|
+
snapshot
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
const errors = issues.filter((issue) => issue.severity === "error");
|
|
420
|
+
const warnings = issues.filter((issue) => issue.severity === "warning");
|
|
421
|
+
if (errors.length > 0) return register(rejectedEvent({
|
|
422
|
+
summary: prepareInput.summary,
|
|
423
|
+
turnId,
|
|
424
|
+
issues: errors,
|
|
425
|
+
warnings
|
|
426
|
+
}));
|
|
427
|
+
if (patches.length === 0) return register(rejectedEvent({
|
|
428
|
+
summary: prepareInput.summary,
|
|
429
|
+
turnId,
|
|
430
|
+
issues: [createIssue({
|
|
431
|
+
code: "no-expression-patches",
|
|
432
|
+
message: "No expression patches were produced. Check whether the requested locations already match the target state."
|
|
433
|
+
})],
|
|
434
|
+
warnings
|
|
435
|
+
}));
|
|
436
|
+
const event = createSurveyChangeSet({
|
|
437
|
+
operations: [{
|
|
438
|
+
kind: "survey-json-patch",
|
|
439
|
+
patches
|
|
440
|
+
}],
|
|
441
|
+
snapshot,
|
|
442
|
+
summary: prepareInput.summary,
|
|
443
|
+
turnId
|
|
444
|
+
});
|
|
445
|
+
return register({
|
|
446
|
+
...event,
|
|
447
|
+
validation: {
|
|
448
|
+
...event.validation,
|
|
449
|
+
warnings: [...event.validation.warnings, ...warnings]
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
},
|
|
453
|
+
toModelOutput: (value) => toTextModelOutput(value, (output) => "action" in output && output.action === "context" ? output.modelSummary : summarizeDraftEvent(output))
|
|
454
|
+
});
|
|
455
|
+
//#endregion
|
|
456
|
+
//#region src/server/tools/survey-get-current-context-tool.ts
|
|
457
|
+
const TOOL_ID$7 = "survey_get_current_context";
|
|
458
|
+
const contextScopeSchema = z.enum([
|
|
459
|
+
"summary",
|
|
460
|
+
"selected-item",
|
|
461
|
+
"outline",
|
|
462
|
+
"response-slots",
|
|
463
|
+
"ui-context",
|
|
464
|
+
"history"
|
|
465
|
+
]);
|
|
466
|
+
const outlineModeSchema$1 = z.enum([
|
|
467
|
+
"full",
|
|
468
|
+
"focused",
|
|
469
|
+
"children"
|
|
470
|
+
]);
|
|
471
|
+
const translationSnippetSchema = z.object({
|
|
472
|
+
locale: z.string(),
|
|
473
|
+
contentKey: z.string(),
|
|
474
|
+
text: z.string()
|
|
475
|
+
});
|
|
476
|
+
const inputSchema$7 = z.object({
|
|
477
|
+
scopes: z.array(contextScopeSchema).min(1).default(["summary"]).describe("Which current editor context sections to inspect."),
|
|
478
|
+
itemId: z.string().optional().describe("Optional item id to inspect. Defaults to the selected/focused item."),
|
|
479
|
+
query: z.string().max(160).optional().describe("Optional text used to find matching item ids, keys, labels, or response slots."),
|
|
480
|
+
cursor: z.string().optional().describe("Optional numeric cursor returned by a previous outline or response slot request."),
|
|
481
|
+
outlineMode: outlineModeSchema$1.default("full").optional().describe("For outline scope: \"full\" pages the complete survey key index, \"focused\" returns the selected/focused neighborhood, and \"children\" returns direct children of itemId."),
|
|
482
|
+
limit: z.number().int().min(1).max(50).default(12).describe("Maximum number of rows to return for list-like scopes.")
|
|
483
|
+
});
|
|
484
|
+
const outputSchema$6 = z.object({
|
|
485
|
+
ok: z.boolean(),
|
|
486
|
+
reason: z.string().optional(),
|
|
487
|
+
revision: z.number().int().nonnegative().optional(),
|
|
488
|
+
contentHash: z.string().optional(),
|
|
489
|
+
scopes: z.array(contextScopeSchema).optional(),
|
|
490
|
+
summary: z.object({
|
|
491
|
+
sessionId: z.string().nullable(),
|
|
492
|
+
view: z.string(),
|
|
493
|
+
selectedItemId: z.string().optional(),
|
|
494
|
+
focusItemId: z.string().optional(),
|
|
495
|
+
selectedLocale: z.string(),
|
|
496
|
+
recentItemIds: z.array(z.string()),
|
|
497
|
+
surveyKey: z.string().optional(),
|
|
498
|
+
locales: z.array(z.string()),
|
|
499
|
+
itemCount: z.number().int().nonnegative(),
|
|
500
|
+
historyIndex: z.number().int(),
|
|
501
|
+
outlineItemCount: z.number().int().nonnegative(),
|
|
502
|
+
responseSlotCount: z.number().int().nonnegative(),
|
|
503
|
+
rootItem: itemSummarySchema.optional(),
|
|
504
|
+
availableItemTypes: z.array(z.string()),
|
|
505
|
+
deterministicCreateItemTypes: z.array(z.string()),
|
|
506
|
+
itemTypeDetails: z.array(assistantItemTypeManifestSchema)
|
|
507
|
+
}).optional(),
|
|
508
|
+
selectedItem: z.object({
|
|
509
|
+
available: z.boolean(),
|
|
510
|
+
reason: z.string().optional(),
|
|
511
|
+
requestedItemId: z.string().optional(),
|
|
512
|
+
item: itemSummarySchema.optional(),
|
|
513
|
+
relationSource: z.string().optional(),
|
|
514
|
+
pathItems: z.array(itemSummarySchema).optional(),
|
|
515
|
+
siblingItems: z.array(itemSummarySchema).optional(),
|
|
516
|
+
childItems: z.array(itemSummarySchema).optional(),
|
|
517
|
+
translationSnippets: z.array(translationSnippetSchema).optional(),
|
|
518
|
+
descendantItems: z.array(itemSummarySchema).optional(),
|
|
519
|
+
descendantCount: z.number().int().nonnegative().optional(),
|
|
520
|
+
descendantsTruncated: z.boolean().optional()
|
|
521
|
+
}).optional(),
|
|
522
|
+
outline: z.object({
|
|
523
|
+
strategy: z.string(),
|
|
524
|
+
mode: outlineModeSchema$1.optional(),
|
|
525
|
+
query: z.string().optional(),
|
|
526
|
+
requestedItemId: z.string().optional(),
|
|
527
|
+
totalAvailable: z.number().int().nonnegative(),
|
|
528
|
+
returned: z.number().int().nonnegative(),
|
|
529
|
+
nextCursor: z.string().optional(),
|
|
530
|
+
truncated: z.boolean(),
|
|
531
|
+
items: z.array(itemSummarySchema),
|
|
532
|
+
note: z.string().optional()
|
|
533
|
+
}).optional(),
|
|
534
|
+
responseSlots: z.object({
|
|
535
|
+
available: z.boolean(),
|
|
536
|
+
query: z.string().optional(),
|
|
537
|
+
totalAvailable: z.number().int().nonnegative(),
|
|
538
|
+
returned: z.number().int().nonnegative(),
|
|
539
|
+
nextCursor: z.string().optional(),
|
|
540
|
+
truncated: z.boolean(),
|
|
541
|
+
slots: z.array(z.string()),
|
|
542
|
+
note: z.string().optional()
|
|
543
|
+
}).optional(),
|
|
544
|
+
uiContext: z.object({
|
|
545
|
+
activeSurface: z.string().optional(),
|
|
546
|
+
openPanels: z.array(z.string()),
|
|
547
|
+
highlights: z.array(z.object({
|
|
548
|
+
kind: z.string(),
|
|
549
|
+
itemId: z.string().optional(),
|
|
550
|
+
componentId: z.string().optional(),
|
|
551
|
+
label: z.string().optional(),
|
|
552
|
+
details: z.string().optional()
|
|
553
|
+
}))
|
|
554
|
+
}).optional(),
|
|
555
|
+
history: z.object({
|
|
556
|
+
currentIndex: z.number().int(),
|
|
557
|
+
totalEntries: z.number().int().nonnegative(),
|
|
558
|
+
canUndo: z.boolean(),
|
|
559
|
+
canRedo: z.boolean(),
|
|
560
|
+
recent: z.array(z.object({
|
|
561
|
+
index: z.number().int(),
|
|
562
|
+
kind: z.enum(["survey-snapshot", "asset-change"]),
|
|
563
|
+
label: z.string(),
|
|
564
|
+
source: z.enum([
|
|
565
|
+
"user",
|
|
566
|
+
"system",
|
|
567
|
+
"assistant"
|
|
568
|
+
]).optional(),
|
|
569
|
+
timestamp: z.number(),
|
|
570
|
+
isCurrent: z.boolean()
|
|
571
|
+
}))
|
|
572
|
+
}).optional()
|
|
573
|
+
});
|
|
574
|
+
const findFocusItemNode = (node, itemId) => {
|
|
575
|
+
if (!node) return;
|
|
576
|
+
if (node.itemId === itemId) return node;
|
|
577
|
+
for (const descendant of node.descendants) {
|
|
578
|
+
const match = findFocusItemNode(descendant, itemId);
|
|
579
|
+
if (match) return match;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
const flattenFocusDescendants = (node) => {
|
|
583
|
+
const descendants = [];
|
|
584
|
+
const visit = (current) => {
|
|
585
|
+
for (const descendant of current.descendants) {
|
|
586
|
+
descendants.push(descendant);
|
|
587
|
+
visit(descendant);
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
visit(node);
|
|
591
|
+
return descendants;
|
|
592
|
+
};
|
|
593
|
+
const getCandidateItems = (snapshot) => {
|
|
594
|
+
const outlineById = mapOutlineById(snapshot);
|
|
595
|
+
return summarizeKeyIndexEntries(getKeyIndexEntries(snapshot), outlineById);
|
|
596
|
+
};
|
|
597
|
+
const buildSummary = (snapshot) => ({
|
|
598
|
+
rootItem: snapshot.inspection.outline.filter((item) => item.depth === 0).map(summarizeOutlineNode)[0],
|
|
599
|
+
sessionId: snapshot.version.sessionId,
|
|
600
|
+
view: snapshot.ui.view,
|
|
601
|
+
selectedItemId: snapshot.ui.selectedItemId,
|
|
602
|
+
focusItemId: snapshot.ui.focusItemId,
|
|
603
|
+
selectedLocale: snapshot.ui.selectedLocale,
|
|
604
|
+
recentItemIds: snapshot.ui.recentItemIds ?? [],
|
|
605
|
+
surveyKey: snapshot.inspection.surveyKey,
|
|
606
|
+
locales: snapshot.inspection.locales,
|
|
607
|
+
itemCount: snapshot.inspection.itemCount,
|
|
608
|
+
historyIndex: snapshot.version.historyIndex,
|
|
609
|
+
outlineItemCount: snapshot.inspection.keyIndex.length,
|
|
610
|
+
responseSlotCount: snapshot.inspection.responseSlots.length,
|
|
611
|
+
availableItemTypes: snapshot.capabilities.itemTypes.map((entry) => entry.itemType),
|
|
612
|
+
deterministicCreateItemTypes: getDeterministicCreateItemTypes(snapshot.capabilities),
|
|
613
|
+
itemTypeDetails: snapshot.capabilities.itemTypes
|
|
614
|
+
});
|
|
615
|
+
const buildSelectedItem = (snapshot, input) => {
|
|
616
|
+
const outlineById = mapOutlineById(snapshot);
|
|
617
|
+
const indexById = mapKeyIndexById(snapshot);
|
|
618
|
+
const resolvedInputItem = input.itemId ? resolveItemSummary(input.itemId, indexById, outlineById) : void 0;
|
|
619
|
+
const requestedItemId = resolvedInputItem?.itemId ?? input.itemId ?? snapshot.ui.selectedItemId ?? snapshot.ui.focusItemId;
|
|
620
|
+
if (!requestedItemId) return {
|
|
621
|
+
available: false,
|
|
622
|
+
reason: "No item is currently selected or focused in the editor."
|
|
623
|
+
};
|
|
624
|
+
const focusNode = findFocusItemNode(snapshot.inspection.focusItem, requestedItemId);
|
|
625
|
+
const item = focusNode ? summarizeFocusItemNode(focusNode, outlineById) : resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById);
|
|
626
|
+
if (!item) return {
|
|
627
|
+
available: false,
|
|
628
|
+
requestedItemId,
|
|
629
|
+
reason: "The requested item is not present in the current context snapshot."
|
|
630
|
+
};
|
|
631
|
+
const limit = clampLimit(input.limit);
|
|
632
|
+
const descendants = focusNode ? flattenFocusDescendants(focusNode) : [];
|
|
633
|
+
return {
|
|
634
|
+
available: true,
|
|
635
|
+
requestedItemId,
|
|
636
|
+
item,
|
|
637
|
+
relationSource: snapshot.inspection.focus?.focusItemId === requestedItemId ? "selected-focus" : focusNode ? "focused-subtree" : "key-index",
|
|
638
|
+
pathItems: snapshot.inspection.focus?.pathItemIds?.map((itemId) => summarizeItemById(itemId, indexById, outlineById)).filter((entry) => Boolean(entry)),
|
|
639
|
+
siblingItems: snapshot.inspection.focus?.siblingItemIds?.map((itemId) => summarizeItemById(itemId, indexById, outlineById)).filter((entry) => Boolean(entry)),
|
|
640
|
+
childItems: snapshot.inspection.focus?.childItemIds?.map((itemId) => summarizeItemById(itemId, indexById, outlineById)).filter((entry) => Boolean(entry)),
|
|
641
|
+
translationSnippets: focusNode?.translations.slice(0, limit),
|
|
642
|
+
descendantItems: descendants.slice(0, limit).map((descendant) => summarizeFocusItemNode(descendant, outlineById)),
|
|
643
|
+
descendantCount: descendants.length,
|
|
644
|
+
descendantsTruncated: descendants.length > limit || snapshot.inspection.focusItemTreeTruncated
|
|
645
|
+
};
|
|
646
|
+
};
|
|
647
|
+
const buildOutline = (snapshot, input) => {
|
|
648
|
+
const query = normalizeText(input.query);
|
|
649
|
+
const outlineById = mapOutlineById(snapshot);
|
|
650
|
+
const indexById = mapKeyIndexById(snapshot);
|
|
651
|
+
const resolvedInputItem = input.itemId ? resolveItemSummary(input.itemId, indexById, outlineById) : void 0;
|
|
652
|
+
const requestedItemId = resolvedInputItem?.itemId ?? input.itemId ?? snapshot.ui.focusItemId ?? snapshot.ui.selectedItemId;
|
|
653
|
+
const outlineMode = input.outlineMode ?? "full";
|
|
654
|
+
let strategy = "focused-snapshot-outline";
|
|
655
|
+
let items;
|
|
656
|
+
let note;
|
|
657
|
+
if (query) {
|
|
658
|
+
strategy = "query-match";
|
|
659
|
+
items = getCandidateItems(snapshot).filter((item) => itemMatchesQuery(item, query));
|
|
660
|
+
} else if (outlineMode === "children" && requestedItemId) {
|
|
661
|
+
strategy = "direct-children";
|
|
662
|
+
const parent = resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById);
|
|
663
|
+
items = parent ? findDirectChildrenByFullKey(getKeyIndexEntries(snapshot), outlineById, parent.fullKey) : [];
|
|
664
|
+
if (!parent) note = "The requested item could not be resolved by item id, key, or fullKey.";
|
|
665
|
+
} else if (outlineMode === "focused" && requestedItemId && snapshot.inspection.focus?.focusItemId === requestedItemId) {
|
|
666
|
+
const focus = snapshot.inspection.focus;
|
|
667
|
+
const descendantIds = snapshot.inspection.focusItem ? flattenFocusDescendants(snapshot.inspection.focusItem).map((item) => item.itemId) : [];
|
|
668
|
+
items = unique([
|
|
669
|
+
...focus.pathItemIds,
|
|
670
|
+
requestedItemId,
|
|
671
|
+
...focus.childItemIds,
|
|
672
|
+
...focus.siblingItemIds,
|
|
673
|
+
...descendantIds
|
|
674
|
+
]).map((itemId) => summarizeItemById(itemId, indexById, outlineById)).filter((entry) => Boolean(entry));
|
|
675
|
+
} else if (outlineMode === "focused" && requestedItemId) {
|
|
676
|
+
strategy = "item-match";
|
|
677
|
+
const item = resolvedInputItem ?? summarizeItemById(requestedItemId, indexById, outlineById);
|
|
678
|
+
items = item ? [item] : [];
|
|
679
|
+
note = "The requested item is outside the selected focus tree in this snapshot.";
|
|
680
|
+
} else {
|
|
681
|
+
strategy = "full-key-index";
|
|
682
|
+
items = getCandidateItems(snapshot);
|
|
683
|
+
}
|
|
684
|
+
const page = sliceWithCursor(items, input);
|
|
685
|
+
return {
|
|
686
|
+
strategy,
|
|
687
|
+
mode: outlineMode,
|
|
688
|
+
query: input.query,
|
|
689
|
+
requestedItemId,
|
|
690
|
+
totalAvailable: items.length,
|
|
691
|
+
returned: page.items.length,
|
|
692
|
+
nextCursor: page.nextCursor,
|
|
693
|
+
truncated: page.truncated,
|
|
694
|
+
items: page.items,
|
|
695
|
+
note
|
|
696
|
+
};
|
|
697
|
+
};
|
|
698
|
+
const buildResponseSlots = (snapshot, input) => {
|
|
699
|
+
const responseSlots = snapshot.inspection.responseSlots;
|
|
700
|
+
const query = normalizeText(input.query);
|
|
701
|
+
const filtered = query ? responseSlots.filter((slot) => slot.toLowerCase().includes(query)) : responseSlots;
|
|
702
|
+
const page = sliceWithCursor(filtered, input);
|
|
703
|
+
return {
|
|
704
|
+
available: true,
|
|
705
|
+
query: input.query,
|
|
706
|
+
totalAvailable: filtered.length,
|
|
707
|
+
returned: page.items.length,
|
|
708
|
+
nextCursor: page.nextCursor,
|
|
709
|
+
truncated: page.truncated,
|
|
710
|
+
slots: page.items
|
|
711
|
+
};
|
|
712
|
+
};
|
|
713
|
+
const summarizeForModel$3 = (output) => {
|
|
714
|
+
if (!output.ok) return output.reason ?? "Current editor context is unavailable.";
|
|
715
|
+
const lines = [`Snapshot revision ${output.revision}, content hash ${output.contentHash}.`];
|
|
716
|
+
if (output.summary) {
|
|
717
|
+
const selected = output.summary.selectedItemId ?? "none";
|
|
718
|
+
const surveyKey = output.summary.surveyKey ?? "not set";
|
|
719
|
+
lines.push(`Summary: view=${output.summary.view}; selectedItemId=${selected}; locale=${output.summary.selectedLocale}; surveyKey=${surveyKey}; itemCount=${output.summary.itemCount}.`);
|
|
720
|
+
if (output.summary.rootItem) lines.push(`Root group for top-level create-item target.parentItemId: ${output.summary.rootItem.fullKey} (id=${output.summary.rootItem.itemId}, key=${output.summary.rootItem.key}).`);
|
|
721
|
+
lines.push(`Outline access: ${output.summary.outlineItemCount} item(s) are pageable.`);
|
|
722
|
+
const creatableDetails = output.summary.itemTypeDetails.filter((entry) => entry.create === "deterministic").map((entry) => {
|
|
723
|
+
const primarySurface = entry.contentSurfaces.find((surface) => surface.role === "primary");
|
|
724
|
+
const fixedSurfaces = entry.contentSurfaces.filter((surface) => !surface.pattern).map((surface) => surface.key);
|
|
725
|
+
const patterns = entry.contentSurfaces.filter((surface) => surface.pattern).map((surface) => surface.key);
|
|
726
|
+
const contentKeys = [
|
|
727
|
+
primarySurface ? `primary=${primarySurface.key}` : void 0,
|
|
728
|
+
fixedSurfaces.length ? `visible=${fixedSurfaces.join("|")}` : void 0,
|
|
729
|
+
patterns.length ? `dynamic=${patterns.join("|")}` : void 0
|
|
730
|
+
].filter((value) => Boolean(value)).join("; ");
|
|
731
|
+
return contentKeys ? `${entry.itemType} (${contentKeys})` : entry.itemType;
|
|
732
|
+
});
|
|
733
|
+
if (creatableDetails.length > 0) lines.push(`Creatable item types: ${creatableDetails.join(", ")}.`);
|
|
734
|
+
}
|
|
735
|
+
if (output.selectedItem) if (output.selectedItem.available && output.selectedItem.item) {
|
|
736
|
+
lines.push(`Selected item: ${output.selectedItem.item.fullKey} (${output.selectedItem.item.itemType})${output.selectedItem.item.itemLabel ? ` - ${output.selectedItem.item.itemLabel}` : ""}.`);
|
|
737
|
+
if (output.selectedItem.translationSnippets?.length) lines.push(`Translation snippets: ${output.selectedItem.translationSnippets.map((entry) => `${entry.locale}.${entry.contentKey}: ${entry.text}`).join("; ")}`);
|
|
738
|
+
} else lines.push(`Selected item unavailable: ${output.selectedItem.reason ?? "unknown reason"}.`);
|
|
739
|
+
if (output.outline) {
|
|
740
|
+
lines.push(`Outline (${output.outline.strategy}${output.outline.mode ? `, mode=${output.outline.mode}` : ""}): ${output.outline.returned}/${output.outline.totalAvailable} rows returned.`);
|
|
741
|
+
for (const item of output.outline.items) lines.push(`- ${item.fullKey} (${item.itemType})${item.itemLabel ? ` - ${item.itemLabel}` : ""}`);
|
|
742
|
+
if (output.outline.nextCursor) lines.push(`More outline rows are available with cursor ${output.outline.nextCursor}.`);
|
|
743
|
+
}
|
|
744
|
+
if (output.responseSlots) lines.push(output.responseSlots.available ? `Response slots: ${output.responseSlots.slots.join(", ") || "none"}` : `Response slots unavailable: ${output.responseSlots.note ?? "not indexed"}.`);
|
|
745
|
+
if (output.uiContext) lines.push(`UI context: activeSurface=${output.uiContext.activeSurface ?? "not provided"}; openPanels=${output.uiContext.openPanels.join(", ") || "none"}; highlights=${output.uiContext.highlights.map((entry) => entry.label ?? entry.itemId ?? entry.componentId ?? entry.kind).join(", ") || "none"}.`);
|
|
746
|
+
if (output.history) lines.push(`Recent editor history (${output.history.currentIndex + 1}/${output.history.totalEntries}): ${output.history.recent.map((entry) => `${entry.index}:${entry.label}${entry.isCurrent ? " [current]" : ""}`).join("; ") || "none"}.`);
|
|
747
|
+
return lines.join("\n");
|
|
748
|
+
};
|
|
749
|
+
const surveyGetCurrentContextTool = createTool({
|
|
750
|
+
id: TOOL_ID$7,
|
|
751
|
+
description: "Read the current Survey Editor context from the latest request snapshot. Use for questions about this screen, selected item, survey outline, item keys, labels, locales, or response slots. The outline scope can page the complete survey key index, so use cursor/limit instead of guessing when a focused outline is truncated.",
|
|
752
|
+
inputSchema: inputSchema$7,
|
|
753
|
+
outputSchema: outputSchema$6,
|
|
754
|
+
mcp: { annotations: {
|
|
755
|
+
title: "Get current survey context",
|
|
756
|
+
readOnlyHint: true,
|
|
757
|
+
destructiveHint: false,
|
|
758
|
+
idempotentHint: true,
|
|
759
|
+
openWorldHint: false
|
|
760
|
+
} },
|
|
761
|
+
execute: async (inputData, context) => {
|
|
762
|
+
const input = {
|
|
763
|
+
...inputData,
|
|
764
|
+
scopes: inputData.scopes ?? ["summary"],
|
|
765
|
+
limit: inputData.limit ?? 12,
|
|
766
|
+
outlineMode: inputData.outlineMode ?? "full"
|
|
767
|
+
};
|
|
768
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
769
|
+
if (!snapshot) return {
|
|
770
|
+
ok: false,
|
|
771
|
+
reason: "No live editor snapshot was provided with this assistant turn.",
|
|
772
|
+
scopes: input.scopes
|
|
773
|
+
};
|
|
774
|
+
const scopes = unique(input.scopes);
|
|
775
|
+
const output = {
|
|
776
|
+
ok: true,
|
|
777
|
+
revision: snapshot.version.revision,
|
|
778
|
+
contentHash: snapshot.version.contentHash,
|
|
779
|
+
scopes
|
|
780
|
+
};
|
|
781
|
+
if (scopes.includes("summary")) output.summary = buildSummary(snapshot);
|
|
782
|
+
if (scopes.includes("selected-item")) output.selectedItem = buildSelectedItem(snapshot, input);
|
|
783
|
+
if (scopes.includes("outline")) output.outline = buildOutline(snapshot, input);
|
|
784
|
+
if (scopes.includes("response-slots")) output.responseSlots = buildResponseSlots(snapshot, input);
|
|
785
|
+
if (scopes.includes("ui-context")) output.uiContext = {
|
|
786
|
+
activeSurface: snapshot.ui.activeSurface,
|
|
787
|
+
openPanels: snapshot.ui.openPanels ?? [],
|
|
788
|
+
highlights: snapshot.ui.highlights ?? []
|
|
789
|
+
};
|
|
790
|
+
if (scopes.includes("history") && snapshot.ui.history) output.history = snapshot.ui.history;
|
|
791
|
+
return output;
|
|
792
|
+
},
|
|
793
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeForModel$3)
|
|
794
|
+
});
|
|
795
|
+
//#endregion
|
|
796
|
+
//#region src/server/tools/survey-get-item-details-tool.ts
|
|
797
|
+
const TOOL_ID$6 = "survey_get_item_details";
|
|
798
|
+
const DEFAULT_TEXT_LIMIT$1 = 400;
|
|
799
|
+
const MAX_TEXT_LIMIT = 2e3;
|
|
800
|
+
const DEFAULT_CHILDREN_LIMIT = 20;
|
|
801
|
+
const inputSchema$6 = z.object({
|
|
802
|
+
itemId: z.string().describe("Identifier of the item to inspect: its itemId, key (e.g. \"info_1\"), or fullKey (e.g. \"survey.info_1\"). Discover candidates first via survey_inspect search or current context."),
|
|
803
|
+
locales: z.array(z.string()).optional().describe("Optional locale codes to restrict returned translations to. Defaults to all locales."),
|
|
804
|
+
textLimit: z.number().int().min(20).max(MAX_TEXT_LIMIT).default(DEFAULT_TEXT_LIMIT$1).describe("Maximum characters returned per translation snippet."),
|
|
805
|
+
includeChildren: z.boolean().optional().describe("Deprecated alias for includeSurveyChildren. This means survey-tree children only, not choice options or form fields."),
|
|
806
|
+
includeSurveyChildren: z.boolean().default(false).describe("Whether to include a shallow list of this item's direct survey-tree children, such as group members."),
|
|
807
|
+
includeItemConfig: z.boolean().default(true).describe("Whether to include item-internal config details such as choice options and form field groups."),
|
|
808
|
+
childrenLimit: z.number().int().min(1).max(50).default(DEFAULT_CHILDREN_LIMIT).describe("Maximum number of direct survey-tree children to return.")
|
|
809
|
+
});
|
|
810
|
+
const outputSchema$5 = z.object({
|
|
811
|
+
ok: z.boolean(),
|
|
812
|
+
reason: z.string().optional(),
|
|
813
|
+
item: itemSummarySchema.optional(),
|
|
814
|
+
translations: z.array(translationEntrySchema).optional(),
|
|
815
|
+
surveyChildren: z.array(itemSummarySchema).optional(),
|
|
816
|
+
surveyChildrenTruncated: z.boolean().optional(),
|
|
817
|
+
configDetails: itemConfigDetailsSchema.optional(),
|
|
818
|
+
capabilityDetails: z.object({
|
|
819
|
+
summary: z.string(),
|
|
820
|
+
details: z.unknown().optional()
|
|
821
|
+
}).optional()
|
|
822
|
+
});
|
|
823
|
+
const summarizeConfigDetails = (configDetails) => {
|
|
824
|
+
const lines = [`Config details (${configDetails.kind}): ${configDetails.summary.join("; ")}`];
|
|
825
|
+
if (configDetails.mainResponseSlotId) lines.push(`Main response slot: ${configDetails.mainResponseSlotId}`);
|
|
826
|
+
for (const option of configDetails.choiceOptions ?? []) {
|
|
827
|
+
lines.push(`- option ${option.key ?? option.id} (id=${option.id}, labelContentKey=${option.labelContentKey})`);
|
|
828
|
+
if (option.embeddedFormItemId || option.embeddedFormFieldGroupCount) {
|
|
829
|
+
lines.push(` embedded form: itemId=${option.embeddedFormItemId ?? "inline"}, fieldGroups=${option.embeddedFormFieldGroupCount ?? 0}`);
|
|
830
|
+
if (option.embeddedFormTranslationPrefix || option.embeddedFormResponseSlotPrefix) lines.push(` embedded form keys: translationPrefix=${option.embeddedFormTranslationPrefix ?? "n/a"}, responseSlotPrefix=${option.embeddedFormResponseSlotPrefix ?? "n/a"}`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
for (const group of configDetails.formFieldGroups ?? []) {
|
|
834
|
+
lines.push(`- field group ${group.id}: ${group.fieldCount} field(s), titleContentKey=${group.titleContentKey}, layout=${group.layout.base}/${group.layout.xs}/${group.layout.sm}/${group.layout.md}/${group.layout.xl}`);
|
|
835
|
+
if (group.hasDisplayCondition !== void 0) lines.push(` hasDisplayCondition=${group.hasDisplayCondition ? "true" : "false"}`);
|
|
836
|
+
for (const field of group.fields) {
|
|
837
|
+
lines.push(` - field ${field.key} (${field.type}, id=${field.id}, responseSlot=${field.responseSlotId}, labelContentKey=${field.labelContentKey})`);
|
|
838
|
+
lines.push(` extra content keys: description=${field.descriptionContentKey}, error=${field.errorContentKey}${field.placeholderContentKey ? `, placeholder=${field.placeholderContentKey}` : ""}${field.unitContentKey ? `, unit=${field.unitContentKey}` : ""}${field.checkedLabelContentKey ? `, checkedLabel=${field.checkedLabelContentKey}` : ""}${field.uncheckedLabelContentKey ? `, uncheckedLabel=${field.uncheckedLabelContentKey}` : ""}`);
|
|
839
|
+
if (field.validationTypes?.length) lines.push(` validations: ${field.validationTypes.join(", ")}`);
|
|
840
|
+
if (field.validationMessageContentKeys?.length) lines.push(` validation message keys: ${field.validationMessageContentKeys.join(", ")}`);
|
|
841
|
+
if (field.selectOptions?.length) lines.push(` select options: ${field.selectOptions.map((option) => `${option.value ?? option.id} (${option.labelContentKey})`).join(", ")}`);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
return lines;
|
|
845
|
+
};
|
|
846
|
+
const summarizeForModel$2 = (output) => {
|
|
847
|
+
if (!output.ok) return output.reason ?? "Item details are unavailable.";
|
|
848
|
+
const lines = [];
|
|
849
|
+
if (output.item) lines.push(`Item: ${output.item.fullKey} (${output.item.itemType})${output.item.itemLabel ? ` - ${output.item.itemLabel}` : ""}.`);
|
|
850
|
+
if (output.translations?.length) lines.push(`Translations: ${output.translations.map((entry) => `${entry.locale}.${entry.contentKey}: ${entry.text}`).join("; ")}`);
|
|
851
|
+
else lines.push("Translations: none found for this item.");
|
|
852
|
+
if (output.surveyChildren) {
|
|
853
|
+
lines.push(`Survey-tree children (${output.surveyChildren.length}):`);
|
|
854
|
+
for (const child of output.surveyChildren) lines.push(`- ${child.fullKey} (${child.itemType})${child.itemLabel ? ` - ${child.itemLabel}` : ""}`);
|
|
855
|
+
if (output.surveyChildrenTruncated) lines.push("More children exist than were returned; narrow down or raise childrenLimit.");
|
|
856
|
+
}
|
|
857
|
+
if (output.configDetails) lines.push(...summarizeConfigDetails(output.configDetails));
|
|
858
|
+
if (output.capabilityDetails) {
|
|
859
|
+
lines.push(`Item capability: ${output.capabilityDetails.summary}`);
|
|
860
|
+
if (output.capabilityDetails.details !== void 0) lines.push(`Capability details: ${JSON.stringify(output.capabilityDetails.details)}`);
|
|
861
|
+
}
|
|
862
|
+
return lines.join("\n");
|
|
863
|
+
};
|
|
864
|
+
const surveyGetItemDetailsTool = createTool({
|
|
865
|
+
id: TOOL_ID$6,
|
|
866
|
+
description: "Fetch full details for a SPECIFIC survey item, whether or not it is currently selected. Returns item translations plus item-internal config details such as choice options and form fields. Use survey_search_items first when you only know visible text.",
|
|
867
|
+
inputSchema: inputSchema$6,
|
|
868
|
+
outputSchema: outputSchema$5,
|
|
869
|
+
mcp: { annotations: {
|
|
870
|
+
title: "Get survey item details",
|
|
871
|
+
readOnlyHint: true,
|
|
872
|
+
destructiveHint: false,
|
|
873
|
+
idempotentHint: true,
|
|
874
|
+
openWorldHint: false
|
|
875
|
+
} },
|
|
876
|
+
execute: async (inputData, context) => {
|
|
877
|
+
const input = {
|
|
878
|
+
...inputData,
|
|
879
|
+
textLimit: inputData.textLimit ?? DEFAULT_TEXT_LIMIT$1,
|
|
880
|
+
includeSurveyChildren: inputData.includeSurveyChildren ?? inputData.includeChildren ?? false,
|
|
881
|
+
includeItemConfig: inputData.includeItemConfig ?? true,
|
|
882
|
+
childrenLimit: inputData.childrenLimit ?? DEFAULT_CHILDREN_LIMIT
|
|
883
|
+
};
|
|
884
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
885
|
+
if (!snapshot) return {
|
|
886
|
+
ok: false,
|
|
887
|
+
reason: "No live editor snapshot was provided with this assistant turn."
|
|
888
|
+
};
|
|
889
|
+
const outlineById = mapOutlineById(snapshot);
|
|
890
|
+
const indexById = mapKeyIndexById(snapshot);
|
|
891
|
+
const rawItemsById = mapRawItemsById(snapshot);
|
|
892
|
+
const item = resolveItemSummary(input.itemId, indexById, outlineById);
|
|
893
|
+
if (!item) return {
|
|
894
|
+
ok: false,
|
|
895
|
+
reason: `No item matching "${input.itemId}" (by itemId, key, or fullKey) was found in the current context snapshot.`
|
|
896
|
+
};
|
|
897
|
+
const output = {
|
|
898
|
+
ok: true,
|
|
899
|
+
item,
|
|
900
|
+
translations: buildItemTranslationEntries(snapshot, item.itemId, input)
|
|
901
|
+
};
|
|
902
|
+
if (input.includeSurveyChildren) {
|
|
903
|
+
const allChildren = findDirectChildrenByFullKey(getKeyIndexEntries(snapshot), outlineById, item.fullKey);
|
|
904
|
+
const limit = clampLimit(input.childrenLimit);
|
|
905
|
+
output.surveyChildren = allChildren.slice(0, limit);
|
|
906
|
+
output.surveyChildrenTruncated = allChildren.length > limit;
|
|
907
|
+
}
|
|
908
|
+
if (input.includeItemConfig) {
|
|
909
|
+
const rawItem = rawItemsById.get(item.itemId);
|
|
910
|
+
output.configDetails = rawItem ? buildItemConfigDetails(rawItem) : void 0;
|
|
911
|
+
output.capabilityDetails = rawItem ? inspectAssistantItem({
|
|
912
|
+
capabilities: snapshot.trustedCapabilities,
|
|
913
|
+
item: rawItem
|
|
914
|
+
}) : void 0;
|
|
915
|
+
if (rawItem?.itemType === "choiceItem" && output.configDetails?.choiceOptions) {
|
|
916
|
+
const rawConfig = rawItem.config && typeof rawItem.config === "object" && !Array.isArray(rawItem.config) ? rawItem.config : void 0;
|
|
917
|
+
const rawOptions = Array.isArray(rawConfig?.options) ? rawConfig.options : [];
|
|
918
|
+
for (const option of output.configDetails.choiceOptions) {
|
|
919
|
+
const rawOption = rawOptions.find((candidate) => candidate && typeof candidate === "object" && "id" in candidate && candidate.id === option.id);
|
|
920
|
+
const embeddedFormDetails = buildEmbeddedFormDetails(option, rawOption && typeof rawOption === "object" && "embeddedForm" in rawOption ? rawOption.embeddedForm : void 0);
|
|
921
|
+
if (embeddedFormDetails?.formFieldGroups?.length) output.configDetails.formFieldGroups = [...output.configDetails.formFieldGroups ?? [], ...embeddedFormDetails.formFieldGroups];
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
return output;
|
|
926
|
+
},
|
|
927
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeForModel$2)
|
|
928
|
+
});
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/server/tools/survey-get-raw-survey-tool.ts
|
|
931
|
+
const TOOL_ID$5 = "survey_get_raw_survey";
|
|
932
|
+
const DEFAULT_VALUE_CHARACTER_LIMIT = 12e3;
|
|
933
|
+
const MAX_VALUE_CHARACTER_LIMIT = 6e4;
|
|
934
|
+
const jsonPointerPathSchema = z.string().max(500).describe("JSON Pointer path into the survey document. Examples: \"/surveyItems/0/config/items\", \"/metadata\", \"/translations/en/itemTranslations/<itemId>/title\".");
|
|
935
|
+
const inputSchema$5 = z.object({
|
|
936
|
+
paths: z.array(jsonPointerPathSchema).min(1).max(20).optional().describe("Optional exact JSON Pointer paths to inspect. Omit paths and itemIdentifiers for a top-level raw survey overview."),
|
|
937
|
+
itemIdentifiers: z.array(z.string().min(1).max(240)).min(1).max(20).optional().describe("Optional item ids, keys, or fullKeys to inspect. Returns exact /surveyItems/<index> paths plus item translation paths for each item."),
|
|
938
|
+
valueCharacterLimit: z.number().int().min(1e3).max(MAX_VALUE_CHARACTER_LIMIT).default(DEFAULT_VALUE_CHARACTER_LIMIT).describe("Maximum serialized characters returned per requested value.")
|
|
939
|
+
});
|
|
940
|
+
const rawSurveyItemPathSchema = z.object({
|
|
941
|
+
path: z.string(),
|
|
942
|
+
id: z.string(),
|
|
943
|
+
key: z.string(),
|
|
944
|
+
itemType: z.string(),
|
|
945
|
+
parentId: z.string().optional(),
|
|
946
|
+
childCount: z.number().int().nonnegative().optional()
|
|
947
|
+
});
|
|
948
|
+
const outputSchema$4 = z.object({
|
|
949
|
+
ok: z.boolean(),
|
|
950
|
+
reason: z.string().optional(),
|
|
951
|
+
revision: z.number().int().nonnegative().optional(),
|
|
952
|
+
contentHash: z.string().optional(),
|
|
953
|
+
overview: z.object({
|
|
954
|
+
topLevelKeys: z.array(z.string()),
|
|
955
|
+
surveyItemCount: z.number().int().nonnegative(),
|
|
956
|
+
locales: z.array(z.string()),
|
|
957
|
+
itemPaths: z.array(rawSurveyItemPathSchema),
|
|
958
|
+
note: z.string().optional()
|
|
959
|
+
}).optional(),
|
|
960
|
+
values: z.array(z.object({
|
|
961
|
+
path: z.string(),
|
|
962
|
+
found: z.boolean(),
|
|
963
|
+
value: z.unknown().optional(),
|
|
964
|
+
preview: z.string().optional(),
|
|
965
|
+
truncated: z.boolean().optional(),
|
|
966
|
+
error: z.string().optional()
|
|
967
|
+
})).optional(),
|
|
968
|
+
items: z.array(z.object({
|
|
969
|
+
identifier: z.string(),
|
|
970
|
+
found: z.boolean(),
|
|
971
|
+
itemId: z.string().optional(),
|
|
972
|
+
itemPath: z.string().optional(),
|
|
973
|
+
rawItem: z.unknown().optional(),
|
|
974
|
+
rawItemPreview: z.string().optional(),
|
|
975
|
+
rawItemTruncated: z.boolean().optional(),
|
|
976
|
+
translationPaths: z.array(z.string()).optional(),
|
|
977
|
+
translationsByLocale: z.record(z.string(), z.unknown()).optional(),
|
|
978
|
+
translationsPreview: z.string().optional(),
|
|
979
|
+
translationsTruncated: z.boolean().optional(),
|
|
980
|
+
error: z.string().optional()
|
|
981
|
+
})).optional()
|
|
982
|
+
});
|
|
983
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
984
|
+
const getGroupChildren = (item) => {
|
|
985
|
+
if (!isRecord(item) || !isRecord(item.config) || !Array.isArray(item.config.items)) return [];
|
|
986
|
+
return item.config.items.filter((entry) => typeof entry === "string");
|
|
987
|
+
};
|
|
988
|
+
const buildParentByChildId = (rawSurvey) => {
|
|
989
|
+
const parentByChildId = /* @__PURE__ */ new Map();
|
|
990
|
+
const rawItems = Array.isArray(rawSurvey.surveyItems) ? rawSurvey.surveyItems : [];
|
|
991
|
+
for (const item of rawItems) for (const childId of getGroupChildren(item)) parentByChildId.set(childId, item.id);
|
|
992
|
+
return parentByChildId;
|
|
993
|
+
};
|
|
994
|
+
const buildOverview = (snapshot) => {
|
|
995
|
+
const rawSurvey = getRawSurvey(snapshot);
|
|
996
|
+
const rawItems = getRawSurveyItems(snapshot);
|
|
997
|
+
const parentByChildId = buildParentByChildId(rawSurvey);
|
|
998
|
+
return {
|
|
999
|
+
topLevelKeys: Object.keys(rawSurvey).sort(),
|
|
1000
|
+
surveyItemCount: rawItems.length,
|
|
1001
|
+
locales: snapshot.inspection.locales,
|
|
1002
|
+
itemPaths: rawItems.map((item, index) => ({
|
|
1003
|
+
path: `/surveyItems/${index}`,
|
|
1004
|
+
id: item.id,
|
|
1005
|
+
key: item.key,
|
|
1006
|
+
itemType: item.itemType,
|
|
1007
|
+
parentId: parentByChildId.get(item.id),
|
|
1008
|
+
childCount: getGroupChildren(item).length || void 0
|
|
1009
|
+
})),
|
|
1010
|
+
note: "Use paths with JSON Pointer syntax. Patch operations are applied relative to the survey document root, so do not prefix paths with \"/survey\"."
|
|
1011
|
+
};
|
|
1012
|
+
};
|
|
1013
|
+
const toOutputValue = (value, characterLimit) => {
|
|
1014
|
+
const serialized = JSON.stringify(value, null, 2) ?? "undefined";
|
|
1015
|
+
if (serialized.length <= characterLimit) return {
|
|
1016
|
+
value,
|
|
1017
|
+
truncated: false
|
|
1018
|
+
};
|
|
1019
|
+
return {
|
|
1020
|
+
preview: serialized.slice(0, characterLimit),
|
|
1021
|
+
truncated: true
|
|
1022
|
+
};
|
|
1023
|
+
};
|
|
1024
|
+
const buildValues = (snapshot, input) => {
|
|
1025
|
+
const rawSurvey = getRawSurvey(snapshot);
|
|
1026
|
+
return input.paths.map((path) => {
|
|
1027
|
+
try {
|
|
1028
|
+
return {
|
|
1029
|
+
path,
|
|
1030
|
+
found: true,
|
|
1031
|
+
...toOutputValue(getValueAtJsonPointer(rawSurvey, path), input.valueCharacterLimit)
|
|
1032
|
+
};
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
return {
|
|
1035
|
+
path,
|
|
1036
|
+
found: false,
|
|
1037
|
+
error: (error instanceof JsonPatchError ? error : void 0)?.message ?? (error instanceof Error ? error.message : "The requested JSON Pointer path was not found.")
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
};
|
|
1042
|
+
const findRawItemByIdentifier = (snapshot, identifier) => {
|
|
1043
|
+
const rawItems = getRawSurveyItems(snapshot);
|
|
1044
|
+
const directIndex = rawItems.findIndex((item) => item.id === identifier);
|
|
1045
|
+
if (directIndex >= 0) return {
|
|
1046
|
+
item: rawItems[directIndex],
|
|
1047
|
+
index: directIndex
|
|
1048
|
+
};
|
|
1049
|
+
const resolved = resolveItemSummary(identifier, mapKeyIndexById(snapshot), mapOutlineById(snapshot));
|
|
1050
|
+
if (!resolved) return;
|
|
1051
|
+
const resolvedIndex = rawItems.findIndex((item) => item.id === resolved.itemId);
|
|
1052
|
+
if (resolvedIndex < 0) return;
|
|
1053
|
+
return {
|
|
1054
|
+
item: rawItems[resolvedIndex],
|
|
1055
|
+
index: resolvedIndex
|
|
1056
|
+
};
|
|
1057
|
+
};
|
|
1058
|
+
const getTranslationsByLocaleForItem = (rawSurvey, itemId) => {
|
|
1059
|
+
const entries = {};
|
|
1060
|
+
for (const [locale, localeTranslations] of Object.entries(rawSurvey.translations ?? {})) {
|
|
1061
|
+
const itemTranslations = localeTranslations?.itemTranslations?.[itemId];
|
|
1062
|
+
if (itemTranslations) entries[locale] = itemTranslations;
|
|
1063
|
+
}
|
|
1064
|
+
return entries;
|
|
1065
|
+
};
|
|
1066
|
+
const buildItemValues = (snapshot, input) => {
|
|
1067
|
+
const rawSurvey = getRawSurvey(snapshot);
|
|
1068
|
+
return input.itemIdentifiers.map((identifier) => {
|
|
1069
|
+
const resolved = findRawItemByIdentifier(snapshot, identifier);
|
|
1070
|
+
if (!resolved) return {
|
|
1071
|
+
identifier,
|
|
1072
|
+
found: false,
|
|
1073
|
+
error: `No item matching "${identifier}" was found by item id, key, or fullKey.`
|
|
1074
|
+
};
|
|
1075
|
+
const itemId = resolved.item.id;
|
|
1076
|
+
const rawItemOutput = toOutputValue(resolved.item, input.valueCharacterLimit);
|
|
1077
|
+
const translationsOutput = toOutputValue(getTranslationsByLocaleForItem(rawSurvey, itemId), input.valueCharacterLimit);
|
|
1078
|
+
const translationsValue = "value" in translationsOutput && isRecord(translationsOutput.value) ? translationsOutput.value : void 0;
|
|
1079
|
+
return {
|
|
1080
|
+
identifier,
|
|
1081
|
+
found: true,
|
|
1082
|
+
itemId,
|
|
1083
|
+
itemPath: `/surveyItems/${resolved.index}`,
|
|
1084
|
+
rawItem: "value" in rawItemOutput ? rawItemOutput.value : void 0,
|
|
1085
|
+
rawItemPreview: "preview" in rawItemOutput ? rawItemOutput.preview : void 0,
|
|
1086
|
+
rawItemTruncated: rawItemOutput.truncated,
|
|
1087
|
+
translationPaths: snapshot.inspection.locales.map((locale) => `/translations/${encodeJsonPointerSegment(locale)}/itemTranslations/${encodeJsonPointerSegment(itemId)}`),
|
|
1088
|
+
translationsByLocale: translationsValue,
|
|
1089
|
+
translationsPreview: "preview" in translationsOutput ? translationsOutput.preview : void 0,
|
|
1090
|
+
translationsTruncated: translationsOutput.truncated
|
|
1091
|
+
};
|
|
1092
|
+
});
|
|
1093
|
+
};
|
|
1094
|
+
const summarizeForModel$1 = (output) => {
|
|
1095
|
+
if (!output.ok) return output.reason ?? "Raw survey context is unavailable.";
|
|
1096
|
+
const lines = [];
|
|
1097
|
+
if (output.overview) {
|
|
1098
|
+
lines.push(`Raw survey overview: ${output.overview.surveyItemCount} item(s), top-level keys ${output.overview.topLevelKeys.join(", ")}.`);
|
|
1099
|
+
lines.push(`Locales: ${output.overview.locales.join(", ") || "none"}.`);
|
|
1100
|
+
lines.push("Survey item JSON paths:");
|
|
1101
|
+
for (const item of output.overview.itemPaths.slice(0, 50)) lines.push(`- ${item.path}: ${item.key} (${item.itemType}, id=${item.id})${item.parentId ? ` parent=${item.parentId}` : ""}`);
|
|
1102
|
+
if (output.overview.itemPaths.length > 50) lines.push("More item paths exist; request a specific path for exact raw JSON.");
|
|
1103
|
+
}
|
|
1104
|
+
for (const item of output.items ?? []) {
|
|
1105
|
+
if (!item.found) {
|
|
1106
|
+
lines.push(`${item.identifier}: not found (${item.error ?? "unknown error"})`);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
lines.push(`${item.identifier}: itemId=${item.itemId}; raw path ${item.itemPath}.`);
|
|
1110
|
+
if (item.translationPaths?.length) lines.push(`Translation paths: ${item.translationPaths.join(", ")}.`);
|
|
1111
|
+
if (item.rawItemTruncated) lines.push(`Raw item truncated preview:\n${item.rawItemPreview ?? ""}`);
|
|
1112
|
+
else lines.push(`Raw item: ${JSON.stringify(item.rawItem)}`);
|
|
1113
|
+
if (item.translationsTruncated) lines.push(`Translations truncated preview:\n${item.translationsPreview ?? ""}`);
|
|
1114
|
+
else lines.push(`Translations by locale: ${JSON.stringify(item.translationsByLocale ?? {})}`);
|
|
1115
|
+
}
|
|
1116
|
+
for (const entry of output.values ?? []) {
|
|
1117
|
+
if (!entry.found) {
|
|
1118
|
+
lines.push(`${entry.path}: not found (${entry.error ?? "unknown error"})`);
|
|
1119
|
+
continue;
|
|
1120
|
+
}
|
|
1121
|
+
if (entry.truncated) lines.push(`${entry.path}: truncated JSON preview:\n${entry.preview ?? ""}`);
|
|
1122
|
+
else lines.push(`${entry.path}: ${JSON.stringify(entry.value)}`);
|
|
1123
|
+
}
|
|
1124
|
+
return lines.join("\n");
|
|
1125
|
+
};
|
|
1126
|
+
const surveyGetRawSurveyTool = createTool({
|
|
1127
|
+
id: TOOL_ID$5,
|
|
1128
|
+
description: "Inspect exact raw survey JSON by item id/key/fullKey or JSON Pointer path. Use this before survey-json-patch edits to inspect item config, survey-level metadata, maxItemsPerPage, templateValues, translations/locales, or group ordering arrays.",
|
|
1129
|
+
inputSchema: inputSchema$5,
|
|
1130
|
+
outputSchema: outputSchema$4,
|
|
1131
|
+
mcp: { annotations: {
|
|
1132
|
+
title: "Get raw survey JSON",
|
|
1133
|
+
readOnlyHint: true,
|
|
1134
|
+
destructiveHint: false,
|
|
1135
|
+
idempotentHint: true,
|
|
1136
|
+
openWorldHint: false
|
|
1137
|
+
} },
|
|
1138
|
+
execute: async (inputData, context) => {
|
|
1139
|
+
const input = {
|
|
1140
|
+
...inputData,
|
|
1141
|
+
valueCharacterLimit: inputData.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT
|
|
1142
|
+
};
|
|
1143
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
1144
|
+
if (!snapshot) return {
|
|
1145
|
+
ok: false,
|
|
1146
|
+
reason: "No live editor snapshot was provided with this assistant turn."
|
|
1147
|
+
};
|
|
1148
|
+
return {
|
|
1149
|
+
ok: true,
|
|
1150
|
+
revision: snapshot.version.revision,
|
|
1151
|
+
contentHash: snapshot.version.contentHash,
|
|
1152
|
+
overview: input.paths || input.itemIdentifiers ? void 0 : buildOverview(snapshot),
|
|
1153
|
+
items: input.itemIdentifiers ? buildItemValues(snapshot, {
|
|
1154
|
+
itemIdentifiers: input.itemIdentifiers,
|
|
1155
|
+
valueCharacterLimit: input.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT
|
|
1156
|
+
}) : void 0,
|
|
1157
|
+
values: input.paths ? buildValues(snapshot, {
|
|
1158
|
+
paths: input.paths,
|
|
1159
|
+
valueCharacterLimit: input.valueCharacterLimit ?? DEFAULT_VALUE_CHARACTER_LIMIT
|
|
1160
|
+
}) : void 0
|
|
1161
|
+
};
|
|
1162
|
+
},
|
|
1163
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeForModel$1)
|
|
1164
|
+
});
|
|
1165
|
+
//#endregion
|
|
1166
|
+
//#region src/server/tools/survey-search-items-tool.ts
|
|
1167
|
+
const TOOL_ID$4 = "survey_search_items";
|
|
1168
|
+
const MAX_QUERY_LENGTH = 180;
|
|
1169
|
+
const MAX_MATCHES_PER_ITEM = 6;
|
|
1170
|
+
const DEFAULT_TEXT_LIMIT = 220;
|
|
1171
|
+
const searchMatchSchema = z.object({
|
|
1172
|
+
source: z.enum([
|
|
1173
|
+
"structure",
|
|
1174
|
+
"translation",
|
|
1175
|
+
"config"
|
|
1176
|
+
]),
|
|
1177
|
+
field: z.string().optional(),
|
|
1178
|
+
locale: z.string().optional(),
|
|
1179
|
+
contentKey: z.string().optional(),
|
|
1180
|
+
text: z.string(),
|
|
1181
|
+
score: z.number()
|
|
1182
|
+
});
|
|
1183
|
+
const searchResultSchema = z.object({
|
|
1184
|
+
item: itemSummarySchema,
|
|
1185
|
+
score: z.number(),
|
|
1186
|
+
matches: z.array(searchMatchSchema)
|
|
1187
|
+
});
|
|
1188
|
+
const inputSchema$4 = z.object({
|
|
1189
|
+
query: z.string().min(1).max(MAX_QUERY_LENGTH).describe("Text to search for across all survey items, including visible translated content such as titles, option labels, and form field labels. Examples: \"age\", \"consent\", \"blood pressure\"."),
|
|
1190
|
+
itemTypes: z.array(z.string()).optional().describe("Optional item types to restrict results to, such as choiceItem or formItem."),
|
|
1191
|
+
locales: z.array(z.string()).optional().describe("Optional locale codes to restrict translation-content matches to."),
|
|
1192
|
+
cursor: z.string().optional().describe("Optional numeric cursor returned by a previous search."),
|
|
1193
|
+
limit: z.number().int().min(1).max(50).default(12).describe("Maximum number of matching items to return.")
|
|
1194
|
+
});
|
|
1195
|
+
const outputSchema$3 = z.object({
|
|
1196
|
+
ok: z.boolean(),
|
|
1197
|
+
reason: z.string().optional(),
|
|
1198
|
+
query: z.string().optional(),
|
|
1199
|
+
totalAvailable: z.number().int().nonnegative().optional(),
|
|
1200
|
+
returned: z.number().int().nonnegative().optional(),
|
|
1201
|
+
nextCursor: z.string().optional(),
|
|
1202
|
+
truncated: z.boolean().optional(),
|
|
1203
|
+
results: z.array(searchResultSchema).optional()
|
|
1204
|
+
});
|
|
1205
|
+
const STOP_WORDS = new Set([
|
|
1206
|
+
"a",
|
|
1207
|
+
"about",
|
|
1208
|
+
"an",
|
|
1209
|
+
"and",
|
|
1210
|
+
"called",
|
|
1211
|
+
"choice",
|
|
1212
|
+
"field",
|
|
1213
|
+
"form",
|
|
1214
|
+
"for",
|
|
1215
|
+
"in",
|
|
1216
|
+
"item",
|
|
1217
|
+
"label",
|
|
1218
|
+
"named",
|
|
1219
|
+
"of",
|
|
1220
|
+
"option",
|
|
1221
|
+
"question",
|
|
1222
|
+
"survey",
|
|
1223
|
+
"the",
|
|
1224
|
+
"this",
|
|
1225
|
+
"title",
|
|
1226
|
+
"titled",
|
|
1227
|
+
"with"
|
|
1228
|
+
]);
|
|
1229
|
+
const normalizeSearchText = (value) => value.trim().toLowerCase().replace(/\s+/g, " ");
|
|
1230
|
+
const queryTerms = (query) => {
|
|
1231
|
+
const terms = normalizeSearchText(query).split(/[\s.,;:!?()[\]{}"'`/\\]+/).map((term) => term.trim()).filter((term) => term.length > 1 && !STOP_WORDS.has(term));
|
|
1232
|
+
if (terms.length > 0) return terms;
|
|
1233
|
+
return normalizeSearchText(query).split(/[\s.,;:!?()[\]{}"'`/\\]+/).map((term) => term.trim()).filter((term) => term.length > 1);
|
|
1234
|
+
};
|
|
1235
|
+
const scoreText = (value, query, terms, baseScore) => {
|
|
1236
|
+
const normalizedValue = normalizeSearchText(value);
|
|
1237
|
+
const normalizedQuery = normalizeSearchText(query);
|
|
1238
|
+
if (!normalizedValue || !normalizedQuery) return null;
|
|
1239
|
+
if (normalizedValue === normalizedQuery) return baseScore + 80;
|
|
1240
|
+
if (normalizedValue.includes(normalizedQuery)) return baseScore + 50;
|
|
1241
|
+
const hitCount = terms.filter((term) => normalizedValue.includes(term)).length;
|
|
1242
|
+
if (terms.length > 0 && hitCount === terms.length) return baseScore + hitCount * 12;
|
|
1243
|
+
return null;
|
|
1244
|
+
};
|
|
1245
|
+
const addMatch = (matches, match) => {
|
|
1246
|
+
const text = match.text?.trim();
|
|
1247
|
+
if (!text) return;
|
|
1248
|
+
if (!matches.some((existing) => existing.source === match.source && existing.field === match.field && existing.locale === match.locale && existing.contentKey === match.contentKey && existing.text === text)) matches.push({
|
|
1249
|
+
...match,
|
|
1250
|
+
text
|
|
1251
|
+
});
|
|
1252
|
+
};
|
|
1253
|
+
const candidateItems = (snapshot) => {
|
|
1254
|
+
const outlineById = mapOutlineById(snapshot);
|
|
1255
|
+
const rawItemsById = mapRawItemsById(snapshot);
|
|
1256
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1257
|
+
const candidates = [];
|
|
1258
|
+
for (const entry of summarizeKeyIndexEntries(snapshot.inspection.keyIndex, outlineById)) {
|
|
1259
|
+
seen.add(entry.itemId);
|
|
1260
|
+
candidates.push({
|
|
1261
|
+
item: entry,
|
|
1262
|
+
rawItem: rawItemsById.get(entry.itemId)
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
for (const rawItem of rawItemsById.values()) {
|
|
1266
|
+
if (seen.has(rawItem.id)) continue;
|
|
1267
|
+
candidates.push({
|
|
1268
|
+
item: summarizeRawItem(rawItem),
|
|
1269
|
+
rawItem
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
return candidates;
|
|
1273
|
+
};
|
|
1274
|
+
const searchItems = (snapshot, input) => {
|
|
1275
|
+
const terms = queryTerms(input.query);
|
|
1276
|
+
const itemTypeFilter = input.itemTypes?.length ? new Set(input.itemTypes) : void 0;
|
|
1277
|
+
return candidateItems(snapshot).filter(({ item }) => !itemTypeFilter || itemTypeFilter.has(item.itemType)).map(({ item, rawItem }) => {
|
|
1278
|
+
const matches = [];
|
|
1279
|
+
const structuralFields = [
|
|
1280
|
+
["itemId", item.itemId],
|
|
1281
|
+
["itemType", item.itemType],
|
|
1282
|
+
["key", item.key],
|
|
1283
|
+
["fullKey", item.fullKey],
|
|
1284
|
+
["itemLabel", item.itemLabel],
|
|
1285
|
+
["path", item.path?.join(" ")]
|
|
1286
|
+
];
|
|
1287
|
+
for (const [field, text] of structuralFields) {
|
|
1288
|
+
if (!text) continue;
|
|
1289
|
+
const score = scoreText(text, input.query, terms, 50);
|
|
1290
|
+
if (score !== null) addMatch(matches, {
|
|
1291
|
+
source: "structure",
|
|
1292
|
+
field,
|
|
1293
|
+
text,
|
|
1294
|
+
score
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
for (const translation of buildItemTranslationEntries(snapshot, item.itemId, {
|
|
1298
|
+
locales: input.locales,
|
|
1299
|
+
textLimit: DEFAULT_TEXT_LIMIT
|
|
1300
|
+
})) {
|
|
1301
|
+
const score = scoreText(`${translation.contentKey} ${translation.text}`, input.query, terms, 100);
|
|
1302
|
+
if (score !== null) addMatch(matches, {
|
|
1303
|
+
source: "translation",
|
|
1304
|
+
locale: translation.locale,
|
|
1305
|
+
contentKey: translation.contentKey,
|
|
1306
|
+
text: translation.text,
|
|
1307
|
+
score
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
if (rawItem) for (const text of buildConfigSearchText(rawItem)) {
|
|
1311
|
+
const score = scoreText(text, input.query, terms, 60);
|
|
1312
|
+
if (score !== null) addMatch(matches, {
|
|
1313
|
+
source: "config",
|
|
1314
|
+
text,
|
|
1315
|
+
score
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
if (matches.length === 0) return;
|
|
1319
|
+
matches.sort((a, b) => b.score - a.score);
|
|
1320
|
+
return {
|
|
1321
|
+
item,
|
|
1322
|
+
matches: matches.slice(0, MAX_MATCHES_PER_ITEM),
|
|
1323
|
+
score: matches.reduce((sum, match) => sum + match.score, 0)
|
|
1324
|
+
};
|
|
1325
|
+
}).filter((result) => Boolean(result)).sort((a, b) => b.score - a.score || a.item.fullKey.localeCompare(b.item.fullKey));
|
|
1326
|
+
};
|
|
1327
|
+
const summarizeForModel = (output) => {
|
|
1328
|
+
if (!output.ok) return output.reason ?? "Survey item search is unavailable.";
|
|
1329
|
+
const lines = [`Search "${output.query ?? ""}": ${output.returned ?? 0}/${output.totalAvailable ?? 0} matching item(s) returned.`];
|
|
1330
|
+
for (const result of output.results ?? []) {
|
|
1331
|
+
lines.push(`- ${result.item.fullKey} (${result.item.itemType}, itemId=${result.item.itemId}, score=${result.score})`);
|
|
1332
|
+
for (const match of result.matches) {
|
|
1333
|
+
const source = match.source === "translation" ? `${match.locale}.${match.contentKey}` : match.field ?? match.source;
|
|
1334
|
+
lines.push(` match ${match.source}:${source}: ${match.text}`);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
if (output.nextCursor) lines.push(`More search results are available with cursor ${output.nextCursor}.`);
|
|
1338
|
+
lines.push("Use survey_inspect with action \"item-details\" and itemRef to inspect a result.");
|
|
1339
|
+
return lines.join("\n");
|
|
1340
|
+
};
|
|
1341
|
+
const surveySearchItemsTool = createTool({
|
|
1342
|
+
id: TOOL_ID$4,
|
|
1343
|
+
description: "Search all survey items by visible translated text, item keys, labels, and config identifiers. Use this when the user refers to an unselected item by title, label, option text, field label, or another phrase rather than an item id.",
|
|
1344
|
+
inputSchema: inputSchema$4,
|
|
1345
|
+
outputSchema: outputSchema$3,
|
|
1346
|
+
mcp: { annotations: {
|
|
1347
|
+
title: "Search survey items",
|
|
1348
|
+
readOnlyHint: true,
|
|
1349
|
+
destructiveHint: false,
|
|
1350
|
+
idempotentHint: true,
|
|
1351
|
+
openWorldHint: false
|
|
1352
|
+
} },
|
|
1353
|
+
execute: async (inputData, context) => {
|
|
1354
|
+
const input = {
|
|
1355
|
+
...inputData,
|
|
1356
|
+
limit: inputData.limit ?? 12
|
|
1357
|
+
};
|
|
1358
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
1359
|
+
if (!snapshot) return {
|
|
1360
|
+
ok: false,
|
|
1361
|
+
reason: "No live editor snapshot was provided with this assistant turn.",
|
|
1362
|
+
query: input.query
|
|
1363
|
+
};
|
|
1364
|
+
const results = searchItems(snapshot, input);
|
|
1365
|
+
const page = sliceWithCursor(results, input);
|
|
1366
|
+
return {
|
|
1367
|
+
ok: true,
|
|
1368
|
+
query: input.query,
|
|
1369
|
+
totalAvailable: results.length,
|
|
1370
|
+
returned: page.items.length,
|
|
1371
|
+
nextCursor: page.nextCursor,
|
|
1372
|
+
truncated: page.truncated,
|
|
1373
|
+
results: page.items
|
|
1374
|
+
};
|
|
1375
|
+
},
|
|
1376
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeForModel)
|
|
1377
|
+
});
|
|
1378
|
+
//#endregion
|
|
1379
|
+
//#region src/server/tools/survey-inspect-tool.ts
|
|
1380
|
+
const TOOL_ID$3 = "survey_inspect";
|
|
1381
|
+
const inspectActionSchema = z.enum([
|
|
1382
|
+
"current-context",
|
|
1383
|
+
"search-items",
|
|
1384
|
+
"item-details",
|
|
1385
|
+
"assets",
|
|
1386
|
+
"raw-json"
|
|
1387
|
+
]);
|
|
1388
|
+
const outlineModeSchema = z.enum([
|
|
1389
|
+
"full",
|
|
1390
|
+
"focused",
|
|
1391
|
+
"children"
|
|
1392
|
+
]);
|
|
1393
|
+
const optionalInput = (schema) => z.preprocess((value) => value === null ? void 0 : value, schema.optional());
|
|
1394
|
+
const optionalNonBlankString = (maxLength) => z.preprocess((value) => value === null || typeof value === "string" && value.trim().length === 0 ? void 0 : value, z.string().min(1).max(maxLength).optional());
|
|
1395
|
+
const inputSchema$3 = z.object({
|
|
1396
|
+
action: inspectActionSchema.describe("The survey information to inspect."),
|
|
1397
|
+
reason: optionalInput(z.string().max(500)).describe("Short reason this inspection is needed."),
|
|
1398
|
+
scopes: optionalInput(z.array(z.enum([
|
|
1399
|
+
"summary",
|
|
1400
|
+
"selected-item",
|
|
1401
|
+
"outline",
|
|
1402
|
+
"response-slots",
|
|
1403
|
+
"ui-context",
|
|
1404
|
+
"history"
|
|
1405
|
+
])).min(1).max(6)).describe("For current-context: context sections to inspect."),
|
|
1406
|
+
query: optionalNonBlankString(180).describe("For search-items: text to search across survey content. For assets: optional asset id, filename, name, ALT text, or media type filter. For current-context outline: optional key/fullKey/label filter."),
|
|
1407
|
+
itemRef: optionalNonBlankString(240).describe("For current-context outline, item-details, or raw-json: item id, key, fullKey, visible label, or \"selected\"."),
|
|
1408
|
+
cursor: optionalNonBlankString(240).describe("For current-context/search-items pagination: numeric cursor from a previous result."),
|
|
1409
|
+
outlineMode: optionalInput(outlineModeSchema).describe("For current-context outline: \"full\" pages all survey items, \"focused\" returns the selected/focused neighborhood, and \"children\" returns direct children of itemRef."),
|
|
1410
|
+
paths: optionalInput(z.array(z.string().min(1).max(500)).min(1).max(20)).describe("For raw-json: exact JSON Pointer paths to inspect."),
|
|
1411
|
+
includeChildren: optionalInput(z.boolean()).describe("For item-details: include direct survey-tree children."),
|
|
1412
|
+
includeItemConfig: optionalInput(z.boolean()).describe("For item-details: include choice/form/internal item config details."),
|
|
1413
|
+
limit: optionalInput(z.number().int().min(1).max(50)).describe("Maximum list rows to return.")
|
|
1414
|
+
});
|
|
1415
|
+
const outputSchema$2 = z.object({
|
|
1416
|
+
ok: z.boolean(),
|
|
1417
|
+
action: inspectActionSchema,
|
|
1418
|
+
reason: z.string().optional(),
|
|
1419
|
+
modelSummary: z.string(),
|
|
1420
|
+
result: z.unknown().optional()
|
|
1421
|
+
});
|
|
1422
|
+
const runTool = async (tool, input, context) => {
|
|
1423
|
+
const execute = tool.execute;
|
|
1424
|
+
if (!execute) throw new Error("Survey inspection backend is not executable.");
|
|
1425
|
+
return execute(input, context);
|
|
1426
|
+
};
|
|
1427
|
+
const unwrapToolOutput = (value) => {
|
|
1428
|
+
if (value && typeof value === "object" && "output" in value && value.output !== void 0) return value.output;
|
|
1429
|
+
return value;
|
|
1430
|
+
};
|
|
1431
|
+
const stringifyForModel = (value) => {
|
|
1432
|
+
if (typeof value === "string") return value;
|
|
1433
|
+
return JSON.stringify(value, null, 2);
|
|
1434
|
+
};
|
|
1435
|
+
const resolveItemRef = (input, snapshot) => {
|
|
1436
|
+
if (input.itemRef && input.itemRef !== "selected") return input.itemRef;
|
|
1437
|
+
return snapshot?.ui.selectedItemId;
|
|
1438
|
+
};
|
|
1439
|
+
const listAssetUsageSummaries = (survey) => {
|
|
1440
|
+
const usagesByAssetId = /* @__PURE__ */ new Map();
|
|
1441
|
+
const addContent = (content, usage) => {
|
|
1442
|
+
for (const assetUsage of getAssetUsagesFromContent(content)) {
|
|
1443
|
+
const usages = usagesByAssetId.get(assetUsage.assetId) ?? [];
|
|
1444
|
+
usages.push({
|
|
1445
|
+
...usage,
|
|
1446
|
+
blockIndex: assetUsage.blockIndex
|
|
1447
|
+
});
|
|
1448
|
+
usagesByAssetId.set(assetUsage.assetId, usages);
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
for (const [locale, localeTranslations] of Object.entries(survey.translations ?? {})) {
|
|
1452
|
+
for (const scope of [
|
|
1453
|
+
"surveyCardContent",
|
|
1454
|
+
"navigationContent",
|
|
1455
|
+
"validationMessages"
|
|
1456
|
+
]) for (const [contentKey, content] of Object.entries(localeTranslations[scope] ?? {})) addContent(content, {
|
|
1457
|
+
locale,
|
|
1458
|
+
scope,
|
|
1459
|
+
contentKey
|
|
1460
|
+
});
|
|
1461
|
+
for (const [itemId, itemTranslations] of Object.entries(localeTranslations.itemTranslations ?? {})) for (const [contentKey, content] of Object.entries(itemTranslations ?? {})) addContent(content, {
|
|
1462
|
+
locale,
|
|
1463
|
+
scope: "itemTranslation",
|
|
1464
|
+
itemId,
|
|
1465
|
+
contentKey
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
return usagesByAssetId;
|
|
1469
|
+
};
|
|
1470
|
+
const summarizeAssetSource = (asset) => ({
|
|
1471
|
+
type: asset.source.type,
|
|
1472
|
+
mediaType: asset.source.mediaType
|
|
1473
|
+
});
|
|
1474
|
+
const listAssets = (input, snapshot) => {
|
|
1475
|
+
const survey = snapshot.survey;
|
|
1476
|
+
const usagesByAssetId = listAssetUsageSummaries(survey);
|
|
1477
|
+
const query = input.query?.trim().toLowerCase();
|
|
1478
|
+
const allAssets = Object.entries(survey.assets ?? {}).map(([assetId, asset]) => {
|
|
1479
|
+
const usages = usagesByAssetId.get(assetId) ?? [];
|
|
1480
|
+
return {
|
|
1481
|
+
assetId,
|
|
1482
|
+
kind: asset.kind,
|
|
1483
|
+
source: summarizeAssetSource(asset),
|
|
1484
|
+
...asset.metadata ? { metadata: asset.metadata } : {},
|
|
1485
|
+
usageCount: usages.length,
|
|
1486
|
+
usages
|
|
1487
|
+
};
|
|
1488
|
+
}).filter((asset) => {
|
|
1489
|
+
if (!query) return true;
|
|
1490
|
+
return [
|
|
1491
|
+
asset.assetId,
|
|
1492
|
+
asset.source.mediaType,
|
|
1493
|
+
asset.metadata?.name,
|
|
1494
|
+
asset.metadata?.filename,
|
|
1495
|
+
asset.metadata?.alt
|
|
1496
|
+
].some((value) => value?.toLowerCase().includes(query));
|
|
1497
|
+
}).sort((left, right) => left.assetId.localeCompare(right.assetId));
|
|
1498
|
+
const parsedCursor = Number.parseInt(input.cursor ?? "0", 10);
|
|
1499
|
+
const offset = Number.isFinite(parsedCursor) && parsedCursor >= 0 ? parsedCursor : 0;
|
|
1500
|
+
const limit = input.limit ?? 20;
|
|
1501
|
+
const assets = allAssets.slice(offset, offset + limit);
|
|
1502
|
+
const nextOffset = offset + assets.length;
|
|
1503
|
+
return {
|
|
1504
|
+
totalAvailable: allAssets.length,
|
|
1505
|
+
returned: assets.length,
|
|
1506
|
+
...nextOffset < allAssets.length ? { nextCursor: String(nextOffset) } : {},
|
|
1507
|
+
assets
|
|
1508
|
+
};
|
|
1509
|
+
};
|
|
1510
|
+
const surveyInspectTool = createTool({
|
|
1511
|
+
id: TOOL_ID$3,
|
|
1512
|
+
description: "Inspect current survey state through one compact interface: current context, item search, item details, image assets with explicit asset IDs and usages, or focused raw JSON. Use this before making changes when the answer depends on the live editor state.",
|
|
1513
|
+
inputSchema: inputSchema$3,
|
|
1514
|
+
outputSchema: outputSchema$2,
|
|
1515
|
+
mcp: { annotations: {
|
|
1516
|
+
title: "Inspect survey",
|
|
1517
|
+
readOnlyHint: true,
|
|
1518
|
+
destructiveHint: false,
|
|
1519
|
+
idempotentHint: true,
|
|
1520
|
+
openWorldHint: false
|
|
1521
|
+
} },
|
|
1522
|
+
execute: async (inputData, context) => {
|
|
1523
|
+
const input = inputData;
|
|
1524
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
1525
|
+
if (!snapshot) return {
|
|
1526
|
+
ok: false,
|
|
1527
|
+
action: input.action,
|
|
1528
|
+
reason: "No live editor snapshot was provided with this assistant turn.",
|
|
1529
|
+
modelSummary: "No live editor snapshot is available for this turn."
|
|
1530
|
+
};
|
|
1531
|
+
if (input.action === "current-context") {
|
|
1532
|
+
const result = unwrapToolOutput(await runTool(surveyGetCurrentContextTool, {
|
|
1533
|
+
scopes: input.scopes ?? ["summary", "selected-item"],
|
|
1534
|
+
limit: input.limit,
|
|
1535
|
+
cursor: input.cursor,
|
|
1536
|
+
itemId: resolveItemRef(input, snapshot),
|
|
1537
|
+
query: input.query,
|
|
1538
|
+
outlineMode: input.outlineMode
|
|
1539
|
+
}, context));
|
|
1540
|
+
return {
|
|
1541
|
+
ok: true,
|
|
1542
|
+
action: input.action,
|
|
1543
|
+
modelSummary: stringifyForModel(result),
|
|
1544
|
+
result
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
if (input.action === "search-items") {
|
|
1548
|
+
if (!input.query) return {
|
|
1549
|
+
ok: false,
|
|
1550
|
+
action: input.action,
|
|
1551
|
+
reason: "Search requires a query.",
|
|
1552
|
+
modelSummary: "Search requires a query."
|
|
1553
|
+
};
|
|
1554
|
+
const result = unwrapToolOutput(await runTool(surveySearchItemsTool, {
|
|
1555
|
+
query: input.query,
|
|
1556
|
+
limit: input.limit,
|
|
1557
|
+
cursor: input.cursor
|
|
1558
|
+
}, context));
|
|
1559
|
+
return {
|
|
1560
|
+
ok: true,
|
|
1561
|
+
action: input.action,
|
|
1562
|
+
modelSummary: stringifyForModel(result),
|
|
1563
|
+
result
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
if (input.action === "item-details") {
|
|
1567
|
+
const itemId = resolveItemRef(input, snapshot);
|
|
1568
|
+
if (!itemId) return {
|
|
1569
|
+
ok: false,
|
|
1570
|
+
action: input.action,
|
|
1571
|
+
reason: "No item reference was provided and no item is selected.",
|
|
1572
|
+
modelSummary: "No item reference was provided and no item is selected."
|
|
1573
|
+
};
|
|
1574
|
+
const result = unwrapToolOutput(await runTool(surveyGetItemDetailsTool, {
|
|
1575
|
+
itemId,
|
|
1576
|
+
includeSurveyChildren: input.includeChildren ?? false,
|
|
1577
|
+
includeItemConfig: input.includeItemConfig ?? true,
|
|
1578
|
+
childrenLimit: input.limit
|
|
1579
|
+
}, context));
|
|
1580
|
+
return {
|
|
1581
|
+
ok: true,
|
|
1582
|
+
action: input.action,
|
|
1583
|
+
modelSummary: stringifyForModel(result),
|
|
1584
|
+
result
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
if (input.action === "assets") {
|
|
1588
|
+
const result = listAssets(input, snapshot);
|
|
1589
|
+
return {
|
|
1590
|
+
ok: true,
|
|
1591
|
+
action: input.action,
|
|
1592
|
+
modelSummary: stringifyForModel(result),
|
|
1593
|
+
result
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
const itemId = resolveItemRef(input, snapshot);
|
|
1597
|
+
const itemIdentifiers = itemId ? [itemId] : void 0;
|
|
1598
|
+
const result = unwrapToolOutput(await runTool(surveyGetRawSurveyTool, {
|
|
1599
|
+
paths: input.paths,
|
|
1600
|
+
itemIdentifiers
|
|
1601
|
+
}, context));
|
|
1602
|
+
return {
|
|
1603
|
+
ok: true,
|
|
1604
|
+
action: input.action,
|
|
1605
|
+
modelSummary: stringifyForModel(result),
|
|
1606
|
+
result
|
|
1607
|
+
};
|
|
1608
|
+
},
|
|
1609
|
+
toModelOutput: (value) => toTextModelOutput(value, (output) => output.modelSummary)
|
|
1610
|
+
});
|
|
1611
|
+
//#endregion
|
|
1612
|
+
//#region src/server/tools/survey-attachment-tool.ts
|
|
1613
|
+
const TOOL_ID$2 = "survey_attachment";
|
|
1614
|
+
const surveyAttachmentTool = createTool({
|
|
1615
|
+
id: TOOL_ID$2,
|
|
1616
|
+
description: "Attach only the stored PDFs or images needed for the current task to the next native model request. After this succeeds, read the original files directly and continue the task.",
|
|
1617
|
+
inputSchema: z.object({ documentIds: z.array(z.string().min(1)).min(1).max(4).describe("IDs of only the stored attachments needed for the current request.") }),
|
|
1618
|
+
outputSchema: z.object({ loaded: z.array(z.object({
|
|
1619
|
+
id: z.string(),
|
|
1620
|
+
filename: z.string(),
|
|
1621
|
+
mediaType: z.string()
|
|
1622
|
+
})) }),
|
|
1623
|
+
mcp: { annotations: {
|
|
1624
|
+
title: "Load chat attachment",
|
|
1625
|
+
readOnlyHint: true,
|
|
1626
|
+
destructiveHint: false,
|
|
1627
|
+
idempotentHint: true,
|
|
1628
|
+
openWorldHint: false
|
|
1629
|
+
} },
|
|
1630
|
+
execute: async (inputData, context) => {
|
|
1631
|
+
const access = (context?.requestContext)?.get("attachmentAccess");
|
|
1632
|
+
if (!access) return { loaded: [] };
|
|
1633
|
+
const requestedIds = [...new Set(inputData.documentIds)];
|
|
1634
|
+
const authorized = access.documents.filter((document) => requestedIds.includes(document.id));
|
|
1635
|
+
const attachments = await access.load(authorized.map((document) => document.id));
|
|
1636
|
+
access.selectedAttachments.splice(0, access.selectedAttachments.length, ...attachments);
|
|
1637
|
+
return { loaded: authorized.map((document) => ({
|
|
1638
|
+
id: document.id,
|
|
1639
|
+
filename: document.name,
|
|
1640
|
+
mediaType: document.mediaType
|
|
1641
|
+
})) };
|
|
1642
|
+
},
|
|
1643
|
+
toModelOutput: (value) => toTextModelOutput(value, () => "The selected original attachments are included in this model input. Read them directly now and continue the user's task. Do not claim that their content is unavailable or ask the user to paste extracted text.")
|
|
1644
|
+
});
|
|
1645
|
+
//#endregion
|
|
1646
|
+
//#region src/server/tools/survey-audit-tool.ts
|
|
1647
|
+
const TOOL_ID$1 = "survey_audit";
|
|
1648
|
+
const surveyAuditTool = createTool({
|
|
1649
|
+
id: TOOL_ID$1,
|
|
1650
|
+
description: "Audit the current survey for deterministic structural, content, localization, response, and asset issues, and return a research-informed questionnaire-quality review rubric for qualitative critique. This is read-only and is not psychometric validation.",
|
|
1651
|
+
inputSchema: z.object({
|
|
1652
|
+
sourceLocale: z.string().min(1).optional().describe("Locale treated as the source when checking translation completeness."),
|
|
1653
|
+
targetLocales: z.array(z.string().min(1)).max(20).optional(),
|
|
1654
|
+
maxFindings: z.number().int().min(1).max(300).default(120).optional(),
|
|
1655
|
+
reason: z.string().max(500).optional()
|
|
1656
|
+
}),
|
|
1657
|
+
outputSchema: z.object({
|
|
1658
|
+
ok: z.boolean(),
|
|
1659
|
+
reason: z.string().optional(),
|
|
1660
|
+
report: z.unknown().optional()
|
|
1661
|
+
}),
|
|
1662
|
+
mcp: { annotations: {
|
|
1663
|
+
title: "Audit survey",
|
|
1664
|
+
readOnlyHint: true,
|
|
1665
|
+
destructiveHint: false,
|
|
1666
|
+
idempotentHint: true,
|
|
1667
|
+
openWorldHint: false
|
|
1668
|
+
} },
|
|
1669
|
+
execute: async (input, context) => {
|
|
1670
|
+
const snapshot = context?.requestContext?.get("engineContext");
|
|
1671
|
+
if (!snapshot) return {
|
|
1672
|
+
ok: false,
|
|
1673
|
+
reason: "No live editor snapshot is available for this turn."
|
|
1674
|
+
};
|
|
1675
|
+
return {
|
|
1676
|
+
ok: true,
|
|
1677
|
+
report: auditSurvey(snapshot, input)
|
|
1678
|
+
};
|
|
1679
|
+
},
|
|
1680
|
+
toModelOutput: (value) => toTextModelOutput(value, (output) => JSON.stringify(output, null, 2))
|
|
1681
|
+
});
|
|
1682
|
+
//#endregion
|
|
1683
|
+
//#region src/server/tools/survey-asset-tool.ts
|
|
1684
|
+
const TOOL_ID = "survey_asset";
|
|
1685
|
+
const inputSchema = z.object({
|
|
1686
|
+
action: z.enum([
|
|
1687
|
+
"import-attachment",
|
|
1688
|
+
"update-metadata",
|
|
1689
|
+
"remove"
|
|
1690
|
+
]),
|
|
1691
|
+
documentId: z.string().min(1).optional().describe("Stored attachment id for import-attachment."),
|
|
1692
|
+
assetId: z.string().min(1).max(240).optional(),
|
|
1693
|
+
name: z.string().max(500).nullable().optional(),
|
|
1694
|
+
filename: z.string().max(500).nullable().optional(),
|
|
1695
|
+
alt: z.string().max(2e3).nullable().optional(),
|
|
1696
|
+
continuationMode: z.enum(SURVEY_CHANGE_CONTINUATION_MODES).optional().describe("Required after any earlier mutation candidate in the turn. Use \"append\" to keep earlier candidates, including an imported asset; use \"replace\" only when resubmitting the complete intended proposal."),
|
|
1697
|
+
summary: z.string().min(1).max(500)
|
|
1698
|
+
});
|
|
1699
|
+
const slug = (value) => value.toLowerCase().replace(/\.[^.]+$/, "").replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 100) || "image";
|
|
1700
|
+
const OMITTED_EMBEDDED_IMAGE_DATA = "[embedded image data omitted from transcript]";
|
|
1701
|
+
const getAssetReferenceLabels = (snapshot, assetId) => {
|
|
1702
|
+
const translations = (snapshot?.survey)?.translations;
|
|
1703
|
+
if (!translations) return [];
|
|
1704
|
+
const references = [];
|
|
1705
|
+
const inspectContent = (content, label) => {
|
|
1706
|
+
if (getAssetUsagesFromContent(content).some((usage) => usage.assetId === assetId)) references.push(label);
|
|
1707
|
+
};
|
|
1708
|
+
for (const [locale, localeTranslations] of Object.entries(translations)) {
|
|
1709
|
+
for (const surface of [
|
|
1710
|
+
"surveyCardContent",
|
|
1711
|
+
"navigationContent",
|
|
1712
|
+
"validationMessages"
|
|
1713
|
+
]) for (const [contentKey, content] of Object.entries(localeTranslations[surface] ?? {})) inspectContent(content, `${locale}:${surface}:${contentKey}`);
|
|
1714
|
+
for (const [itemId, itemTranslations] of Object.entries(localeTranslations.itemTranslations ?? {})) for (const [contentKey, content] of Object.entries(itemTranslations ?? {})) inspectContent(content, `${locale}:item:${itemId}:${contentKey}`);
|
|
1715
|
+
}
|
|
1716
|
+
return references;
|
|
1717
|
+
};
|
|
1718
|
+
const getToolOutput = (value) => value && typeof value === "object" && "output" in value && value.output !== void 0 ? value.output : value;
|
|
1719
|
+
const describeAssetOperation = (operation) => {
|
|
1720
|
+
switch (operation.kind) {
|
|
1721
|
+
case "set-image-asset":
|
|
1722
|
+
case "update-image-asset-metadata":
|
|
1723
|
+
case "remove-image-asset": return `${operation.kind} ${operation.assetId}`;
|
|
1724
|
+
default: return operation.kind;
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
const summarizeAssetChange = (event) => {
|
|
1728
|
+
const lines = [`${event.status === "validated" ? "Validated" : "Rejected"} survey asset change: ${event.summary}`, `Change id: ${event.id}`];
|
|
1729
|
+
if (event.operations.length > 0) lines.push(`Operations: ${event.operations.map(describeAssetOperation).join(", ")}`);
|
|
1730
|
+
if (event.status === "validated") {
|
|
1731
|
+
lines.push("Lifecycle: this candidate is registered, not live. The embedded image bytes remain available to the application and were omitted from model context.");
|
|
1732
|
+
const importedAssetIds = event.operations.filter((operation) => operation.kind === "set-image-asset").map((operation) => operation.assetId);
|
|
1733
|
+
if (importedAssetIds.length > 0) {
|
|
1734
|
+
lines.push(`Asset id to reference: ${importedAssetIds.join(", ")}`);
|
|
1735
|
+
lines.push("Required continuation: pass continuationMode \"append\" on every following mutation that should keep this asset import. To use the image in a NEW item, create that item in one survey_change call and put the image block directly in create-item.translations[].content; do not create placeholder text and do not call update-placed-image for an item that is not in the immutable snapshot. For an existing rich-text image placement, use update-placed-image. If a later proposal is rejected, re-import the attachment with continuationMode \"replace\", then append one corrected dependent survey_change; never replace the turn with only the asset reference.");
|
|
1736
|
+
lines.push(`New info-item image source: { "type": "asset", "assetId": "${importedAssetIds[0]}" }. Embed it in a richText image block inside the create-item translation content.`);
|
|
1737
|
+
lines.push(`New info-item translation example: { "locale": "<selected-locale>", "contentKey": "content", "content": { "type": "richText", "version": 1, "doc": { "type": "doc", "blocks": [{ "type": "image", "source": { "type": "asset", "assetId": "${importedAssetIds[0]}" }, "alt": "<meaningful description>" }] } } }.`);
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
if (event.validation.issues.length > 0) lines.push(`Issues:\n${event.validation.issues.map((issue) => `- ${issue.code}: ${issue.message}`).join("\n")}`);
|
|
1741
|
+
if (event.validation.warnings.length > 0) lines.push(`Warnings:\n${event.validation.warnings.map((warning) => `- ${warning.code}: ${warning.message}`).join("\n")}`);
|
|
1742
|
+
return lines.join("\n");
|
|
1743
|
+
};
|
|
1744
|
+
const redactEmbeddedImageOperation = (operation) => operation.kind === "set-image-asset" ? {
|
|
1745
|
+
...operation,
|
|
1746
|
+
asset: {
|
|
1747
|
+
...operation.asset,
|
|
1748
|
+
source: {
|
|
1749
|
+
...operation.asset.source,
|
|
1750
|
+
data: OMITTED_EMBEDDED_IMAGE_DATA
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
} : operation;
|
|
1754
|
+
const redactAssetChangeForTranscript = (event) => ({
|
|
1755
|
+
...event,
|
|
1756
|
+
operations: event.operations.map(redactEmbeddedImageOperation),
|
|
1757
|
+
validation: {
|
|
1758
|
+
...event.validation,
|
|
1759
|
+
normalizedOperations: event.validation.normalizedOperations.map(redactEmbeddedImageOperation)
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
const surveyAssetTool = createTool({
|
|
1763
|
+
id: TOOL_ID,
|
|
1764
|
+
description: "Import an attached image into survey assets without asking the model to copy base64, or update/remove an existing image asset. The result is an undoable candidate change, not a live asset. After importing, pass continuationMode \"append\" to the dependent mutation so the import and references are authorized together. For a new item, embed the asset image block directly in create-item.translations[].content in that one dependent call; update-placed-image is only for an image placement that already exists in the immutable snapshot. This tool refuses to remove a currently referenced asset. To delete references and their asset together, use one survey_change candidate with reference-removal operations first and remove-image-asset last.",
|
|
1765
|
+
inputSchema,
|
|
1766
|
+
outputSchema: surveyChangeSetSchema,
|
|
1767
|
+
mcp: { annotations: {
|
|
1768
|
+
title: "Prepare survey asset change",
|
|
1769
|
+
readOnlyHint: true,
|
|
1770
|
+
destructiveHint: false,
|
|
1771
|
+
idempotentHint: false,
|
|
1772
|
+
openWorldHint: false
|
|
1773
|
+
} },
|
|
1774
|
+
execute: async (input, context) => {
|
|
1775
|
+
const requestContext = context?.requestContext;
|
|
1776
|
+
const { changeCollector, turnId } = requireSurveyAssistantTurnState(requestContext);
|
|
1777
|
+
const snapshot = requestContext?.get("engineContext");
|
|
1778
|
+
let operation;
|
|
1779
|
+
if (input.action === "import-attachment") {
|
|
1780
|
+
if (!input.documentId) throw new Error("import-attachment requires documentId.");
|
|
1781
|
+
const access = requestContext?.get("attachmentAccess");
|
|
1782
|
+
const manifest = access?.documents.find((entry) => entry.id === input.documentId);
|
|
1783
|
+
if (!access || !manifest) throw new Error(`Attachment "${input.documentId}" is not available for this turn.`);
|
|
1784
|
+
if (!manifest.mediaType.startsWith("image/")) throw new Error(`Attachment "${manifest.name}" is not an image.`);
|
|
1785
|
+
const [loaded] = await access.load([input.documentId]);
|
|
1786
|
+
if (!loaded) throw new Error(`Attachment "${manifest.name}" could not be loaded.`);
|
|
1787
|
+
const base = input.assetId ?? slug(manifest.name);
|
|
1788
|
+
let assetId = base;
|
|
1789
|
+
let suffix = 2;
|
|
1790
|
+
while (snapshot?.survey.assets?.[assetId]) assetId = `${base}-${suffix++}`;
|
|
1791
|
+
operation = {
|
|
1792
|
+
kind: "set-image-asset",
|
|
1793
|
+
assetId,
|
|
1794
|
+
asset: {
|
|
1795
|
+
kind: "image",
|
|
1796
|
+
source: {
|
|
1797
|
+
type: "embedded",
|
|
1798
|
+
mediaType: loaded.mediaType,
|
|
1799
|
+
encoding: "base64",
|
|
1800
|
+
data: loaded.data
|
|
1801
|
+
},
|
|
1802
|
+
metadata: {
|
|
1803
|
+
filename: input.filename ?? loaded.filename,
|
|
1804
|
+
name: input.name ?? void 0,
|
|
1805
|
+
alt: input.alt ?? void 0
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
} else if (input.action === "update-metadata") {
|
|
1810
|
+
if (!input.assetId) throw new Error("update-metadata requires assetId.");
|
|
1811
|
+
operation = {
|
|
1812
|
+
kind: "update-image-asset-metadata",
|
|
1813
|
+
assetId: input.assetId,
|
|
1814
|
+
metadata: {
|
|
1815
|
+
name: input.name,
|
|
1816
|
+
filename: input.filename,
|
|
1817
|
+
alt: input.alt
|
|
1818
|
+
}
|
|
1819
|
+
};
|
|
1820
|
+
} else {
|
|
1821
|
+
if (!input.assetId) throw new Error("remove requires assetId.");
|
|
1822
|
+
operation = {
|
|
1823
|
+
kind: "remove-image-asset",
|
|
1824
|
+
assetId: input.assetId
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
let event = createSurveyChangeSet({
|
|
1828
|
+
operations: [operation],
|
|
1829
|
+
snapshot,
|
|
1830
|
+
summary: input.summary,
|
|
1831
|
+
turnId
|
|
1832
|
+
});
|
|
1833
|
+
if (operation.kind === "remove-image-asset") {
|
|
1834
|
+
const referenceLabels = getAssetReferenceLabels(snapshot, operation.assetId);
|
|
1835
|
+
if (referenceLabels.length > 0) event = surveyChangeSetSchema.parse({
|
|
1836
|
+
...event,
|
|
1837
|
+
status: "rejected",
|
|
1838
|
+
validation: {
|
|
1839
|
+
...event.validation,
|
|
1840
|
+
valid: false,
|
|
1841
|
+
issues: [...event.validation.issues, {
|
|
1842
|
+
severity: "error",
|
|
1843
|
+
code: "image-asset-still-referenced",
|
|
1844
|
+
message: `Image asset "${operation.assetId}" is still referenced by ${referenceLabels.slice(0, 3).join(", ")}. Prepare one survey_change candidate containing every reference-removal operation first and remove-image-asset last. If replacing earlier candidates in this turn, that combined candidate must use continuationMode "replace".`,
|
|
1845
|
+
operationIndex: 0
|
|
1846
|
+
}],
|
|
1847
|
+
normalizedOperations: []
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
return changeCollector.register(event, { continuationMode: input.continuationMode });
|
|
1852
|
+
},
|
|
1853
|
+
transform: { transcript: { output: ({ output }) => output ? redactAssetChangeForTranscript(getToolOutput(output)) : output } },
|
|
1854
|
+
toModelOutput: (value) => toTextModelOutput(value, summarizeAssetChange)
|
|
1855
|
+
});
|
|
1856
|
+
//#endregion
|
|
1857
|
+
//#region src/server/tools/index.ts
|
|
1858
|
+
const SURVEY_ASSISTANT_TOOL_IDS = [
|
|
1859
|
+
TOOL_ID$3,
|
|
1860
|
+
TOOL_ID$9,
|
|
1861
|
+
TOOL_ID$8,
|
|
1862
|
+
TOOL_ID$10,
|
|
1863
|
+
TOOL_ID$2,
|
|
1864
|
+
TOOL_ID$1,
|
|
1865
|
+
TOOL_ID
|
|
1866
|
+
];
|
|
1867
|
+
const surveyAssistantTools = Object.freeze({
|
|
1868
|
+
[TOOL_ID$3]: surveyInspectTool,
|
|
1869
|
+
[TOOL_ID$9]: surveyChangeTool,
|
|
1870
|
+
[TOOL_ID$10]: surveyAuthoringReferenceTool,
|
|
1871
|
+
[TOOL_ID$8]: surveyExpressionTool,
|
|
1872
|
+
[TOOL_ID$2]: surveyAttachmentTool,
|
|
1873
|
+
[TOOL_ID$1]: surveyAuditTool,
|
|
1874
|
+
[TOOL_ID]: surveyAssetTool
|
|
1875
|
+
});
|
|
1876
|
+
//#endregion
|
|
1877
|
+
export { surveyAuditTool as i, surveyAssistantTools as n, surveyAssetTool as r, SURVEY_ASSISTANT_TOOL_IDS as t };
|
|
1878
|
+
|
|
1879
|
+
//# sourceMappingURL=tools-Hz2p7vyv.mjs.map
|