@case-framework/survey-assistant 0.3.0 → 0.4.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.
Files changed (76) hide show
  1. package/README.md +12 -4
  2. package/dist/capabilities-default.d.mts +1 -1
  3. package/dist/capabilities-default.mjs +1 -1
  4. package/dist/{constants-DrGZXtQf.d.mts → constants-k1b_evIb.d.mts} +5 -2
  5. package/dist/constants-k1b_evIb.d.mts.map +1 -0
  6. package/dist/{controller-proxy-CpkQRezb.mjs → controller-proxy-jWIPOZAv.mjs} +17 -8
  7. package/dist/controller-proxy-jWIPOZAv.mjs.map +1 -0
  8. package/dist/{controller-proxy-DmBdzqKs.d.mts → controller-proxy-quQjtA7j.d.mts} +2 -2
  9. package/dist/{controller-proxy-DmBdzqKs.d.mts.map → controller-proxy-quQjtA7j.d.mts.map} +1 -1
  10. package/dist/{engine-CWTuN3o2.mjs → engine-BvfUx_Jx.mjs} +85 -12
  11. package/dist/engine-BvfUx_Jx.mjs.map +1 -0
  12. package/dist/engine.d.mts +2 -2
  13. package/dist/engine.mjs +3 -3
  14. package/dist/{form-authoring-DCd9XfXf.mjs → form-authoring-BQh40yDb.mjs} +2 -2
  15. package/dist/{form-authoring-DCd9XfXf.mjs.map → form-authoring-BQh40yDb.mjs.map} +1 -1
  16. package/dist/{index-D4OitUg4.d.mts → index-8x1Eqlnz.d.mts} +4 -1
  17. package/dist/index-8x1Eqlnz.d.mts.map +1 -0
  18. package/dist/{index-Dxgg0-D_.d.mts → index-BDp6S7r9.d.mts} +11 -5
  19. package/dist/index-BDp6S7r9.d.mts.map +1 -0
  20. package/dist/{index-DZk20e3k.d.mts → index-biZnRl-h.d.mts} +3 -3
  21. package/dist/{index-DZk20e3k.d.mts.map → index-biZnRl-h.d.mts.map} +1 -1
  22. package/dist/{index-Bo4dHAo8.d.mts → index-r8HVcn5b.d.mts} +8 -4
  23. package/dist/index-r8HVcn5b.d.mts.map +1 -0
  24. package/dist/{memory-thread-repository-acbz6HZJ.mjs → memory-thread-repository-xBZOog_q.mjs} +49 -21
  25. package/dist/memory-thread-repository-xBZOog_q.mjs.map +1 -0
  26. package/dist/{protocol-DATvkr1S.mjs → protocol-DJUP4gc0.mjs} +10 -4
  27. package/dist/protocol-DJUP4gc0.mjs.map +1 -0
  28. package/dist/protocol.d.mts +1 -1
  29. package/dist/protocol.mjs +1 -1
  30. package/dist/{react-Br5YE8H-.mjs → react-CY6N7lVi.mjs} +25 -5
  31. package/dist/react-CY6N7lVi.mjs.map +1 -0
  32. package/dist/react-integration.d.mts +1 -1
  33. package/dist/react-integration.mjs +1 -1
  34. package/dist/react.d.mts +2 -2
  35. package/dist/react.mjs +2 -2
  36. package/dist/{request-context-BEjnaaFr.mjs → request-context-DixY5DYu.mjs} +3 -3
  37. package/dist/request-context-DixY5DYu.mjs.map +1 -0
  38. package/dist/server-agent.d.mts +4 -4
  39. package/dist/server-agent.d.mts.map +1 -1
  40. package/dist/server-agent.mjs +4 -3
  41. package/dist/server-agent.mjs.map +1 -1
  42. package/dist/server-runtime.d.mts +340 -7
  43. package/dist/server-runtime.d.mts.map +1 -1
  44. package/dist/server-runtime.mjs +321 -23
  45. package/dist/server-runtime.mjs.map +1 -1
  46. package/dist/server-tasks.d.mts +1 -1
  47. package/dist/server-tasks.mjs +5 -4
  48. package/dist/server-tasks.mjs.map +1 -1
  49. package/dist/server-tools.d.mts +1 -1
  50. package/dist/server-tools.mjs +1 -1
  51. package/dist/server.d.mts +6 -6
  52. package/dist/server.d.mts.map +1 -1
  53. package/dist/server.mjs +2 -2
  54. package/dist/{tasks-DQgL449A.d.mts → tasks-BWmTMXoK.d.mts} +3 -3
  55. package/dist/{tasks-DQgL449A.d.mts.map → tasks-BWmTMXoK.d.mts.map} +1 -1
  56. package/dist/{thread-handlers-CeYl45xG.d.mts → thread-handlers-D8gkLfU6.d.mts} +13 -5
  57. package/dist/{thread-handlers-CeYl45xG.d.mts.map → thread-handlers-D8gkLfU6.d.mts.map} +1 -1
  58. package/dist/{tools-Dg9HZrYU.mjs → tools-TXI8bfzZ.mjs} +25 -6
  59. package/dist/{tools-Dg9HZrYU.mjs.map → tools-TXI8bfzZ.mjs.map} +1 -1
  60. package/dist/ui.css +1 -1
  61. package/dist/ui.d.mts +3 -3
  62. package/dist/ui.d.mts.map +1 -1
  63. package/dist/ui.mjs +370 -127
  64. package/dist/ui.mjs.map +1 -1
  65. package/docs/integration.md +83 -62
  66. package/package.json +3 -3
  67. package/dist/constants-DrGZXtQf.d.mts.map +0 -1
  68. package/dist/controller-proxy-CpkQRezb.mjs.map +0 -1
  69. package/dist/engine-CWTuN3o2.mjs.map +0 -1
  70. package/dist/index-Bo4dHAo8.d.mts.map +0 -1
  71. package/dist/index-D4OitUg4.d.mts.map +0 -1
  72. package/dist/index-Dxgg0-D_.d.mts.map +0 -1
  73. package/dist/memory-thread-repository-acbz6HZJ.mjs.map +0 -1
  74. package/dist/protocol-DATvkr1S.mjs.map +0 -1
  75. package/dist/react-Br5YE8H-.mjs.map +0 -1
  76. package/dist/request-context-BEjnaaFr.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { H as surveyDocumentVersionSchema, M as surveyAssistantThreadSchema, N as surveyAssistantThreadTranscriptSchema, f as surveyChangeSetSchema, j as surveyAssistantThreadListSchema, l as surveyAssistantTurnFinalSchema, n as SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE, o as surveyAssistantApplyOutcomeSchema, p as surveyAssistantModelCatalogSchema, r as applyReceiptSchema } from "./protocol-DATvkr1S.mjs";
2
- import { a as applySurveyAssistantLaunchUIContext, l as readSurveyAssistantJson } from "./controller-proxy-CpkQRezb.mjs";
1
+ import { H as surveyDocumentVersionSchema, M as surveyAssistantThreadSchema, N as surveyAssistantThreadTranscriptSchema, f as surveyChangeSetSchema, j as surveyAssistantThreadListSchema, l as surveyAssistantTurnFinalSchema, n as SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE, o as surveyAssistantApplyOutcomeSchema, p as surveyAssistantModelCatalogSchema, r as applyReceiptSchema } from "./protocol-DJUP4gc0.mjs";
2
+ import { a as applySurveyAssistantLaunchUIContext, l as readSurveyAssistantJson } from "./controller-proxy-jWIPOZAv.mjs";
3
3
  import { DefaultChatTransport } from "ai";
4
4
  import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useRef, useState } from "react";
5
5
  import { useChat } from "@ai-sdk/react";
@@ -147,6 +147,11 @@ const createApplyReceipts = ({ afterSnapshot, beforeSnapshot, changeSets, result
147
147
  const findLastUserMessage = (messages) => {
148
148
  for (let index = messages.length - 1; index >= 0; index -= 1) if (messages[index]?.role === "user") return messages[index];
149
149
  };
150
+ const fetchSurveyAssistantChat = async (input, init) => {
151
+ const response = await globalThis.fetch(input, init);
152
+ if (!response.ok) await readSurveyAssistantJson(response);
153
+ return response;
154
+ };
150
155
  const createSurveyAssistantTransport = ({ api = "/api/survey-assistant/chat", resourceId, surveyId, threadId }) => new DefaultChatTransport({
151
156
  api,
152
157
  body: {
@@ -154,6 +159,7 @@ const createSurveyAssistantTransport = ({ api = "/api/survey-assistant/chat", re
154
159
  ...surveyId ? { surveyId } : {},
155
160
  threadId
156
161
  },
162
+ fetch: fetchSurveyAssistantChat,
157
163
  prepareSendMessagesRequest: ({ api, body, credentials, headers, id, messageId, messages, trigger }) => {
158
164
  const latestUserMessage = findLastUserMessage(messages);
159
165
  return {
@@ -189,8 +195,15 @@ const createSurveyAssistantThreadClient = (api = "/api/survey-assistant/threads"
189
195
  const body = await readSurveyAssistantJson(await fetch(api, { cache: "no-store" }));
190
196
  return surveyAssistantThreadListSchema.parse(body).threads;
191
197
  },
192
- async read(threadId) {
193
- const body = await readSurveyAssistantJson(await fetch(`${api}/${encodeURIComponent(threadId)}`, { cache: "no-store" }));
198
+ async listPage(options) {
199
+ const search = new URLSearchParams();
200
+ if (options?.cursor) search.set("cursor", options.cursor);
201
+ const body = await readSurveyAssistantJson(await fetch(`${api}${search.size ? `?${search}` : ""}`, { cache: "no-store" }));
202
+ return surveyAssistantThreadListSchema.parse(body);
203
+ },
204
+ async read(threadId, cursor) {
205
+ const search = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
206
+ const body = await readSurveyAssistantJson(await fetch(`${api}/${encodeURIComponent(threadId)}${search}`, { cache: "no-store" }));
194
207
  return surveyAssistantThreadTranscriptSchema.parse(body);
195
208
  },
196
209
  async rename(threadId, title) {
@@ -416,6 +429,12 @@ const useSurveyAssistantSession = ({ api, applyPolicy, controller, initialMessag
416
429
  const notifyTurnActiveChange = useEffectEvent((active) => {
417
430
  onTurnActiveChange?.(active);
418
431
  });
432
+ const prependMessages = useCallback((olderMessages) => {
433
+ setMessages((current) => {
434
+ const currentIds = new Set(current.map((message) => message.id));
435
+ return [...olderMessages.filter((message) => !currentIds.has(message.id)), ...current];
436
+ });
437
+ }, [setMessages]);
419
438
  const turnAuthorization = useMemo(() => resolveLatestSurveyTurnAuthorization(messages), [messages]);
420
439
  const latestTurnOutcome = useMemo(() => resolveSurveyTurnOutcome({
421
440
  applyResultsByChangeId,
@@ -735,6 +754,7 @@ const useSurveyAssistantSession = ({ api, applyPolicy, controller, initialMessag
735
754
  isStreaming,
736
755
  latestTurnOutcome,
737
756
  messages,
757
+ prependMessages,
738
758
  state,
739
759
  status,
740
760
  stop,
@@ -745,4 +765,4 @@ const useSurveyAssistantSession = ({ api, applyPolicy, controller, initialMessag
745
765
  //#endregion
746
766
  export { createSurveyAssistantTransport as a, getSurveyDocumentVersionFromSnapshot as c, resolveSurveyTurnOutcome as d, unwrapSurveyAssistantToolOutput as f, createSurveyAssistantThreadClient as i, parseSurveyChangeSet as l, reduceSurveyAssistantSessionState as m, createSurveyAssistantModelCatalogClient as n, collectSurveyChangeSets as o, isSurveyAssistantTurnActive as p, useSurveyAssistantModelCatalog as r, createApplyReceipts as s, useSurveyAssistantSession as t, resolveLatestSurveyTurnAuthorization as u };
747
767
 
748
- //# sourceMappingURL=react-Br5YE8H-.mjs.map
768
+ //# sourceMappingURL=react-CY6N7lVi.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react-CY6N7lVi.mjs","names":["findLastUserMessageIndex"],"sources":["../src/react/session-state.ts","../src/react/turn-authorization.ts","../src/react/transport.ts","../src/react/thread-client.ts","../src/react/model-catalog.ts","../src/react/document-baseline.ts","../src/react/use-survey-assistant-session.ts"],"sourcesContent":["export type SurveyAssistantSessionState =\n | \"idle\"\n | \"submitting\"\n | \"streaming\"\n | \"completed\"\n | \"failed\"\n | \"aborted\"\n | \"applying\"\n | \"applied\";\n\nexport type SurveyAssistantSessionEvent =\n | { type: \"submit\" }\n | { type: \"stream-started\" }\n | { type: \"completed\" }\n | { type: \"apply-started\" }\n | { type: \"applied\" }\n | { type: \"failed\" }\n | { type: \"aborted\" }\n | { type: \"reset\"; hasTranscript: boolean };\n\nexport const isSurveyAssistantTurnActive = ({\n isStreaming,\n state,\n}: {\n isStreaming: boolean;\n state: SurveyAssistantSessionState;\n}): boolean =>\n state !== \"aborted\" &&\n (isStreaming || state === \"submitting\" || state === \"streaming\" || state === \"applying\");\n\nexport const reduceSurveyAssistantSessionState = (\n _state: SurveyAssistantSessionState,\n event: SurveyAssistantSessionEvent,\n): SurveyAssistantSessionState => {\n switch (event.type) {\n case \"submit\":\n return \"submitting\";\n case \"stream-started\":\n return \"streaming\";\n case \"completed\":\n return \"completed\";\n case \"apply-started\":\n return \"applying\";\n case \"applied\":\n return \"applied\";\n case \"failed\":\n return \"failed\";\n case \"aborted\":\n return \"aborted\";\n case \"reset\":\n return event.hasTranscript ? \"completed\" : \"idle\";\n }\n};\n","import {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE,\n applyReceiptSchema,\n surveyAssistantTurnFinalSchema,\n surveyChangeSetSchema,\n type ApplyReceipt,\n type SurveyAssistantSnapshot,\n type SurveyAssistantTurnFinal,\n type SurveyApplyResult,\n type SurveyChangeSet,\n type SurveyDocumentVersion,\n} from \"../protocol\";\nimport type { UIMessage } from \"ai\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isCompletedToolPart = (\n part: UIMessage[\"parts\"][number],\n): part is UIMessage[\"parts\"][number] & { state: \"output-available\"; output: unknown } =>\n (part.type === \"dynamic-tool\" || part.type.startsWith(\"tool-\")) &&\n \"state\" in part &&\n part.state === \"output-available\" &&\n \"output\" in part;\n\nexport const unwrapSurveyAssistantToolOutput = (output: unknown) => {\n if (isRecord(output) && \"output\" in output && output.output !== undefined) {\n return output.output;\n }\n return output;\n};\n\nexport const parseSurveyChangeSet = (output: unknown): SurveyChangeSet | null => {\n const parsed = surveyChangeSetSchema.safeParse(unwrapSurveyAssistantToolOutput(output));\n return parsed.success ? parsed.data : null;\n};\n\nexport const collectSurveyChangeSets = (messages: UIMessage[]): SurveyChangeSet[] => {\n const changes: SurveyChangeSet[] = [];\n for (const message of messages) {\n for (const part of message.parts) {\n if (!isCompletedToolPart(part)) {\n continue;\n }\n const change = parseSurveyChangeSet(part.output);\n if (change) {\n changes.push(change);\n }\n }\n }\n return changes;\n};\n\nconst findLastUserMessageIndex = (messages: UIMessage[]) => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return index;\n }\n return -1;\n};\n\nexport type SurveyTurnAuthorization =\n | { status: \"pending\" }\n | { status: \"invalid\"; reason: string; turnId?: string }\n | {\n status: \"failed\" | \"aborted\";\n turnFinal: SurveyAssistantTurnFinal;\n changeSets: [];\n }\n | {\n status: \"completed\";\n turnFinal: SurveyAssistantTurnFinal;\n changeSets: SurveyChangeSet[];\n };\n\nexport type SurveyTurnOutcome =\n | {\n status: \"failed\";\n terminationReason?: SurveyAssistantTurnFinal[\"terminationReason\"];\n }\n | {\n status: \"aborted\";\n terminationReason?: SurveyAssistantTurnFinal[\"terminationReason\"];\n }\n | {\n status: \"blocked\";\n blockedChangeSetCount: number;\n }\n | {\n status: \"apply-failed\";\n appliedChangeSetCount: number;\n failedChangeSetCount: number;\n };\n\nexport const resolveLatestSurveyTurnAuthorization = (\n messages: UIMessage[],\n): SurveyTurnAuthorization => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n if (lastUserIndex < 0) {\n return { status: \"pending\" };\n }\n\n const turnMessages = messages.slice(lastUserIndex + 1);\n const finalParts = turnMessages\n .flatMap((message) => message.parts)\n .filter((part) => part.type === SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE);\n if (finalParts.length === 0) {\n return { status: \"pending\" };\n }\n if (finalParts.length !== 1) {\n return { status: \"invalid\", reason: \"The assistant returned multiple turn finals.\" };\n }\n\n const finalPart = finalParts[0];\n const finalParse = surveyAssistantTurnFinalSchema.safeParse(\n finalPart && \"data\" in finalPart ? finalPart.data : undefined,\n );\n if (!finalParse.success) {\n return { status: \"invalid\", reason: \"The assistant returned an invalid turn final.\" };\n }\n const turnFinal = finalParse.data;\n if (turnFinal.status !== \"completed\") {\n return { status: turnFinal.status, turnFinal, changeSets: [] };\n }\n\n const candidates = collectSurveyChangeSets(turnMessages).filter(\n (change) => change.turnId === turnFinal.turnId,\n );\n const candidatesById = new Map<string, SurveyChangeSet>();\n for (const candidate of candidates) {\n if (candidatesById.has(candidate.id)) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant returned duplicate change set \"${candidate.id}\".`,\n };\n }\n candidatesById.set(candidate.id, candidate);\n }\n\n for (const blockedChangeSetId of turnFinal.blockedChangeSetIds ?? []) {\n const candidate = candidatesById.get(blockedChangeSetId);\n if (!candidate || candidate.status !== \"rejected\" || candidate.validation.valid) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant did not provide blocked change set \"${blockedChangeSetId}\".`,\n };\n }\n }\n\n const changeSets: SurveyChangeSet[] = [];\n for (const changeSetId of turnFinal.executableChangeSetIds) {\n const candidate = candidatesById.get(changeSetId);\n if (!candidate || candidate.status !== \"validated\" || !candidate.validation.valid) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant did not provide authorized change set \"${changeSetId}\".`,\n };\n }\n changeSets.push(candidate);\n }\n\n return { status: \"completed\", turnFinal, changeSets };\n};\n\nexport const resolveSurveyTurnOutcome = ({\n applyResultsByChangeId,\n authorization,\n}: {\n applyResultsByChangeId: Record<string, SurveyApplyResult>;\n authorization: SurveyTurnAuthorization;\n}): SurveyTurnOutcome | null => {\n if (authorization.status === \"failed\" || authorization.status === \"aborted\") {\n return {\n status: authorization.status,\n terminationReason: authorization.turnFinal.terminationReason,\n };\n }\n if (authorization.status !== \"completed\") {\n return null;\n }\n\n const blockedChangeSetCount = authorization.turnFinal.blockedChangeSetIds?.length ?? 0;\n if (blockedChangeSetCount > 0) {\n return { status: \"blocked\", blockedChangeSetCount };\n }\n\n if (authorization.changeSets.length === 0) {\n return null;\n }\n\n const results = authorization.changeSets.map((change) => applyResultsByChangeId[change.id]);\n if (results.some((result) => result === undefined)) {\n return null;\n }\n\n const failedChangeSetCount = results.filter((result) => result.status !== \"applied\").length;\n if (failedChangeSetCount === 0) {\n return null;\n }\n\n return {\n status: \"apply-failed\",\n appliedChangeSetCount: results.length - failedChangeSetCount,\n failedChangeSetCount,\n };\n};\n\nexport const getSurveyDocumentVersionFromSnapshot = (\n snapshot: SurveyAssistantSnapshot,\n): SurveyDocumentVersion => ({ ...snapshot.version });\n\nexport const createApplyReceipts = ({\n afterSnapshot,\n beforeSnapshot,\n changeSets,\n results,\n turnFinal,\n createdAt = new Date().toISOString(),\n}: {\n afterSnapshot: SurveyAssistantSnapshot | null;\n beforeSnapshot: SurveyAssistantSnapshot;\n changeSets: SurveyChangeSet[];\n results: SurveyApplyResult[];\n turnFinal: SurveyAssistantTurnFinal;\n createdAt?: string;\n}): ApplyReceipt[] => {\n const beforeVersion = getSurveyDocumentVersionFromSnapshot(beforeSnapshot);\n const afterVersion = afterSnapshot\n ? getSurveyDocumentVersionFromSnapshot(afterSnapshot)\n : undefined;\n const resultsByChangeId = new Map(results.map((result) => [result.changeId, result]));\n\n return changeSets.map((changeSet) => {\n const result = resultsByChangeId.get(changeSet.id);\n const status = result?.status ?? \"failed\";\n return applyReceiptSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId: turnFinal.turnId,\n changeSetId: changeSet.id,\n beforeVersion,\n ...(status === \"applied\" && afterVersion ? { afterVersion } : {}),\n status,\n operationCount: changeSet.operations.length,\n ...(status === \"applied\" && afterVersion?.historyIndex !== undefined\n ? { commit: { index: afterVersion.historyIndex } }\n : {}),\n ...(result?.issues ? { issues: result.issues } : {}),\n createdAt,\n });\n });\n};\n","import { DefaultChatTransport, type UIMessage } from \"ai\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nconst findLastUserMessage = (messages: UIMessage[]): UIMessage | undefined => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return messages[index];\n }\n return undefined;\n};\n\nconst fetchSurveyAssistantChat: typeof fetch = async (input, init) => {\n const response = await globalThis.fetch(input, init);\n if (!response.ok) await readSurveyAssistantJson(response);\n return response;\n};\n\nexport const createSurveyAssistantTransport = ({\n api = \"/api/survey-assistant/chat\",\n resourceId,\n surveyId,\n threadId,\n}: {\n api?: string;\n resourceId: string;\n surveyId?: string;\n threadId: string;\n}) =>\n new DefaultChatTransport({\n api,\n body: { resourceId, ...(surveyId ? { surveyId } : {}), threadId },\n fetch: fetchSurveyAssistantChat,\n prepareSendMessagesRequest: ({\n api,\n body,\n credentials,\n headers,\n id,\n messageId,\n messages,\n trigger,\n }) => {\n const latestUserMessage = findLastUserMessage(messages);\n return {\n api,\n credentials,\n headers,\n body: {\n ...body,\n id,\n messages: latestUserMessage ? [latestUserMessage] : [],\n trigger,\n messageId,\n },\n };\n },\n });\n","import {\n surveyAssistantThreadListSchema,\n surveyAssistantThreadSchema,\n surveyAssistantThreadTranscriptSchema,\n type SurveyAssistantThread,\n type SurveyAssistantThreadList,\n type SurveyAssistantThreadTranscript,\n} from \"../protocol\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nexport interface SurveyAssistantThreadClient {\n delete(threadId: string): Promise<void>;\n create(title?: string): Promise<SurveyAssistantThread>;\n list(): Promise<SurveyAssistantThread[]>;\n /** Paged history capability. Older custom clients may omit this method. */\n listPage?(options?: { cursor?: string }): Promise<SurveyAssistantThreadList>;\n read(threadId: string, cursor?: string): Promise<SurveyAssistantThreadTranscript>;\n rename(threadId: string, title: string): Promise<SurveyAssistantThread>;\n setAutomaticTitle(threadId: string, title?: string): Promise<SurveyAssistantThread>;\n}\n\nexport const createSurveyAssistantThreadClient = (\n api = \"/api/survey-assistant/threads\",\n): SurveyAssistantThreadClient => ({\n async delete(threadId) {\n const response = await fetch(`${api}/${encodeURIComponent(threadId)}`, { method: \"DELETE\" });\n if (!response.ok) await readSurveyAssistantJson(response);\n },\n async create(title) {\n const body = await readSurveyAssistantJson(\n await fetch(api, {\n body: JSON.stringify(title ? { title } : {}),\n headers: { \"content-type\": \"application/json\" },\n method: \"POST\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n async list() {\n const body = await readSurveyAssistantJson(await fetch(api, { cache: \"no-store\" }));\n return surveyAssistantThreadListSchema.parse(body).threads;\n },\n async listPage(options) {\n const search = new URLSearchParams();\n if (options?.cursor) search.set(\"cursor\", options.cursor);\n const body = await readSurveyAssistantJson(\n await fetch(`${api}${search.size ? `?${search}` : \"\"}`, { cache: \"no-store\" }),\n );\n return surveyAssistantThreadListSchema.parse(body);\n },\n async read(threadId, cursor) {\n const search = cursor ? `?cursor=${encodeURIComponent(cursor)}` : \"\";\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}${search}`, { cache: \"no-store\" }),\n );\n return surveyAssistantThreadTranscriptSchema.parse(body);\n },\n async rename(threadId, title) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, {\n body: JSON.stringify({ mode: \"manual\", title }),\n headers: { \"content-type\": \"application/json\" },\n method: \"PATCH\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n async setAutomaticTitle(threadId, title) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, {\n body: JSON.stringify({ mode: \"automatic\", ...(title ? { title } : {}) }),\n headers: { \"content-type\": \"application/json\" },\n method: \"PATCH\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n});\n","import { useCallback, useEffect, useState } from \"react\";\nimport {\n surveyAssistantModelCatalogSchema,\n type SurveyAssistantModelCatalog,\n type SurveyAssistantModelOption,\n} from \"../protocol\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nconst DEFAULT_MODEL_STORAGE_KEY = \"survey-assistant-selected-model\";\n\nexport interface SurveyAssistantModelCatalogClient {\n get(): Promise<SurveyAssistantModelCatalog>;\n}\n\nexport const createSurveyAssistantModelCatalogClient = (\n api = \"/api/survey-assistant/models\",\n): SurveyAssistantModelCatalogClient => ({\n async get() {\n const body = await readSurveyAssistantJson(\n await fetch(api, { cache: \"no-store\" }),\n \"The assistant model catalog could not be loaded.\",\n );\n return surveyAssistantModelCatalogSchema.parse(body);\n },\n});\n\nexport interface UseSurveyAssistantModelCatalogOptions {\n api?: string;\n client?: SurveyAssistantModelCatalogClient;\n onModelChange?(modelId: string): void;\n storageKey?: string | false;\n}\n\nexport interface SurveyAssistantModelCatalogState {\n error: Error | null;\n loading: boolean;\n modelId?: string;\n models: SurveyAssistantModelOption[];\n reload(): void;\n selectModel(modelId: string): void;\n}\n\nexport const useSurveyAssistantModelCatalog = ({\n api,\n client: providedClient,\n onModelChange,\n storageKey = DEFAULT_MODEL_STORAGE_KEY,\n}: UseSurveyAssistantModelCatalogOptions = {}): SurveyAssistantModelCatalogState => {\n const [models, setModels] = useState<SurveyAssistantModelOption[]>([]);\n const [modelId, setModelId] = useState<string>();\n const [error, setError] = useState<Error | null>(null);\n const [loading, setLoading] = useState(true);\n const [reloadToken, setReloadToken] = useState(0);\n\n useEffect(() => {\n let cancelled = false;\n const client = providedClient ?? createSurveyAssistantModelCatalogClient(api);\n setLoading(true);\n setError(null);\n void client\n .get()\n .then((catalog) => {\n if (cancelled) return;\n const rememberedId =\n storageKey && typeof window !== \"undefined\"\n ? (window.localStorage.getItem(storageKey) ?? undefined)\n : undefined;\n const selectedId =\n rememberedId && catalog.models.some((model) => model.id === rememberedId)\n ? rememberedId\n : catalog.defaultModelId;\n setModels(catalog.models);\n setModelId(selectedId);\n onModelChange?.(selectedId);\n })\n .catch((reason: unknown) => {\n if (!cancelled) setError(reason instanceof Error ? reason : new Error(String(reason)));\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [api, onModelChange, providedClient, reloadToken, storageKey]);\n\n const selectModel = useCallback(\n (nextModelId: string) => {\n if (!models.some((model) => model.id === nextModelId)) return;\n setModelId(nextModelId);\n if (storageKey && typeof window !== \"undefined\") {\n window.localStorage.setItem(storageKey, nextModelId);\n }\n onModelChange?.(nextModelId);\n },\n [models, onModelChange, storageKey],\n );\n\n const reload = useCallback(() => setReloadToken((current) => current + 1), []);\n\n return { error, loading, modelId, models, reload, selectModel };\n};\n","\"use client\";\n\nimport {\n surveyDocumentVersionSchema,\n type SurveyAssistantSnapshot,\n type SurveyDocumentVersion,\n} from \"../protocol\";\n\nconst STORAGE_PREFIX = \"case-survey-assistant:settled-document:\";\nconst memoryBaselines = new Map<string, SurveyDocumentVersion>();\n\nconst getStorageKey = (resourceId: string, threadId: string) =>\n `${STORAGE_PREFIX}${encodeURIComponent(resourceId)}:${encodeURIComponent(threadId)}`;\n\nconst getSessionStorage = (): Storage | undefined => {\n if (typeof document === \"undefined\") return undefined;\n\n try {\n return window.sessionStorage;\n } catch {\n return undefined;\n }\n};\n\nexport const readSettledDocumentVersion = ({\n resourceId,\n threadId,\n}: {\n resourceId: string;\n threadId: string;\n}): SurveyDocumentVersion | undefined => {\n const storageKey = getStorageKey(resourceId, threadId);\n const storedInMemory = memoryBaselines.get(storageKey);\n if (storedInMemory) return { ...storedInMemory };\n\n const serialized = getSessionStorage()?.getItem(storageKey);\n if (!serialized) return undefined;\n\n try {\n const parsed = surveyDocumentVersionSchema.safeParse(JSON.parse(serialized));\n if (!parsed.success) return undefined;\n memoryBaselines.set(storageKey, parsed.data);\n return { ...parsed.data };\n } catch {\n return undefined;\n }\n};\n\nexport const writeSettledDocumentVersion = ({\n resourceId,\n snapshot,\n threadId,\n}: {\n resourceId: string;\n snapshot: SurveyAssistantSnapshot;\n threadId: string;\n}): void => {\n const storageKey = getStorageKey(resourceId, threadId);\n const version = surveyDocumentVersionSchema.parse(snapshot.version);\n memoryBaselines.set(storageKey, version);\n\n try {\n getSessionStorage()?.setItem(storageKey, JSON.stringify(version));\n } catch {\n // In-memory continuity still works when browser storage is disabled or full.\n }\n};\n","\"use client\";\n\nimport { useChat } from \"@ai-sdk/react\";\nimport {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n surveyAssistantApplyOutcomeSchema,\n type ApplyReceipt,\n type SurveyAssistantApplyOutcome,\n type SurveyApplyResult,\n type SurveyAssistantApplyPolicy,\n type SurveyAssistantTurnFinal,\n type SurveyChangeSet,\n} from \"../protocol\";\nimport type { ChatStatus, FileUIPart, UIMessage } from \"ai\";\nimport {\n useCallback,\n useEffect,\n useEffectEvent,\n useMemo,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport {\n collectSurveyChangeSets,\n createApplyReceipts,\n resolveLatestSurveyTurnAuthorization,\n resolveSurveyTurnOutcome,\n} from \"./turn-authorization\";\nimport { isSurveyAssistantTurnActive, reduceSurveyAssistantSessionState } from \"./session-state\";\nimport type { SurveyAssistantSessionState } from \"./session-state\";\nimport type { SurveyTurnOutcome } from \"./turn-authorization\";\nimport { createSurveyAssistantTransport } from \"./transport\";\nimport type { SurveyAssistantController } from \"./controller\";\nimport { readSettledDocumentVersion, writeSettledDocumentVersion } from \"./document-baseline\";\nimport {\n applySurveyAssistantLaunchUIContext,\n type SurveyAssistantLaunchUIContext,\n} from \"./thread-launcher\";\n\nconst createLocalId = (prefix: string) => {\n const id = globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2);\n return `${prefix}-${id}`;\n};\n\nconst compactOutcomeText = (value: string, maximum: number, fallback: string) => {\n const normalized = value.trim() || fallback;\n return normalized.length > maximum ? `${normalized.slice(0, maximum - 1)}…` : normalized;\n};\n\nconst createApplyOutcome = ({\n message,\n preparedChanges,\n results,\n status,\n turnId,\n}: {\n message: string;\n preparedChanges?: SurveyChangeSet[];\n results?: SurveyApplyResult[];\n status: SurveyAssistantApplyOutcome[\"status\"];\n turnId: string;\n}): SurveyAssistantApplyOutcome =>\n surveyAssistantApplyOutcomeSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId,\n status,\n message: compactOutcomeText(message, 2_000, \"No lifecycle detail was reported.\"),\n ...(results && results.length > 0\n ? {\n results: results.slice(0, 100).map((result) => ({\n status: result.status,\n changeId: compactOutcomeText(result.changeId, 240, \"unknown-change\"),\n summary: compactOutcomeText(result.summary, 500, \"Survey change\"),\n message: compactOutcomeText(result.message, 2_000, \"No apply detail was reported.\"),\n appliedOperations: result.appliedOperations,\n })),\n }\n : {}),\n ...(preparedChanges && preparedChanges.length > 0\n ? {\n preparedChanges: preparedChanges.slice(-24).map((change) => ({\n changeId: compactOutcomeText(change.id, 240, \"unknown-change\"),\n status: change.status,\n summary: compactOutcomeText(change.summary, 500, \"Survey change\"),\n operationCount: change.operations.length,\n })),\n }\n : {}),\n createdAt: new Date().toISOString(),\n });\n\ntype AssistantTextPart = Extract<UIMessage[\"parts\"][number], { type: \"text\" }>;\n\nconst getAssistantTextParts = (message: UIMessage) =>\n message.parts.filter(\n (part): part is AssistantTextPart => part.type === \"text\" && part.text.trim().length > 0,\n );\n\nconst findLastAssistantTextMessageIndex = (\n messages: UIMessage[],\n endExclusive = messages.length,\n) => {\n for (let index = Math.min(messages.length, endExclusive) - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role === \"assistant\" && getAssistantTextParts(message).length > 0) return index;\n }\n return -1;\n};\n\nconst findLastUserMessageIndex = (messages: UIMessage[]) => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return index;\n }\n return -1;\n};\n\nconst pruneFailedMessagesForDisplay = (messages: UIMessage[]): UIMessage[] => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n const lastCompletedAssistantIndex = findLastAssistantTextMessageIndex(messages);\n\n if (lastUserIndex > lastCompletedAssistantIndex) return messages.slice(0, lastUserIndex + 1);\n return lastCompletedAssistantIndex >= 0 ? messages.slice(0, lastCompletedAssistantIndex + 1) : [];\n};\n\nconst hasCompletedAssistantResponseAfterLastUser = (messages: UIMessage[]) => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n return lastUserIndex >= 0 && findLastAssistantTextMessageIndex(messages) > lastUserIndex;\n};\n\nconst collectChangeSetsAfterLastUser = (messages: UIMessage[]) => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n return lastUserIndex < 0 ? [] : collectSurveyChangeSets(messages.slice(lastUserIndex + 1));\n};\n\nconst getInitialSessionState = (messages: UIMessage[]): SurveyAssistantSessionState => {\n if (messages.length === 0) return \"idle\";\n const authorization = resolveLatestSurveyTurnAuthorization(messages);\n if (authorization.status === \"failed\") return \"failed\";\n if (authorization.status === \"aborted\") return \"aborted\";\n return \"completed\";\n};\n\nexport interface SurveyAssistantSessionOptions {\n api?: string;\n /** Explicit host decision: apply immediately, present for review, or deny mutations. */\n applyPolicy: SurveyAssistantApplyPolicy;\n controller?: SurveyAssistantController | null;\n initialMessages?: UIMessage[];\n modelId?: string;\n onApplyReceipts?: (receipts: ApplyReceipt[]) => void;\n /**\n * Production persistence/audit barrier. The turn remains active until this\n * resolves; rejection leaves the settled baseline unchanged.\n */\n onSettleApply?: (input: {\n changeSets: SurveyChangeSet[];\n receipts: ApplyReceipt[];\n turnFinal: SurveyAssistantTurnFinal;\n }) => void | Promise<void>;\n /**\n * Required for `review`. Resolve true to apply the authorized change sets,\n * or false to leave the editor unchanged.\n */\n onReviewChangeSets?: (\n changeSets: SurveyChangeSet[],\n turnFinal: SurveyAssistantTurnFinal,\n ) => boolean | Promise<boolean>;\n /** Reports when a turn owns the editor state, including submission, streaming, and apply. */\n onTurnActiveChange?: (active: boolean) => void;\n resourceId?: string;\n /** Host survey id sent as untrusted request context for server-side authorization. */\n surveyId?: string;\n threadId?: string;\n}\n\nexport const resolveSurveyAssistantReviewDecision = async ({\n changeSets,\n onReviewChangeSets,\n turnFinal,\n}: {\n changeSets: SurveyChangeSet[];\n onReviewChangeSets?: SurveyAssistantSessionOptions[\"onReviewChangeSets\"];\n turnFinal: SurveyAssistantTurnFinal;\n}) => {\n if (!onReviewChangeSets) {\n throw new Error(\"No survey assistant review adapter is available.\");\n }\n return onReviewChangeSets(changeSets, turnFinal);\n};\n\nexport interface SurveyAssistantSubmitMessage {\n text: string;\n files: FileUIPart[];\n /** Optional model used for this turn instead of the session's selected model. */\n modelId?: string;\n /** Turn-local UI context layered over the controller snapshot for this submission. */\n uiContext?: SurveyAssistantLaunchUIContext;\n}\n\nexport interface SurveyAssistantSession {\n applyResultsByChangeId: Record<string, SurveyApplyResult>;\n authorizationError: string | null;\n dismissError(): void;\n error: Error | undefined;\n isStreaming: boolean;\n latestTurnOutcome: SurveyTurnOutcome | null;\n messages: UIMessage[];\n prependMessages(messages: UIMessage[]): void;\n state: SurveyAssistantSessionState;\n status: ChatStatus;\n stop(): void;\n submit(message: SurveyAssistantSubmitMessage): boolean;\n retry(): void;\n}\n\nexport const useSurveyAssistantSession = ({\n api,\n applyPolicy,\n controller,\n initialMessages = [],\n modelId,\n onApplyReceipts,\n onSettleApply,\n onReviewChangeSets,\n onTurnActiveChange,\n resourceId: controlledResourceId,\n surveyId,\n threadId: controlledThreadId,\n}: SurveyAssistantSessionOptions): SurveyAssistantSession => {\n const [localResourceId] = useState(() => createLocalId(\"survey-assistant-local-user\"));\n const [localThreadId] = useState(() => createLocalId(\"survey-assistant-local-thread\"));\n const resourceId = controlledResourceId ?? localResourceId;\n const threadId = controlledThreadId ?? localThreadId;\n const applyOutcomeScopeKey = `${resourceId}\\u0000${threadId}`;\n const [state, dispatch] = useReducer(\n reduceSurveyAssistantSessionState,\n initialMessages,\n getInitialSessionState,\n );\n const [applyResultsByChangeId, setApplyResultsByChangeId] = useState<\n Record<string, SurveyApplyResult>\n >({});\n const [authorizationError, setAuthorizationError] = useState<string | null>(null);\n const handledTurnIdsRef = useRef<Set<string>>(new Set());\n const localTurnAwaitingApplyRef = useRef(false);\n const localTurnStreamStartedRef = useRef(false);\n const captureSettledVersionRef = useRef(false);\n const lastSubmittedUIContextRef = useRef<SurveyAssistantLaunchUIContext | undefined>(undefined);\n const lastSubmittedModelIdRef = useRef<string | undefined>(undefined);\n const previousApplyOutcomesRef = useRef<Map<string, SurveyAssistantApplyOutcome>>(new Map());\n\n const transport = useMemo(\n () => createSurveyAssistantTransport({ api, resourceId, surveyId, threadId }),\n [api, resourceId, surveyId, threadId],\n );\n const {\n messages,\n setMessages,\n sendMessage,\n status,\n stop: stopChat,\n error,\n clearError,\n regenerate,\n } = useChat({ id: threadId, messages: initialMessages, transport });\n const isStreaming = status === \"submitted\" || status === \"streaming\";\n const isTurnActive = isSurveyAssistantTurnActive({ isStreaming, state });\n const notifyTurnActiveChange = useEffectEvent((active: boolean) => {\n onTurnActiveChange?.(active);\n });\n const prependMessages = useCallback(\n (olderMessages: UIMessage[]) => {\n setMessages((current) => {\n const currentIds = new Set(current.map((message) => message.id));\n return [...olderMessages.filter((message) => !currentIds.has(message.id)), ...current];\n });\n },\n [setMessages],\n );\n const turnAuthorization = useMemo(\n () => resolveLatestSurveyTurnAuthorization(messages),\n [messages],\n );\n const latestTurnOutcome = useMemo(\n () => resolveSurveyTurnOutcome({ applyResultsByChangeId, authorization: turnAuthorization }),\n [applyResultsByChangeId, turnAuthorization],\n );\n const hasUsefulLatestAssistantResponse = useMemo(\n () =>\n hasCompletedAssistantResponseAfterLastUser(messages) ||\n collectChangeSetsAfterLastUser(messages).length > 0,\n [messages],\n );\n\n const reportAuthorizationError = useCallback((message: string) => {\n queueMicrotask(() => {\n setAuthorizationError(message);\n dispatch({ type: \"failed\" });\n });\n }, []);\n\n useEffect(() => {\n if (status === \"submitted\") dispatch({ type: \"submit\" });\n if (status === \"streaming\") dispatch({ type: \"stream-started\" });\n }, [status]);\n\n useEffect(() => {\n notifyTurnActiveChange(isTurnActive);\n\n return () => {\n if (isTurnActive) notifyTurnActiveChange(false);\n };\n }, [isTurnActive]);\n\n useEffect(() => {\n if (\n !captureSettledVersionRef.current ||\n isStreaming ||\n (state !== \"completed\" && state !== \"failed\" && state !== \"aborted\" && state !== \"applied\")\n ) {\n return;\n }\n\n captureSettledVersionRef.current = false;\n const snapshot = controller?.getSnapshot();\n if (snapshot) {\n writeSettledDocumentVersion({ resourceId, snapshot, threadId });\n }\n }, [controller, isStreaming, resourceId, state, threadId]);\n\n useEffect(() => {\n if (isStreaming) {\n localTurnStreamStartedRef.current = true;\n return;\n }\n if (!localTurnAwaitingApplyRef.current) return;\n\n if (turnAuthorization.status === \"pending\") {\n if (!localTurnStreamStartedRef.current) return;\n const timeoutId = window.setTimeout(() => {\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n reportAuthorizationError(\"The assistant response ended without a valid turn final.\");\n }, 100);\n return () => window.clearTimeout(timeoutId);\n }\n\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n if (turnAuthorization.status === \"invalid\") {\n reportAuthorizationError(turnAuthorization.reason);\n return;\n }\n\n const { turnFinal } = turnAuthorization;\n if (handledTurnIdsRef.current.has(turnFinal.turnId)) return;\n handledTurnIdsRef.current.add(turnFinal.turnId);\n const preparedChanges = collectChangeSetsAfterLastUser(messages).filter(\n (change) => change.turnId === turnFinal.turnId,\n );\n\n if (turnAuthorization.status === \"failed\") {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn failed before editor authorization. Every request-scoped draft change from that turn was discarded and was not applied.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"failed\" });\n return;\n }\n if (turnAuthorization.status === \"aborted\") {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn was interrupted before editor authorization. Every request-scoped draft change from that turn was discarded and was not applied.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"aborted\" });\n return;\n }\n if (turnAuthorization.changeSets.length === 0) {\n if ((turnFinal.blockedChangeSetIds?.length ?? 0) > 0) {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn ended with unresolved rejected changes. No request-scoped draft change from that turn was authorized or applied.\",\n preparedChanges,\n }),\n );\n }\n dispatch({ type: \"completed\" });\n return;\n }\n if (applyPolicy === \"deny\") {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message: \"The host apply policy did not authorize editor mutations for this turn.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n dispatch({ type: \"apply-started\" });\n void (async () => {\n if (applyPolicy === \"review\") {\n let approved: boolean;\n try {\n approved = await resolveSurveyAssistantReviewDecision({\n changeSets: turnAuthorization.changeSets,\n onReviewChangeSets,\n turnFinal,\n });\n } catch (error) {\n const message =\n error instanceof Error &&\n error.message === \"No survey assistant review adapter is available.\"\n ? error.message\n : \"The survey assistant review could not be completed.\";\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message,\n preparedChanges,\n }),\n );\n reportAuthorizationError(message);\n return;\n }\n if (!approved) {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message: \"The proposed editor changes were not approved during review.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n }\n\n if (!controller?.applyAssistantChange && !controller?.applyAssistantChanges) {\n const message = \"No survey editor apply adapter is available.\";\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"apply-failed\",\n message,\n preparedChanges,\n }),\n );\n reportAuthorizationError(message);\n return;\n }\n const beforeSnapshot = controller.getSnapshot();\n if (!beforeSnapshot) {\n const message = \"The editor state was unavailable when applying the assistant change.\";\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"apply-failed\",\n message,\n preparedChanges,\n }),\n );\n reportAuthorizationError(message);\n return;\n }\n\n const result = controller.applyAssistantChanges?.(turnAuthorization.changeSets) ?? {\n results: turnAuthorization.changeSets\n .map((change) => controller.applyAssistantChange?.(change))\n .filter((applyResult): applyResult is SurveyApplyResult => Boolean(applyResult)),\n };\n queueMicrotask(() =>\n setApplyResultsByChangeId((current) => ({\n ...current,\n ...Object.fromEntries(\n result.results.map((applyResult) => [applyResult.changeId, applyResult]),\n ),\n })),\n );\n const receipts = createApplyReceipts({\n beforeSnapshot,\n afterSnapshot: controller.getSnapshot(),\n changeSets: turnAuthorization.changeSets,\n results: result.results,\n turnFinal,\n });\n onApplyReceipts?.(receipts);\n if (!result.results.every((applyResult) => applyResult.status === \"applied\")) {\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"apply-failed\",\n message: \"One or more authorized survey changes could not be applied to the editor.\",\n preparedChanges,\n results: result.results,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n try {\n await onSettleApply?.({\n changeSets: turnAuthorization.changeSets,\n receipts,\n turnFinal,\n });\n previousApplyOutcomesRef.current.delete(applyOutcomeScopeKey);\n dispatch({ type: \"applied\" });\n } catch {\n const message =\n \"The assistant changes were applied locally but could not be settled by the host.\";\n previousApplyOutcomesRef.current.set(\n applyOutcomeScopeKey,\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"settle-failed\",\n message,\n results: result.results,\n }),\n );\n reportAuthorizationError(message);\n }\n })();\n }, [\n applyPolicy,\n applyOutcomeScopeKey,\n controller,\n isStreaming,\n onApplyReceipts,\n onReviewChangeSets,\n onSettleApply,\n reportAuthorizationError,\n messages,\n turnAuthorization,\n ]);\n\n useEffect(() => {\n if (!error) return;\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n dispatch({ type: \"failed\" });\n if (!hasUsefulLatestAssistantResponse) setMessages(pruneFailedMessagesForDisplay);\n }, [error, hasUsefulLatestAssistantResponse, setMessages]);\n\n const submit = useCallback(\n ({\n files,\n modelId: submittedModelId,\n text: rawText,\n uiContext,\n }: SurveyAssistantSubmitMessage) => {\n const text = rawText.trim();\n if (!text && files.length === 0) return false;\n if (isStreaming || localTurnAwaitingApplyRef.current) return false;\n\n localTurnAwaitingApplyRef.current = true;\n localTurnStreamStartedRef.current = false;\n setAuthorizationError(null);\n if (authorizationError || error) setMessages(pruneFailedMessagesForDisplay);\n clearError();\n dispatch({ type: \"submit\" });\n captureSettledVersionRef.current = true;\n lastSubmittedUIContextRef.current = uiContext;\n lastSubmittedModelIdRef.current = submittedModelId ?? modelId;\n\n const controllerSnapshot = controller?.getSnapshot() ?? null;\n const snapshot = applySurveyAssistantLaunchUIContext(controllerSnapshot, uiContext);\n void sendMessage(files.length > 0 ? (text ? { text, files } : { files }) : { text }, {\n body: {\n snapshot,\n previousSettledVersion: readSettledDocumentVersion({ resourceId, threadId }),\n previousApplyOutcome: previousApplyOutcomesRef.current.get(applyOutcomeScopeKey),\n ...(lastSubmittedModelIdRef.current ? { modelId: lastSubmittedModelIdRef.current } : {}),\n },\n });\n return true;\n },\n [\n authorizationError,\n applyOutcomeScopeKey,\n clearError,\n controller,\n error,\n isStreaming,\n modelId,\n resourceId,\n sendMessage,\n setMessages,\n threadId,\n ],\n );\n\n const stop = useCallback(() => {\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n dispatch({ type: \"aborted\" });\n void stopChat();\n }, [stopChat]);\n\n const retry = useCallback(() => {\n localTurnAwaitingApplyRef.current = true;\n localTurnStreamStartedRef.current = false;\n setAuthorizationError(null);\n clearError();\n dispatch({ type: \"submit\" });\n captureSettledVersionRef.current = true;\n const controllerSnapshot = controller?.getSnapshot() ?? null;\n const uiContext = lastSubmittedUIContextRef.current;\n const snapshot = applySurveyAssistantLaunchUIContext(controllerSnapshot, uiContext);\n void regenerate({\n body: {\n snapshot,\n previousSettledVersion: readSettledDocumentVersion({ resourceId, threadId }),\n previousApplyOutcome: previousApplyOutcomesRef.current.get(applyOutcomeScopeKey),\n ...(lastSubmittedModelIdRef.current ? { modelId: lastSubmittedModelIdRef.current } : {}),\n },\n });\n }, [applyOutcomeScopeKey, clearError, controller, modelId, regenerate, resourceId, threadId]);\n\n const dismissError = useCallback(() => {\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n setMessages(pruneFailedMessagesForDisplay);\n setAuthorizationError(null);\n clearError();\n dispatch({ type: \"reset\", hasTranscript: messages.length > 0 });\n }, [clearError, messages.length, setMessages]);\n\n return {\n applyResultsByChangeId,\n authorizationError,\n dismissError,\n error,\n isStreaming,\n latestTurnOutcome,\n messages,\n prependMessages,\n state,\n status,\n stop,\n submit,\n retry,\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAa,+BAA+B,EAC1C,aACA,YAKA,UAAU,cACT,eAAe,UAAU,gBAAgB,UAAU,eAAe,UAAU;AAE/E,MAAa,qCACX,QACA,UACgC;AACh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,cAZmB,kBAAkB;AACrC,6BAA0B,UAAU;AACpC,6BAA0B,UAAU;AACpC,eAAY,8BAA8B;AAC1C,yBAAsB,KAAK;AAC3B,eAAY;AACZ,YAAS;IAAE,MAAM;IAAS,eAAe,SAAS,SAAS;IAAG,CAAC;KAC9D;GAAC;GAAY,SAAS;GAAQ;GAAY,CAK/B;EACZ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
@@ -1,2 +1,2 @@
1
- import { _ as createSurveyAssistantThreadLauncher, a as SurveyAssistantController, c as SurveyAssistantTaskExecutionOptions, d as SurveyAssistantTaskExecutorRequestOptions, f as createSurveyAssistantTaskClient, g as SurveyAssistantThreadLauncher, h as SurveyAssistantThreadLaunch, i as createSurveyAssistantControllerProxy, l as SurveyAssistantTaskExecutor, m as SurveyAssistantLaunchUIContext, n as SurveyAssistantControllerBridge, o as SurveyAssistantTaskClient, p as createSurveyAssistantTaskExecutor, r as createSurveyAssistantControllerBridge, s as SurveyAssistantTaskClientOptions, t as CreateSurveyAssistantControllerProxyOptions, u as SurveyAssistantTaskExecutorCacheContext } from "./controller-proxy-DmBdzqKs.mjs";
1
+ import { _ as createSurveyAssistantThreadLauncher, a as SurveyAssistantController, c as SurveyAssistantTaskExecutionOptions, d as SurveyAssistantTaskExecutorRequestOptions, f as createSurveyAssistantTaskClient, g as SurveyAssistantThreadLauncher, h as SurveyAssistantThreadLaunch, i as createSurveyAssistantControllerProxy, l as SurveyAssistantTaskExecutor, m as SurveyAssistantLaunchUIContext, n as SurveyAssistantControllerBridge, o as SurveyAssistantTaskClient, p as createSurveyAssistantTaskExecutor, r as createSurveyAssistantControllerBridge, s as SurveyAssistantTaskClientOptions, t as CreateSurveyAssistantControllerProxyOptions, u as SurveyAssistantTaskExecutorCacheContext } from "./controller-proxy-quQjtA7j.mjs";
2
2
  export { type CreateSurveyAssistantControllerProxyOptions, type SurveyAssistantController, type SurveyAssistantControllerBridge, type SurveyAssistantLaunchUIContext, type SurveyAssistantTaskClient, type SurveyAssistantTaskClientOptions, type SurveyAssistantTaskExecutionOptions, type SurveyAssistantTaskExecutor, type SurveyAssistantTaskExecutorCacheContext, type SurveyAssistantTaskExecutorRequestOptions, type SurveyAssistantThreadLaunch, type SurveyAssistantThreadLauncher, createSurveyAssistantControllerBridge, createSurveyAssistantControllerProxy, createSurveyAssistantTaskClient, createSurveyAssistantTaskExecutor, createSurveyAssistantThreadLauncher };
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- import { i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-CpkQRezb.mjs";
2
+ import { i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-jWIPOZAv.mjs";
3
3
  export { createSurveyAssistantControllerBridge, createSurveyAssistantControllerProxy, createSurveyAssistantTaskClient, createSurveyAssistantTaskExecutor, createSurveyAssistantThreadLauncher };
package/dist/react.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { C as SurveyAssistantSessionEvent, E as reduceSurveyAssistantSessionState, S as unwrapSurveyAssistantToolOutput, T as isSurveyAssistantTurnActive, _ as createApplyReceipts, a as SurveyAssistantModelCatalogClient, b as resolveLatestSurveyTurnAuthorization, c as createSurveyAssistantModelCatalogClient, d as SurveyAssistantThreadClient, f as createSurveyAssistantThreadClient, g as collectSurveyChangeSets, h as SurveyTurnOutcome, i as useSurveyAssistantSession, l as useSurveyAssistantModelCatalog, m as SurveyTurnAuthorization, n as SurveyAssistantSessionOptions, o as SurveyAssistantModelCatalogState, p as createSurveyAssistantTransport, r as SurveyAssistantSubmitMessage, s as UseSurveyAssistantModelCatalogOptions, t as SurveyAssistantSession, u as SurveyAssistantClientError, v as getSurveyDocumentVersionFromSnapshot, w as SurveyAssistantSessionState, x as resolveSurveyTurnOutcome, y as parseSurveyChangeSet } from "./index-Dxgg0-D_.mjs";
2
- import { _ as createSurveyAssistantThreadLauncher, a as SurveyAssistantController, c as SurveyAssistantTaskExecutionOptions, d as SurveyAssistantTaskExecutorRequestOptions, f as createSurveyAssistantTaskClient, g as SurveyAssistantThreadLauncher, h as SurveyAssistantThreadLaunch, i as createSurveyAssistantControllerProxy, l as SurveyAssistantTaskExecutor, m as SurveyAssistantLaunchUIContext, n as SurveyAssistantControllerBridge, o as SurveyAssistantTaskClient, p as createSurveyAssistantTaskExecutor, r as createSurveyAssistantControllerBridge, s as SurveyAssistantTaskClientOptions, t as CreateSurveyAssistantControllerProxyOptions, u as SurveyAssistantTaskExecutorCacheContext } from "./controller-proxy-DmBdzqKs.mjs";
1
+ import { C as SurveyAssistantSessionEvent, E as reduceSurveyAssistantSessionState, S as unwrapSurveyAssistantToolOutput, T as isSurveyAssistantTurnActive, _ as createApplyReceipts, a as SurveyAssistantModelCatalogClient, b as resolveLatestSurveyTurnAuthorization, c as createSurveyAssistantModelCatalogClient, d as SurveyAssistantThreadClient, f as createSurveyAssistantThreadClient, g as collectSurveyChangeSets, h as SurveyTurnOutcome, i as useSurveyAssistantSession, l as useSurveyAssistantModelCatalog, m as SurveyTurnAuthorization, n as SurveyAssistantSessionOptions, o as SurveyAssistantModelCatalogState, p as createSurveyAssistantTransport, r as SurveyAssistantSubmitMessage, s as UseSurveyAssistantModelCatalogOptions, t as SurveyAssistantSession, u as SurveyAssistantClientError, v as getSurveyDocumentVersionFromSnapshot, w as SurveyAssistantSessionState, x as resolveSurveyTurnOutcome, y as parseSurveyChangeSet } from "./index-BDp6S7r9.mjs";
2
+ import { _ as createSurveyAssistantThreadLauncher, a as SurveyAssistantController, c as SurveyAssistantTaskExecutionOptions, d as SurveyAssistantTaskExecutorRequestOptions, f as createSurveyAssistantTaskClient, g as SurveyAssistantThreadLauncher, h as SurveyAssistantThreadLaunch, i as createSurveyAssistantControllerProxy, l as SurveyAssistantTaskExecutor, m as SurveyAssistantLaunchUIContext, n as SurveyAssistantControllerBridge, o as SurveyAssistantTaskClient, p as createSurveyAssistantTaskExecutor, r as createSurveyAssistantControllerBridge, s as SurveyAssistantTaskClientOptions, t as CreateSurveyAssistantControllerProxyOptions, u as SurveyAssistantTaskExecutorCacheContext } from "./controller-proxy-quQjtA7j.mjs";
3
3
  export { CreateSurveyAssistantControllerProxyOptions, SurveyAssistantClientError, SurveyAssistantController, SurveyAssistantControllerBridge, SurveyAssistantLaunchUIContext, SurveyAssistantModelCatalogClient, SurveyAssistantModelCatalogState, SurveyAssistantSession, SurveyAssistantSessionEvent, SurveyAssistantSessionOptions, SurveyAssistantSessionState, SurveyAssistantSubmitMessage, SurveyAssistantTaskClient, SurveyAssistantTaskClientOptions, SurveyAssistantTaskExecutionOptions, SurveyAssistantTaskExecutor, SurveyAssistantTaskExecutorCacheContext, SurveyAssistantTaskExecutorRequestOptions, SurveyAssistantThreadClient, SurveyAssistantThreadLaunch, SurveyAssistantThreadLauncher, SurveyTurnAuthorization, SurveyTurnOutcome, UseSurveyAssistantModelCatalogOptions, collectSurveyChangeSets, createApplyReceipts, createSurveyAssistantControllerBridge, createSurveyAssistantControllerProxy, createSurveyAssistantModelCatalogClient, createSurveyAssistantTaskClient, createSurveyAssistantTaskExecutor, createSurveyAssistantThreadClient, createSurveyAssistantThreadLauncher, createSurveyAssistantTransport, getSurveyDocumentVersionFromSnapshot, isSurveyAssistantTurnActive, parseSurveyChangeSet, reduceSurveyAssistantSessionState, resolveLatestSurveyTurnAuthorization, resolveSurveyTurnOutcome, unwrapSurveyAssistantToolOutput, useSurveyAssistantModelCatalog, useSurveyAssistantSession };
package/dist/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  "use client";
2
- import { a as createSurveyAssistantTransport, c as getSurveyDocumentVersionFromSnapshot, d as resolveSurveyTurnOutcome, f as unwrapSurveyAssistantToolOutput, i as createSurveyAssistantThreadClient, l as parseSurveyChangeSet, m as reduceSurveyAssistantSessionState, n as createSurveyAssistantModelCatalogClient, o as collectSurveyChangeSets, p as isSurveyAssistantTurnActive, r as useSurveyAssistantModelCatalog, s as createApplyReceipts, t as useSurveyAssistantSession, u as resolveLatestSurveyTurnAuthorization } from "./react-Br5YE8H-.mjs";
3
- import { c as SurveyAssistantClientError, i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-CpkQRezb.mjs";
2
+ import { a as createSurveyAssistantTransport, c as getSurveyDocumentVersionFromSnapshot, d as resolveSurveyTurnOutcome, f as unwrapSurveyAssistantToolOutput, i as createSurveyAssistantThreadClient, l as parseSurveyChangeSet, m as reduceSurveyAssistantSessionState, n as createSurveyAssistantModelCatalogClient, o as collectSurveyChangeSets, p as isSurveyAssistantTurnActive, r as useSurveyAssistantModelCatalog, s as createApplyReceipts, t as useSurveyAssistantSession, u as resolveLatestSurveyTurnAuthorization } from "./react-CY6N7lVi.mjs";
3
+ import { c as SurveyAssistantClientError, i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-jWIPOZAv.mjs";
4
4
  export { SurveyAssistantClientError, collectSurveyChangeSets, createApplyReceipts, createSurveyAssistantControllerBridge, createSurveyAssistantControllerProxy, createSurveyAssistantModelCatalogClient, createSurveyAssistantTaskClient, createSurveyAssistantTaskExecutor, createSurveyAssistantThreadClient, createSurveyAssistantThreadLauncher, createSurveyAssistantTransport, getSurveyDocumentVersionFromSnapshot, isSurveyAssistantTurnActive, parseSurveyChangeSet, reduceSurveyAssistantSessionState, resolveLatestSurveyTurnAuthorization, resolveSurveyTurnOutcome, unwrapSurveyAssistantToolOutput, useSurveyAssistantModelCatalog, useSurveyAssistantSession };
@@ -1,5 +1,5 @@
1
- import { H as surveyDocumentVersionSchema, o as surveyAssistantApplyOutcomeSchema, z as surveyAssistantSnapshotPayloadSchema } from "./protocol-DATvkr1S.mjs";
2
- import { Q as createSurveyAssistantEngineContext } from "./engine-CWTuN3o2.mjs";
1
+ import { H as surveyDocumentVersionSchema, o as surveyAssistantApplyOutcomeSchema, z as surveyAssistantSnapshotPayloadSchema } from "./protocol-DJUP4gc0.mjs";
2
+ import { et as createSurveyAssistantEngineContext } from "./engine-BvfUx_Jx.mjs";
3
3
  import { defaultSurveyAssistantCapabilitySet } from "./capabilities-default.mjs";
4
4
  import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
5
5
  //#region src/server/request-context.ts
@@ -88,4 +88,4 @@ const requireSurveyAssistantTurnState = (requestContext) => {
88
88
  //#endregion
89
89
  export { parseSurveyAssistantPreviousSettledVersion as a, parseSurveyAssistantPreviousApplyOutcome as i, deriveSurveyAssistantDocumentTransition as n, parseSurveyAssistantSnapshot as o, getSurveyAssistantEngineContext as r, requireSurveyAssistantTurnState as s, buildSurveyAssistantRequestContext as t };
90
90
 
91
- //# sourceMappingURL=request-context-BEjnaaFr.mjs.map
91
+ //# sourceMappingURL=request-context-DixY5DYu.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context-DixY5DYu.mjs","names":[],"sources":["../src/server/request-context.ts"],"sourcesContent":["import {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_THREAD_ID_KEY,\n RequestContext,\n} from \"@mastra/core/request-context\";\nimport type { OpenAICompatibleConfig } from \"@mastra/core/llm\";\nimport type { AgentExecutionOptions } from \"@mastra/core/agent\";\nimport {\n surveyAssistantSnapshotPayloadSchema,\n surveyAssistantApplyOutcomeSchema,\n surveyDocumentVersionSchema,\n type SurveyAssistantApplyOutcome,\n type SurveyDocumentSnapshot,\n type SurveyDocumentVersion,\n} from \"../protocol\";\nimport {\n createSurveyAssistantEngineContext,\n TurnSurveyDraft,\n type SurveyAssistantCapabilitySet,\n type SurveyAssistantEngineContext,\n} from \"../engine\";\nimport { defaultSurveyAssistantCapabilitySet } from \"../capabilities/default\";\nimport type {\n SurveyAssistantAttachmentAccess,\n SurveyAssistantModelAttachment,\n} from \"./thread-documents\";\n\nexport interface SurveyAssistantInvocationContext {\n kind: \"chat\";\n}\n\nexport interface SurveyAssistantIdentityContext {\n authority: \"experimental-client-request\" | \"authenticated-host\";\n resourceId: string;\n surveyId?: string;\n threadId: string;\n}\n\nexport interface SurveyAssistantModelSelection {\n id: string;\n model: string | OpenAICompatibleConfig;\n providerName?: string;\n providerOptions?: AgentExecutionOptions[\"providerOptions\"];\n}\n\nexport type SurveyAssistantDocumentTransition =\n | { status: \"no-baseline\" }\n | {\n status: \"session-changed\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n }\n | {\n status: \"unchanged\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n capabilitiesChanged: boolean;\n }\n | {\n status: \"changed\";\n previousHistoryIndex: number;\n currentHistoryIndex: number;\n historyDirection: \"backward\" | \"forward\" | \"same-index\";\n recordedSources: Array<\"user\" | \"system\" | \"assistant\">;\n capabilitiesChanged: boolean;\n };\n\nexport interface SurveyAssistantRequestContext {\n invocation: SurveyAssistantInvocationContext;\n turnId: string;\n turnDraft: TurnSurveyDraft;\n identity: SurveyAssistantIdentityContext;\n authenticatedResourceId?: string;\n authorizedThreadId?: string;\n applyPolicy?: \"auto\" | \"review\" | \"deny\";\n mastra__resourceId?: string;\n mastra__threadId?: string;\n documentTransition?: SurveyAssistantDocumentTransition;\n engineContext?: SurveyAssistantEngineContext;\n documentSnapshot?: SurveyDocumentSnapshot;\n modelAttachments?: SurveyAssistantModelAttachment[];\n attachmentAccess?: SurveyAssistantAttachmentAccess;\n modelSelection?: SurveyAssistantModelSelection;\n previousApplyOutcome?: SurveyAssistantApplyOutcome;\n}\n\nexport const parseSurveyAssistantSnapshot = (value: unknown): SurveyDocumentSnapshot | null => {\n if (value === undefined || value === null) {\n return null;\n }\n\n return surveyAssistantSnapshotPayloadSchema.parse(value);\n};\n\nexport const parseSurveyAssistantPreviousSettledVersion = (\n value: unknown,\n): SurveyDocumentVersion | null => {\n if (value === undefined || value === null) {\n return null;\n }\n\n return surveyDocumentVersionSchema.parse(value);\n};\n\nexport const parseSurveyAssistantPreviousApplyOutcome = (\n value: unknown,\n): SurveyAssistantApplyOutcome | null => {\n if (value === undefined || value === null) {\n return null;\n }\n\n return surveyAssistantApplyOutcomeSchema.parse(value);\n};\n\nexport const deriveSurveyAssistantDocumentTransition = ({\n current,\n previous,\n}: {\n current: SurveyDocumentSnapshot | null;\n previous: SurveyDocumentVersion | null;\n}): SurveyAssistantDocumentTransition | undefined => {\n if (!current) return undefined;\n if (!previous) return { status: \"no-baseline\" };\n\n const previousHistoryIndex = previous.historyIndex;\n const currentHistoryIndex = current.version.historyIndex;\n if (previous.sessionId !== current.version.sessionId) {\n return {\n status: \"session-changed\",\n previousHistoryIndex,\n currentHistoryIndex,\n };\n }\n\n const capabilitiesChanged = previous.capabilityDigest !== current.version.capabilityDigest;\n if (previous.contentHash === current.version.contentHash) {\n return {\n status: \"unchanged\",\n previousHistoryIndex,\n currentHistoryIndex,\n capabilitiesChanged,\n };\n }\n\n const historyDirection =\n currentHistoryIndex > previousHistoryIndex\n ? \"forward\"\n : currentHistoryIndex < previousHistoryIndex\n ? \"backward\"\n : \"same-index\";\n const recordedSources =\n historyDirection === \"forward\"\n ? [\n ...new Set(\n (current.ui.history?.recent ?? [])\n .filter(\n (entry) => entry.index > previousHistoryIndex && entry.index <= currentHistoryIndex,\n )\n .flatMap((entry) => (entry.source ? [entry.source] : [])),\n ),\n ]\n : [];\n\n return {\n status: \"changed\",\n previousHistoryIndex,\n currentHistoryIndex,\n historyDirection,\n recordedSources,\n capabilitiesChanged,\n };\n};\n\nexport const buildSurveyAssistantRequestContext = ({\n turnDraft,\n identity,\n snapshot,\n previousSettledVersion = null,\n trustedCapabilities = defaultSurveyAssistantCapabilitySet,\n attachmentAccess,\n modelAttachments = [],\n modelSelection,\n previousApplyOutcome,\n}: {\n turnDraft: TurnSurveyDraft;\n identity: SurveyAssistantIdentityContext;\n snapshot: SurveyDocumentSnapshot | null;\n previousSettledVersion?: SurveyDocumentVersion | null;\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n attachmentAccess?: SurveyAssistantAttachmentAccess;\n modelAttachments?: SurveyAssistantModelAttachment[];\n modelSelection?: SurveyAssistantModelSelection;\n previousApplyOutcome?: SurveyAssistantApplyOutcome | null;\n}): RequestContext<SurveyAssistantRequestContext> => {\n const requestContext = new RequestContext<SurveyAssistantRequestContext>();\n\n requestContext.set(\"invocation\", { kind: \"chat\" });\n requestContext.set(\"turnId\", turnDraft.turnId);\n requestContext.set(\"turnDraft\", turnDraft);\n requestContext.set(\"identity\", identity);\n if (identity.authority === \"authenticated-host\") {\n requestContext.set(\"authenticatedResourceId\", identity.resourceId);\n requestContext.set(\"authorizedThreadId\", identity.threadId);\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, identity.resourceId);\n requestContext.set(MASTRA_THREAD_ID_KEY, identity.threadId);\n const documentTransition = deriveSurveyAssistantDocumentTransition({\n current: snapshot,\n previous: previousSettledVersion,\n });\n if (documentTransition) {\n requestContext.set(\"documentTransition\", documentTransition);\n }\n if (attachmentAccess && attachmentAccess.documents.length > 0) {\n requestContext.set(\"attachmentAccess\", attachmentAccess);\n }\n if (modelAttachments.length > 0) {\n requestContext.set(\"modelAttachments\", modelAttachments);\n }\n if (modelSelection) {\n requestContext.set(\"modelSelection\", modelSelection);\n }\n if (previousApplyOutcome) {\n requestContext.set(\"previousApplyOutcome\", previousApplyOutcome);\n }\n\n if (!snapshot) {\n return requestContext;\n }\n\n const engineContext = createSurveyAssistantEngineContext(snapshot, trustedCapabilities);\n turnDraft.initialize(engineContext);\n requestContext.set(\"documentSnapshot\", snapshot);\n requestContext.set(\"engineContext\", engineContext);\n\n return requestContext;\n};\n\n/**\n * Returns the materialized request-local survey state. The immutable\n * engineContext remains available as the turn baseline, while every tool uses\n * this accessor so successful same-turn mutations are immediately visible.\n */\nexport const getSurveyAssistantEngineContext = (\n requestContext: RequestContext<SurveyAssistantRequestContext> | undefined,\n): SurveyAssistantEngineContext | undefined =>\n requestContext?.get(\"turnDraft\")?.context ?? requestContext?.get(\"engineContext\");\n\nexport const requireSurveyAssistantTurnState = (\n requestContext: RequestContext<SurveyAssistantRequestContext> | undefined,\n) => {\n const turnId = requestContext?.get(\"turnId\");\n const turnDraft = requestContext?.get(\"turnDraft\");\n if (!turnId || !turnDraft || turnDraft.turnId !== turnId) {\n throw new Error(\"Survey assistant turn context is unavailable or inconsistent.\");\n }\n\n return { turnId, turnDraft };\n};\n"],"mappings":";;;;;AAsFA,MAAa,gCAAgC,UAAkD;AAC7F,KAAI,UAAU,KAAA,KAAa,UAAU,KACnC,QAAO;AAGT,QAAO,qCAAqC,MAAM,MAAM;;AAG1D,MAAa,8CACX,UACiC;AACjC,KAAI,UAAU,KAAA,KAAa,UAAU,KACnC,QAAO;AAGT,QAAO,4BAA4B,MAAM,MAAM;;AAGjD,MAAa,4CACX,UACuC;AACvC,KAAI,UAAU,KAAA,KAAa,UAAU,KACnC,QAAO;AAGT,QAAO,kCAAkC,MAAM,MAAM;;AAGvD,MAAa,2CAA2C,EACtD,SACA,eAImD;AACnD,KAAI,CAAC,QAAS,QAAO,KAAA;AACrB,KAAI,CAAC,SAAU,QAAO,EAAE,QAAQ,eAAe;CAE/C,MAAM,uBAAuB,SAAS;CACtC,MAAM,sBAAsB,QAAQ,QAAQ;AAC5C,KAAI,SAAS,cAAc,QAAQ,QAAQ,UACzC,QAAO;EACL,QAAQ;EACR;EACA;EACD;CAGH,MAAM,sBAAsB,SAAS,qBAAqB,QAAQ,QAAQ;AAC1E,KAAI,SAAS,gBAAgB,QAAQ,QAAQ,YAC3C,QAAO;EACL,QAAQ;EACR;EACA;EACA;EACD;CAGH,MAAM,mBACJ,sBAAsB,uBAClB,YACA,sBAAsB,uBACpB,aACA;AAc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,IAAI,oBAAoB,SAAS;AAChD,gBAAe,IAAI,iBAAiB,cAAc;AAElD,QAAO;;;;;;;AAQT,MAAa,mCACX,mBAEA,gBAAgB,IAAI,YAAY,EAAE,WAAW,gBAAgB,IAAI,gBAAgB;AAEnF,MAAa,mCACX,mBACG;CACH,MAAM,SAAS,gBAAgB,IAAI,SAAS;CAC5C,MAAM,YAAY,gBAAgB,IAAI,YAAY;AAClD,KAAI,CAAC,UAAU,CAAC,aAAa,UAAU,WAAW,OAChD,OAAM,IAAI,MAAM,gEAAgE;AAGlF,QAAO;EAAE;EAAQ;EAAW"}
@@ -1,6 +1,6 @@
1
1
  import { g as SurveyChangeSetShape } from "./lifecycle-DWv5CiSu.mjs";
2
- import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-DrGZXtQf.mjs";
3
- import { n as surveyAssistantTools } from "./index-DZk20e3k.mjs";
2
+ import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-k1b_evIb.mjs";
3
+ import { n as surveyAssistantTools } from "./index-biZnRl-h.mjs";
4
4
  import * as _$_mastra_core_agent0 from "@mastra/core/agent";
5
5
  import { Agent, AgentConfig } from "@mastra/core/agent";
6
6
  import { Memory } from "@mastra/memory";
@@ -37,7 +37,7 @@ declare const createSurveyAssistantAgent: ({
37
37
  observationalMemory
38
38
  }: CreateSurveyAssistantAgentOptions) => Agent<"survey-assistant-agent", Readonly<{
39
39
  survey_inspect: _$_mastra_core_tools0.Tool<{
40
- action: "current-context" | "search-items" | "item-details" | "localization" | "assets" | "raw-json";
40
+ action: "current-context" | "search-items" | "item-details" | "localization" | "assets" | "expression-diagnostics" | "raw-json";
41
41
  reason?: string | undefined;
42
42
  scopes?: ("summary" | "selected-item" | "outline" | "response-slots" | "ui-context" | "history")[] | undefined;
43
43
  query?: string | undefined;
@@ -53,7 +53,7 @@ declare const createSurveyAssistantAgent: ({
53
53
  limit?: number | undefined;
54
54
  }, {
55
55
  ok: boolean;
56
- action: "current-context" | "search-items" | "item-details" | "localization" | "assets" | "raw-json";
56
+ action: "current-context" | "search-items" | "item-details" | "localization" | "assets" | "expression-diagnostics" | "raw-json";
57
57
  modelSummary: string;
58
58
  reason?: string | undefined;
59
59
  result?: unknown;
@@ -1 +1 @@
1
- {"version":3,"file":"server-agent.d.mts","names":[],"sources":["../src/server/agent.ts"],"mappings":";;;;;;;;;;cAwBa,wCAAA,EAA0C,cAAA;AAAA,KA4SlD,0BAAA,GAA6B,WAAA,QACzB,yBAAA,SACA,oBAAA,aAEP,6BAAA;AAAA,KAGG,4BAAA,GAA+B,WAAA,CAClC,WAAA,CAAY,qBAAA,QAA6B,MAAA;AAAA,KA8E/B,yCAAA,GAA4C,OAAA,CACtD,4BAAA;AAAA,KAIG,8CAAA,GAAiD,OAAA,CACpD,IAAA,CAAK,yCAAA;EAEL,KAAA,EAAO,WAAA,CAAY,yCAAA;AAAA;AAAA,cAGR,8CAAA;EAAA;;;;cAMA,+CAAA;EAAmD,KAAA;EAAA,WAAA;EAAA,UAAA;EAAA,GAAA;AAAA,GAK7D,8CAAA,KAAiD,yCAAA;AAAA,UAkCnC,iCAAA;EACf,KAAA,EAAO,0BAAA;EACP,MAAA,GAAS,0BAAA;EACT,mBAAA,GAAsB,yCAAA;AAAA;AAAA,cAGX,0BAAA;EAA8B,MAAA;EAAA,KAAA;EAAA;AAAA,GAIxC,iCAAA,KAAiC,KAAA,2BAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;uBAAA,qBAAA,CAAA,oBAAA"}
1
+ {"version":3,"file":"server-agent.d.mts","names":[],"sources":["../src/server/agent.ts"],"mappings":";;;;;;;;;;cAwBa,wCAAA,EAA0C,cAAA;AAAA,KA6SlD,0BAAA,GAA6B,WAAA,QACzB,yBAAA,SACA,oBAAA,aAEP,6BAAA;AAAA,KAGG,4BAAA,GAA+B,WAAA,CAClC,WAAA,CAAY,qBAAA,QAA6B,MAAA;AAAA,KA8E/B,yCAAA,GAA4C,OAAA,CACtD,4BAAA;AAAA,KAIG,8CAAA,GAAiD,OAAA,CACpD,IAAA,CAAK,yCAAA;EAEL,KAAA,EAAO,WAAA,CAAY,yCAAA;AAAA;AAAA,cAGR,8CAAA;EAAA;;;;cAMA,+CAAA;EAAmD,KAAA;EAAA,WAAA;EAAA,UAAA;EAAA,GAAA;AAAA,GAK7D,8CAAA,KAAiD,yCAAA;AAAA,UAkCnC,iCAAA;EACf,KAAA,EAAO,0BAAA;EACP,MAAA,GAAS,0BAAA;EACT,mBAAA,GAAsB,yCAAA;AAAA;AAAA,cAGX,0BAAA;EAA8B,MAAA;EAAA,KAAA;EAAA;AAAA,GAIxC,iCAAA,KAAiC,KAAA,2BAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;uBAAA,qBAAA,CAAA,oBAAA"}
@@ -1,7 +1,7 @@
1
- import { d as getDeterministicCreateItemTypes } from "./form-authoring-DCd9XfXf.mjs";
1
+ import { d as getDeterministicCreateItemTypes } from "./form-authoring-BQh40yDb.mjs";
2
2
  import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CFUWrRtl.mjs";
3
3
  import { t as FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from "./fair-guidance-CEdJYccK.mjs";
4
- import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-Dg9HZrYU.mjs";
4
+ import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-TXI8bfzZ.mjs";
5
5
  import { createHash } from "node:crypto";
6
6
  import { Agent } from "@mastra/core/agent";
7
7
  import { Memory } from "@mastra/memory";
@@ -154,7 +154,8 @@ const buildInstructions = ({ requestContext }) => {
154
154
  "The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.",
155
155
  "Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.",
156
156
  "For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.",
157
- `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action "localization" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action "assets" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what "this", "here", or "the highlighted part" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,
157
+ `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action "expression-diagnostics" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, and bounded replacement candidates. Use action "localization" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action "assets" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what "this", "here", or "the highlighted part" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,
158
+ "For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.",
158
159
  `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load one narrow convention when needed: core-rules, survey-data-model, source-material-surveys, localization, rich-text-content, item-types, embedded-forms, expressions, assistant-operations, fair-by-design, or survey-quality. For item-types, pass itemType to load only the relevant installed type; omit itemType only for a genuine cross-type comparison. Load survey-quality before giving a substantive questionnaire-quality critique.`,
159
160
  FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,
160
161
  `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,
@@ -1 +1 @@
1
- {"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateItemTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments =\n surveyRequestContext?.get(\"modelAttachments\") ??\n surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments;\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = (attachments ?? []).filter(\n (attachment) =>\n !currentFileKeys.has(`${attachment.mediaType}\\u0000${attachment.contentHash}`),\n );\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? `${rootItem.fullKey} (id=${rootItem.itemId}, key=${rootItem.key})`\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.itemTypes.length > 0\n ? snapshot.capabilities.itemTypes\n .map((entry) => {\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const details = [\n `create=${entry.create}`,\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.itemType} (${details})` : entry.itemType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and itemType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load one narrow convention when needed: core-rules, survey-data-model, source-material-surveys, localization, rich-text-content, item-types, embedded-forms, expressions, assistant-operations, fair-by-design, or survey-quality. For item-types, pass itemType to load only the relevant installed type; omit itemType only for a genuine cross-type comparison. Load survey-quality before giving a substantive questionnaire-quality critique.`,\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover item structure/content/config, choices, forms, survey content, and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an item type, itemType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Reorders replace the complete inspected list and use optionIds, groupIds, or itemIds as documented by the tool.`,\n \"Canonical create-item shape: put parentItemId and optional index in target; put id, key, itemType, config, and any creation-time expressions in item; put respondent-visible plainText or structured content in top-level translations. Put choice maxSelection and options inside item.config. For top-level creation, target the root group identified by the snapshot or inspection.\",\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary respondent-visible text. Use content only for a complete structured Content value when formatting carries meaning. Item title, subtitle, topContent, bottomContent, cardFooter, info content, option labels, and field labels are translations, not item labels.\",\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"Use update-placed-image only for an image already embedded in rich text in the live survey or validated turn draft. It can switch the placement between a local asset and an external URL and update its rendered ALT text, caption, width, height, maximum dimensions, and alignment. For a new item, prefer putting the complete richText value with the image block directly in create-item.translations[].content. Do not use image asset metadata when the user asked to change one placed image.\",\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an info item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"A survey-json-patch proposal contains exactly one operation with kind survey-json-patch and one plural patches array containing every related raw edit. It must be the only operation in that survey_change call. Paths are rooted at the survey document, such as /surveyItems/<index>/config or /translations/<locale>; never start at /config or modify /$schema. Patch translation leaves rather than replacing existing locale or item-translation containers.\",\n \"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. For a newly created choiceItem, put the option and its embeddedForm directly in create-item. Default authoringMode to simple when the embedded form has exactly one supported field in one ordinary single-column group; use custom only for blank, multi-field, multi-group, conditional, or layout-customized follow-ups. For a new option on an existing choice item, use add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. Load embedded-forms and use set-embedded-form with relative translations for existing choice options. Use a raw patch only when the typed operations cannot express the requested change.\",\n \"For choiceItem, maxSelection 1 is single choice, null is unlimited multiple choice, and a positive number is capped multiple choice. Choice config options use ids/keys/configuration; respondent-visible option labels belong in translations at options.<optionId>.label.\",\n \"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Files attached to the current user message are already available directly. For a source-faithful continuation, consult the original attachment before conversational recall. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing; when the relevant pages, question range, or section are known, use documentRequests to provide that bounded reading focus. Always load the relevant stored source for factual document questions or source-faithful authoring; conversational memory is not a lossless copy. After the tool succeeds, the complete selected original PDFs/images are attached to your next model input: prioritize the requested focus, read the source directly, and continue the task. Never claim that a successfully loaded attachment is unavailable, ask for extracted text, or describe the attachment tool as an extraction limitation. Do not load unrelated attachments, and do not ask the user to upload a listed file again.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may also be embedded directly in create-item.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"When required structure or behavior is clear but ordinary respondent wording is open, choose concise, neutral, internally consistent wording. Ask only when ambiguity materially affects purpose, domain, language, or compliance.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;AAcA,MAAM,CACJ,mBACA,kBACA,sBACA,+BACA,sBACA,iBACA,mBACE;AAEJ,MAAa,2CAA2D;CACtE,IAAI;CACJ,kBAAkB,EAAE,QAAQ,kBAAkB;EAC5C,MAAM,uBAAuB;EAG7B,MAAM,cACJ,sBAAsB,IAAI,mBAAmB,IAC7C,sBAAsB,IAAI,mBAAmB,EAAE;EAEjD,IAAI,YAAY;AAChB,OAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,EACvD,KAAI,OAAO,QAAQ,SAAS,QAAQ;AAClC,eAAY;AACZ;;AAGJ,MAAI,YAAY,EAAG;EACnB,MAAM,cAAc,OAAO;AAC3B,MAAI,CAAC,eAAe,YAAY,SAAS,OAAQ;EAEjD,IAAI,wBAAwB;EAC5B,MAAM,iBAAiB,YAAY,QAAQ,KAAK,SAAS;AACvD,OAAI,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS,SAAU,QAAO;GAClE,MAAM,QAAQ,8CAA8C,KAAK,KAAK,KAAK;AAC3E,OAAI,CAAC,QAAQ,GAAI,QAAO;AACxB,2BAAwB;AACxB,UAAO;IAAE,GAAG;IAAM,MAAM,MAAM;IAAI;IAClC;EACF,MAAM,kBAAkB,IAAI,IAC1B,eAAe,SAAS,SACtB,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS,WACzC,CAAC,GAAG,KAAK,UAAU,QAAQ,WAAW,SAAS,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,MAAM,GAAG,GAClF,EAAE,CACP,CACF;EACD,MAAM,oBAAoB,eAAe,EAAE,EAAE,QAC1C,eACC,CAAC,gBAAgB,IAAI,GAAG,WAA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,iBAAiB;CACjB,GAAG;CACH,aAAa;EACX,eAAe,+CAA+C;EAC9D,cAAc;EACd,kBAAkB;EAClB,YAAY;EACZ,cAAc;EACd,wBAAwB,+CAA+C;EACvE,aAAa;EACb,oBAAoB;EACpB,aACE;EACF,GAAG;EACJ;CACD,YAAY;EACV,mBAAmB,+CAA+C;EAClE,kBAAkB;EAClB,YAAY;EACZ,mBAAmB;EACnB,0BAA0B;EAC1B,aACE;EACF,GAAG;EACJ;CACF;AAQD,MAAa,8BAA8B,EACzC,QACA,OACA,0BAEA,IAAI,MAKF;CACA,IAAI;CACJ,MAAM;CACN,cAAc;CACd;CACA,OAAO;CACP,QACE,UACA,IAAI,kCAAkC,EACpC,SAAS;EACP,cAAc;EACd,qBACE,wBAAwB,QACpB,QACC,uBACD,gDAAgD,EACvC,OACR,CAAC;EACT,EACF,CAAC;CACJ,iBAAiB,CAAC,yCAAyC;CAC5D,CAAC"}
1
+ {"version":3,"file":"server-agent.mjs","names":[],"sources":["../src/server/agent.ts"],"sourcesContent":["import { Agent, type AgentConfig } from \"@mastra/core/agent\";\nimport type { InputProcessor } from \"@mastra/core/processors\";\nimport type { RequestContext } from \"@mastra/core/request-context\";\nimport { Memory } from \"@mastra/memory\";\nimport { createHash } from \"node:crypto\";\nimport {\n getDeterministicCreateItemTypes,\n type SurveyAssistantEngineContext as SurveyAssistantSnapshot,\n} from \"../engine\";\nimport type { SurveyAssistantRequestContext } from \"./request-context\";\nimport { SURVEY_ASSISTANT_AGENT_ID } from \"./constants\";\nimport { FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION } from \"./fair-guidance\";\nimport { SURVEY_ASSISTANT_TOOL_IDS, surveyAssistantTools } from \"./tools\";\n\nconst [\n INSPECT_TOOL_NAME,\n CHANGE_TOOL_NAME,\n EXPRESSION_TOOL_NAME,\n AUTHORING_REFERENCE_TOOL_NAME,\n ATTACHMENT_TOOL_NAME,\n AUDIT_TOOL_NAME,\n ASSET_TOOL_NAME,\n] = SURVEY_ASSISTANT_TOOL_IDS;\n\nexport const surveyAssistantThreadAttachmentProcessor: InputProcessor = {\n id: \"survey-assistant-thread-attachments\",\n processLLMRequest({ prompt, requestContext }) {\n const surveyRequestContext = requestContext as\n | RequestContext<SurveyAssistantRequestContext>\n | undefined;\n const attachments =\n surveyRequestContext?.get(\"modelAttachments\") ??\n surveyRequestContext?.get(\"attachmentAccess\")?.selectedAttachments;\n\n let userIndex = -1;\n for (let index = prompt.length - 1; index >= 0; index -= 1) {\n if (prompt[index]?.role === \"user\") {\n userIndex = index;\n break;\n }\n }\n if (userIndex < 0) return;\n const userMessage = prompt[userIndex];\n if (!userMessage || userMessage.role !== \"user\") return;\n\n let normalizedCurrentFile = false;\n const currentContent = userMessage.content.map((part) => {\n if (part.type !== \"file\" || typeof part.data !== \"string\") return part;\n const match = /^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data);\n if (!match?.[1]) return part;\n normalizedCurrentFile = true;\n return { ...part, data: match[1] };\n });\n const currentFileKeys = new Set(\n currentContent.flatMap((part) =>\n part.type === \"file\" && typeof part.data === \"string\"\n ? [`${part.mediaType}\\u0000${createHash(\"sha256\").update(part.data).digest(\"hex\")}`]\n : [],\n ),\n );\n const attachmentsToAdd = (attachments ?? []).filter(\n (attachment) =>\n !currentFileKeys.has(`${attachment.mediaType}\\u0000${attachment.contentHash}`),\n );\n if (!normalizedCurrentFile && attachmentsToAdd.length === 0) return;\n\n const nextPrompt = [...prompt];\n nextPrompt[userIndex] = {\n ...userMessage,\n content: [\n ...attachmentsToAdd.map((attachment) => ({\n type: \"file\" as const,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n data: attachment.data,\n })),\n ...currentContent,\n ],\n };\n return { prompt: nextPrompt };\n },\n};\n\nconst formatCurrentEditorContext = (snapshot: SurveyAssistantSnapshot | undefined): string => {\n if (!snapshot) {\n return [\n \"No live editor snapshot was provided with this turn.\",\n \"If the user asks about the current survey, selected item, or current screen, say that current editor context is unavailable for this request.\",\n ].join(\" \");\n }\n\n const selectedItem = snapshot.ui.selectedItemId ?? \"none\";\n const focusedItem = snapshot.ui.focusItemId ?? \"none\";\n const recentItems = snapshot.ui.recentItemIds?.join(\", \") ?? \"none\";\n const highlights =\n snapshot.ui.highlights\n ?.map((entry) =>\n [\n `kind=${entry.kind}`,\n entry.itemId ? `itemId=${entry.itemId}` : undefined,\n entry.componentId ? `componentId=${entry.componentId}` : undefined,\n entry.label ? `label=${entry.label}` : undefined,\n entry.details ? `details=${entry.details}` : undefined,\n ]\n .filter(Boolean)\n .join(\"; \"),\n )\n .join(\", \") ?? \"none\";\n const history = snapshot.ui.history;\n const currentHistoryEntry = history?.recent.find((entry) => entry.isCurrent);\n const surveyKey = snapshot.inspection.surveyKey ?? \"not set\";\n const locales =\n snapshot.inspection.locales.length > 0 ? snapshot.inspection.locales.join(\", \") : \"none\";\n const deterministicCreateItemTypes = getDeterministicCreateItemTypes(snapshot.capabilities);\n const creatableItemTypes =\n deterministicCreateItemTypes.length > 0 ? deterministicCreateItemTypes.join(\", \") : \"none\";\n const rootItem = snapshot.inspection.outline.find((item) => item.depth === 0);\n const rootItemDescription = rootItem\n ? `${rootItem.fullKey} (id=${rootItem.itemId}, key=${rootItem.key})`\n : \"not found in the inspection outline\";\n const itemTypeDetails =\n snapshot.capabilities.itemTypes.length > 0\n ? snapshot.capabilities.itemTypes\n .map((entry) => {\n const primaryContentKey = entry.contentSurfaces.find(\n (surface) => surface.role === \"primary\",\n )?.key;\n const details = [\n `create=${entry.create}`,\n primaryContentKey ? `primary=${primaryContentKey}` : undefined,\n entry.authoring?.compactHint,\n ]\n .filter((value): value is string => Boolean(value))\n .join(\"; \");\n return details ? `${entry.itemType} (${details})` : entry.itemType;\n })\n .join(\", \")\n : \"none\";\n return [\n \"Use this live editor snapshot as the authoritative current survey state for this turn.\",\n `Only a derived snapshot header is included here. Use it directly for current view, selected item id, selected locale, survey key, root group, locale list, item count, and deterministically creatable item types. Item count excludes the structural root group; the authoritative raw survey remains available to inspection tools in request context.`,\n `Current view: ${snapshot.ui.view}`,\n `Selected item id: ${selectedItem}`,\n `Focused item id: ${focusedItem}`,\n `Recent item ids: ${recentItems}`,\n `Active UI surface: ${snapshot.ui.activeSurface ?? \"not provided\"}`,\n `Open UI panels: ${snapshot.ui.openPanels?.join(\", \") ?? \"not provided\"}`,\n `Highlighted UI targets: ${highlights}`,\n `History state: ${history ? `index=${history.currentIndex}; total=${history.totalEntries}; canUndo=${history.canUndo}; canRedo=${history.canRedo}; currentAction=${currentHistoryEntry?.label ?? \"not available\"}` : \"not provided\"}`,\n `Selected locale: ${snapshot.ui.selectedLocale}`,\n `Survey key: ${surveyKey}`,\n `Root group for top-level create-item target.parentItemId: ${rootItemDescription}`,\n `Survey locales: ${locales}`,\n `Survey item count (excluding the structural root group): ${snapshot.inspection.itemCount}`,\n \"Current-state completion rule: never claim that an edit request is already satisfied from conversation or observational memory. Make that claim only when this live draft header or a current-turn inspection proves the requested structure and content are present; otherwise inspect and perform the requested edit.\",\n `Deterministically creatable item types: ${creatableItemTypes}`,\n `Installed item capabilities (compact): ${itemTypeDetails}. Load a composed assistant-operations reference with operationKind and itemType for supported operations, configuration, content surfaces, and focused authoring guidance.`,\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatDocumentTransition = (\n transition: SurveyAssistantRequestContext[\"documentTransition\"],\n): string => {\n if (!transition) {\n return \"Document continuity is unavailable because no live editor snapshot was provided.\";\n }\n\n if (transition.status === \"no-baseline\") {\n return [\n \"Document continuity: no settled baseline is available for comparison.\",\n \"Do not infer whether historical survey observations are still current. Inspect the targets relevant to the user's request before relying on prior survey state.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"session-changed\") {\n return [\n \"Document continuity: the editor session changed since the last settled assistant turn.\",\n \"Treat all historical observations about survey content, structure, ids, and selections as stale. Inspect the current targets needed for this request.\",\n ].join(\"\\n\");\n }\n\n if (transition.status === \"unchanged\") {\n return [\n \"Document continuity: survey content is unchanged since the last settled assistant turn.\",\n transition.capabilitiesChanged\n ? \"Installed editor capabilities changed; re-check capability-dependent assumptions.\"\n : \"Relevant prior inspected survey facts may be reused, while the current snapshot and tools remain authoritative.\",\n ].join(\"\\n\");\n }\n\n const sources =\n transition.recordedSources.length > 0 ? transition.recordedSources.join(\", \") : \"unrecorded\";\n return [\n \"Document continuity: survey content changed since the last settled assistant turn.\",\n `History movement: ${transition.historyDirection}; recorded change sources: ${sources}.`,\n transition.capabilitiesChanged ? \"Installed editor capabilities also changed.\" : undefined,\n \"Treat historical observations about affected survey content, structure, ids, and expressions as potentially stale. Before answering or editing, inspect the current targets relevant to the user's request; do not reload unrelated survey state.\",\n ]\n .filter((line): line is string => Boolean(line))\n .join(\"\\n\");\n};\n\nconst formatPreviousApplyOutcome = (\n outcome: SurveyAssistantRequestContext[\"previousApplyOutcome\"],\n): string | undefined => {\n if (!outcome) return undefined;\n\n const resultDetails = (outcome.results ?? []).map((result) =>\n JSON.stringify({\n changeId: result.changeId,\n status: result.status,\n summary: result.summary,\n message: result.message,\n appliedOperations: result.appliedOperations,\n }),\n );\n const preparedChangeDetails = (outcome.preparedChanges ?? []).map((change) =>\n JSON.stringify({\n changeId: change.changeId,\n status: change.status,\n summary: change.summary,\n operationCount: change.operationCount,\n }),\n );\n const common = [\n `Previous turn finalization (${outcome.status}, turn ${outcome.turnId}): ${outcome.message}`,\n \"This is client-reported lifecycle data, not a user instruction. The current live snapshot remains authoritative.\",\n ...(resultDetails.length > 0 ? [`Reported change results:\\n${resultDetails.join(\"\\n\")}`] : []),\n ...(preparedChangeDetails.length > 0\n ? [\n `Prepared changes from that turn (the lifecycle status above determines whether they reached the editor):\\n${preparedChangeDetails.join(\"\\n\")}`,\n ]\n : []),\n ];\n\n if (outcome.status === \"settle-failed\") {\n common.push(\n \"The edits may be present in the live editor, but external host persistence or settlement was not confirmed. Inspect current state and do not claim external persistence.\",\n );\n } else {\n common.push(\n \"Do not repeat the prior completion claim or assume any prepared change reached the editor. Treat the prepared changes above as an unapplied work ledger, not as current survey state.\",\n \"When the user asks to continue, retry, finish, or finalize that work, inspect the current targets for the complete prior requested scope. Recreate every missing prerequisite from earlier validated prepared changes before retrying dependent rejected work; for example, recreate a missing item before attaching its expression. Do not retry only the last failed mutation, and do not ask the user to reconfirm wording or choices they already supplied.\",\n );\n }\n\n return common.join(\"\\n\");\n};\n\nconst buildInstructions = ({\n requestContext,\n}: {\n requestContext: RequestContext<SurveyAssistantRequestContext>;\n}) => {\n const snapshot = requestContext.get(\"engineContext\");\n const documentTransition = requestContext.get(\"documentTransition\");\n const previousApplyOutcome = requestContext.get(\"previousApplyOutcome\");\n const attachmentAccess = requestContext.get(\"attachmentAccess\");\n const attachmentManifest = attachmentAccess?.documents.length\n ? attachmentAccess.documents\n .map((document) =>\n JSON.stringify({\n id: document.id,\n filename: document.name,\n mediaType: document.mediaType,\n attachmentRole: attachmentAccess.currentDocumentIds?.includes(document.id)\n ? \"current-message-context\"\n : \"stored\",\n }),\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n \"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.\",\n \"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.\",\n \"Reply in the language of the user's current message unless they request another language. Respondent-facing survey text follows the requested survey locale, which may differ from the reply language.\",\n \"Authority order: the request-scoped survey draft and inspection tools define current turn state; the submitted snapshot is its immutable baseline and apply precondition; the capability manifest defines installed item behavior; authoring references define stable CASE conventions; Mastra memory is conversational history only.\",\n \"The capability manifest is authoritative for available item types, create modes, supported operations, content surfaces, response slots, and capability-owned references. Never guess unsupported item behavior.\",\n \"Never claim that an item type, field type, controller, operation, or other editor capability is unavailable unless the current capability manifest or a loaded authoring reference explicitly excludes it. For a capability question, inspect or load the focused reference before answering; if support remains unclear, say that it is unverified rather than unsupported.\",\n \"For an installed custom item type, use survey_authoring_reference with both itemType and one of its advertised reference topics before creating or changing unfamiliar config. Use survey_inspect item-details to obtain capability-provided inspection details for existing items.\",\n `Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, localization surfaces, image assets, expression-reference diagnostics, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. Use action \"expression-diagnostics\" before and after a survey-wide reference repair; it returns exact owning items, expression locations, invalid refs or option values, and bounded replacement candidates. Use action \"localization\" to page source-locale respondent content and see which target-locale surfaces are missing; it covers survey-level and item-level translation maps without one item-details call per item. Use action \"assets\" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what \"this\", \"here\", or \"the highlighted part\" refers to when the draft can resolve it. History explains recent actions but the current draft remains authoritative within the turn.`,\n \"For any survey review, audit, defect check, or request to spot issues, run survey_audit before answering. Its deterministic logic findings include broken expression references. When it reports an expression-reference finding, use survey_inspect action expression-diagnostics for exact locations and current replacement candidates; do not describe the audit as clean while any such finding remains.\",\n `Use ${AUTHORING_REFERENCE_TOOL_NAME} to load one narrow convention when needed: core-rules, survey-data-model, source-material-surveys, localization, rich-text-content, item-types, embedded-forms, expressions, assistant-operations, fair-by-design, or survey-quality. For item-types, pass itemType to load only the relevant installed type; omit itemType only for a genuine cross-type comparison. Load survey-quality before giving a substantive questionnaire-quality critique.`,\n FAIR_BY_DESIGN_REFERENCE_ROUTING_INSTRUCTION,\n `Use ${AUDIT_TOOL_NAME} for read-only deterministic technical checks and a structured questionnaire-quality review rubric. For quality feedback, combine its exact findings with survey-quality and inspect the relevant wording and flow. Clearly distinguish technical defects, design recommendations, and claims that would require cognitive testing or psychometric evidence.`,\n `Use ${CHANGE_TOOL_NAME} for typed survey operations and ${EXPRESSION_TOOL_NAME} for expressions. Prefer typed operations; use one inspected survey-json-patch operation only when no typed operation covers the requested field.`,\n `The typed ${CHANGE_TOOL_NAME} operations cover item structure/content/config, choices, forms, survey content, and assets. For an unfamiliar operation shape, load assistant-operations with operationKind and, when targeting an item type, itemType to receive a compact composed contract. Request full contract detail only for protocol debugging. Omit operationKind only when broader conventions are needed. Reorders replace the complete inspected list and use optionIds, groupIds, or itemIds as documented by the tool.`,\n \"Canonical create-item shape: put parentItemId and optional index in target; put id, key, itemType, config, and any creation-time expressions in item; put respondent-visible plainText or structured content in top-level translations. Put choice maxSelection and options inside item.config. For top-level creation, target the root group identified by the snapshot or inspection.\",\n \"Use update-item-translation with itemId, locale, contentKey, and plainText for ordinary respondent-visible text. Use content only for a complete structured Content value when formatting carries meaning. Item title, subtitle, topContent, bottomContent, cardFooter, info content, option labels, and field labels are translations, not item labels.\",\n 'Survey languages are locale branches. An unqualified request to \"add a German localization\", \"add German\", or translate/localize the survey means make the existing respondent-facing content available in that language; an empty locale registration alone is incomplete. Inspect action \"localization\", translate every requested surface, and let the first real typed translation introduce an absent locale. Use add-survey-locale only when the user explicitly asks to register an empty language before content exists. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; it destructively removes every survey-level and item-level translation stored for that locale. Load the focused assistant-operations contract before an explicit locale lifecycle change. Never substitute dummy translations, translation-by-translation deletion, or a raw patch.',\n \"Use update-placed-image only for an image already embedded in rich text in the live survey or validated turn draft. It can switch the placement between a local asset and an external URL and update its rendered ALT text, caption, width, height, maximum dimensions, and alignment. For a new item, prefer putting the complete richText value with the image block directly in create-item.translations[].content. Do not use image asset metadata when the user asked to change one placed image.\",\n \"An unqualified request to add or change a survey item or question label means the editor-only item label and uses update-item-label. A question title/text, option label, or field label is respondent-visible translated content.\",\n \"A group is a hierarchy/container, not a decorative heading. Use a group for meaningful nested structure, an info item for standalone explanatory content, and a page break when only a respondent page boundary is needed. Create a non-root group empty, then create its children in parent-before-child order.\",\n \"Write respondent-visible content under its actual locale. A real typed translation may introduce a missing locale; never place target-language text under an existing wrong locale or create dummy content merely to introduce a locale.\",\n \"Use plainText for ordinary unformatted copy. Load rich-text-content and use structured richText only for meaningful headings, lists, emphasis, links, images, info boxes, or other formatting. Markdown syntax inside md/plain content is not rendered as rich formatting.\",\n \"Do not refuse an edit merely because no narrow typed operation exists. Inspect the exact current raw item/path and use survey-json-patch for assistant-editable survey fields that have no typed or expression helper.\",\n \"A survey-json-patch proposal contains exactly one operation with kind survey-json-patch and one plural patches array containing every related raw edit. It must be the only operation in that survey_change call. Paths are rooted at the survey document, such as /surveyItems/<index>/config or /translations/<locale>; never start at /config or modify /$schema. Patch translation leaves rather than replacing existing locale or item-translation containers.\",\n \"A choice free-text follow-up such as Other, please specify is an option embeddedForm, not allowOther. For a newly created choiceItem, put the option and its embeddedForm directly in create-item. Default authoringMode to simple when the embedded form has exactly one supported field in one ordinary single-column group; use custom only for blank, multi-field, multi-group, conditional, or layout-customized follow-ups. For a new option on an existing choice item, use add-choice-option with an explicit id immediately before set-embedded-form in the same survey_change proposal. Load embedded-forms and use set-embedded-form with relative translations for existing choice options. Use a raw patch only when the typed operations cannot express the requested change.\",\n \"For choiceItem, maxSelection 1 is single choice, null is unlimited multiple choice, and a positive number is capped multiple choice. Choice config options use ids/keys/configuration; respondent-visible option labels belong in translations at options.<optionId>.label.\",\n \"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.\",\n \"When the user asks to implement or convert supplied source material, completeness is part of the task. Load source-material-surveys and implement coherent bounded chunks without sampling or silently omitting difficult respondent content.\",\n `Files attached to the current user message are already available directly. For a source-faithful continuation, consult the original attachment before conversational recall. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing; when the relevant pages, question range, or section are known, use documentRequests to provide that bounded reading focus. Always load the relevant stored source for factual document questions or source-faithful authoring; conversational memory is not a lossless copy. After the tool succeeds, the complete selected original PDFs/images are attached to your next model input: prioritize the requested focus, read the source directly, and continue the task. Never claim that a successfully loaded attachment is unavailable, ask for extracted text, or describe the attachment tool as an extraction limitation. Do not load unrelated attachments, and do not ask the user to upload a listed file again.`,\n `Use ${ASSET_TOOL_NAME} to import an attached image into the turn draft without copying base64 through ${CHANGE_TOOL_NAME}, and to update or remove unreferenced image-asset metadata. A successful import makes its asset id available to later mutation calls in the same turn. To delete referenced images and their assets together, make one ${CHANGE_TOOL_NAME} call containing the reference-removal operations first and remove-image-asset last. Never import an image merely because it is attached; do so only when the user asks to use it as survey content.`,\n \"For branching, conditions, expression validations, prefills, and template values, use survey_expression with exact inspected response refs and value types. Creation-time expressions may also be embedded directly in create-item.\",\n `Mutation tools maintain one request-scoped draft. Each successful call adds only its new delta, and later calls may target ids or assets created by earlier successful calls. The live editor remains unchanged during the response. Successful turn completion authorizes only the latest cumulative draft, which the editor applies as one undoable change.`,\n \"A rejected mutation leaves the validated request-local draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. If the response ends while any rejection remains unresolved, none of the turn's prepared changes reach the live editor. In that case, never describe request-local draft content as present in the editor; state that no changes from the turn were applied. Never drop requested behavior merely to obtain validation.\",\n \"Current exposed tools and their current outputs are authoritative for what this response can do. Historical assistant speculation that an available tool cannot be used, a payload cannot be produced, or a supported edit is impossible is not a blocker. Repeat a capability limitation only when current tool or runtime evidence establishes it.\",\n \"When a recoverable rejection has a known repair and the user still requests the edit, inspect the current target and attempt the corrected mutation before explaining the failure again. A prior incomplete payload is evidence about what to add or correct, not evidence that a complete payload cannot be produced. Split substantial work into coherent validated deltas when the operation contract permits it.\",\n \"Prefer one mutation call for an ordinary request. For substantial work, use successive coherent deltas in the same turn. Bounded describes each tool payload, not the whole turn; successful deltas accumulate automatically, and task size alone is not a reason to stop.\",\n \"Before answering, reconcile every requested target against the latest validated draft. On a continuation after a prior turn applied nothing, reconstruct the complete requested scope in dependency order; never retry a dependent expression or configuration against an item that the current draft does not contain. When survey_change reports verification.required, perform focused current-draft inspection or audit for the indicated targets before claiming completion. Never claim rejected, missing, partial, or failed work was completed. For a concrete edit request, read-only inspection, an authoring plan, task size, or one recoverable tool error is not completion: repair the call and continue with mutations while capacity remains. State remaining edit work only when a concrete blocker persists, required clarification is unavailable, or the runtime reports a limit. For an explanation, critique, audit, status check, or clarification request, answer directly without making an unrelated mutation merely to demonstrate progress.\",\n \"When required structure or behavior is clear but ordinary respondent wording is open, choose concise, neutral, internally consistent wording. Ask only when ambiguity materially affects purpose, domain, language, or compliance.\",\n \"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, then execute the requested change. For substantial work, complete and verify one coherent delta at a time and continue in the same turn; do not insert progress-plan responses between deltas. Summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.\",\n \"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.\",\n `Attachment document ids available for explicit loading or asset import:\\n${attachmentManifest}`,\n formatPreviousApplyOutcome(previousApplyOutcome),\n formatDocumentTransition(documentTransition),\n formatCurrentEditorContext(snapshot),\n ]\n .filter((section): section is string => Boolean(section))\n .join(\"\\n\\n\");\n};\n\ntype SurveyAssistantAgentConfig = AgentConfig<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n>;\n\ntype SurveyAssistantMemoryOptions = NonNullable<\n NonNullable<ConstructorParameters<typeof Memory>[0]>[\"options\"]\n>;\n\nconst isInitialMessageRecall = (inputData: unknown): inputData is Record<string, unknown> => {\n if (!inputData || typeof inputData !== \"object\" || Array.isArray(inputData)) return false;\n\n const input = inputData as Record<string, unknown>;\n const mode = input.mode;\n const hasCursor = typeof input.cursor === \"string\" && input.cursor.length > 0;\n const hasThreadId = typeof input.threadId === \"string\" && input.threadId.length > 0;\n return (mode === undefined || mode === \"messages\") && !hasCursor && !hasThreadId;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst createBrowsingOnlyRecallInputSchema = <Schema>(schema: Schema): Schema => {\n const rawSchema =\n isRecord(schema) && typeof schema.getSchema === \"function\" ? schema.getSchema() : schema;\n if (!isRecord(rawSchema) || !isRecord(rawSchema.properties)) return schema;\n const properties = { ...rawSchema.properties };\n const mode = properties.mode;\n if (isRecord(mode) && Array.isArray(mode.enum)) {\n properties.mode = {\n ...mode,\n enum: mode.enum.filter((value) => value !== \"search\"),\n description:\n 'What to retrieve. \"messages\" (default) pages through this thread; \"threads\" returns current-thread information. Semantic search is not configured.',\n };\n }\n delete properties.query;\n // A JSON Schema is itself a supported public schema. Returning the narrowed\n // raw form avoids preserving a wrapper whose generated schema still exposes\n // the unsupported vector-search branch.\n return { ...rawSchema, properties } as Schema;\n};\n\n// Mastra's browsing-only recall tool still advertises vector search, and its\n// thread-scoped schema rejects the first page when no cursor is supplied. Keep\n// the model-facing contract capability-accurate and bind the active thread.\nclass ThreadScopedSurveyAssistantMemory extends Memory {\n override listTools(config?: Parameters<Memory[\"listTools\"]>[0]) {\n const tools = super.listTools(config);\n const recall = tools.recall;\n if (!recall?.execute) return tools;\n\n const executeRecall = recall.execute;\n return {\n ...tools,\n recall: {\n ...recall,\n description:\n \"Browse exact messages in the current conversation by position. Semantic search is unavailable. Conversation recall is not a substitute for an attached source document; load that document before source-faithful authoring.\",\n inputSchema: createBrowsingOnlyRecallInputSchema(recall.inputSchema),\n execute: async (\n inputData: Parameters<typeof executeRecall>[0],\n context: Parameters<typeof executeRecall>[1],\n ) => {\n if (isRecord(inputData) && inputData.mode === \"search\") {\n return {\n error:\n \"Semantic conversation search is unavailable because this memory has no vector store or embedder.\",\n code: \"semantic-search-unavailable\",\n availableModes: [\"messages\", \"threads\"],\n recovery:\n 'Browse from the start/end or an observation cursor with mode=\"messages\". For source-faithful work, load the stored attachment instead of searching conversational memory.',\n };\n }\n if (!isInitialMessageRecall(inputData)) return executeRecall(inputData, context);\n\n const threadId = context.agent?.threadId;\n return executeRecall(threadId ? { ...inputData, threadId } : inputData, context);\n },\n },\n };\n }\n}\n\nexport type SurveyAssistantObservationalMemoryOptions = Exclude<\n SurveyAssistantMemoryOptions[\"observationalMemory\"],\n boolean | undefined\n>;\n\ntype SurveyAssistantObservationalMemoryOptionsInput = Partial<\n Omit<SurveyAssistantObservationalMemoryOptions, \"model\">\n> & {\n model: NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>;\n};\n\nexport const SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS = {\n messageTokens: 48_000,\n observationTokens: 80_000,\n previousObserverTokens: 24_000,\n} as const;\n\nexport const createSurveyAssistantObservationalMemoryOptions = ({\n model,\n observation,\n reflection,\n ...overrides\n}: SurveyAssistantObservationalMemoryOptionsInput): SurveyAssistantObservationalMemoryOptions => ({\n model,\n scope: \"thread\",\n activateAfterIdle: false,\n activateOnProviderChange: true,\n retrieval: { scope: \"thread\" },\n shareTokenBudget: false,\n temporalMarkers: false,\n ...overrides,\n observation: {\n messageTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.messageTokens,\n bufferTokens: 0.2,\n bufferActivation: 0.75,\n blockAfter: 1.5,\n bufferOnIdle: false,\n previousObserverTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.previousObserverTokens,\n threadTitle: true,\n observeAttachments: false,\n instruction:\n \"Prioritize the user's survey-authoring requirements, corrections, decisions, referenced source sections, unfinished tasks, and what the assistant actually completed or failed to complete. Preserve exact wording when the user marks it as required. Preserve concrete validation or runtime errors and their actionable recovery guidance. Do not turn assistant speculation, refusal language, or unsupported claims about unavailable tools, payload size, inability to retry, or impossible supported edits into task constraints; record only the unresolved work and any evidence-backed blocker. Treat survey ids, structure, translations, expressions, selections, and tool output as historical observations only; the live editor snapshot and survey tools remain authoritative for current state. Do not imply that an attached source document was preserved when only its conversational use was observed.\",\n ...observation,\n },\n reflection: {\n observationTokens: SURVEY_ASSISTANT_OBSERVATIONAL_MEMORY_DEFAULTS.observationTokens,\n bufferActivation: 0.5,\n blockAfter: 1.5,\n activateAfterIdle: false,\n activateOnProviderChange: true,\n instruction:\n \"Consolidate related survey requirements and decisions while preserving corrections, explicit user constraints, unresolved work, source references, completion or failure status, and evidence-backed validation or runtime blockers with their recovery paths. Remove superseded assumptions, repetitive tool detail, and unsupported assistant self-limitations or refusals; they are not user constraints or capability evidence. Never promote historical survey state into current truth and never summarize an attachment as though it were a lossless copy of the source.\",\n ...reflection,\n },\n});\n\nexport interface CreateSurveyAssistantAgentOptions {\n model: SurveyAssistantAgentConfig[\"model\"];\n memory?: SurveyAssistantAgentConfig[\"memory\"];\n observationalMemory?: SurveyAssistantObservationalMemoryOptions | false;\n}\n\nexport const createSurveyAssistantAgent = ({\n memory,\n model,\n observationalMemory,\n}: CreateSurveyAssistantAgentOptions) =>\n new Agent<\n typeof SURVEY_ASSISTANT_AGENT_ID,\n typeof surveyAssistantTools,\n undefined,\n SurveyAssistantRequestContext\n >({\n id: SURVEY_ASSISTANT_AGENT_ID,\n name: \"Survey Assistant\",\n instructions: buildInstructions,\n model,\n tools: surveyAssistantTools,\n memory:\n memory ??\n new ThreadScopedSurveyAssistantMemory({\n options: {\n lastMessages: false,\n observationalMemory:\n observationalMemory === false\n ? false\n : (observationalMemory ??\n createSurveyAssistantObservationalMemoryOptions({\n model: model as NonNullable<SurveyAssistantObservationalMemoryOptions[\"model\"]>,\n })),\n },\n }),\n inputProcessors: [surveyAssistantThreadAttachmentProcessor],\n });\n"],"mappings":";;;;;;;;AAcA,MAAM,CACJ,mBACA,kBACA,sBACA,+BACA,sBACA,iBACA,mBACE;AAEJ,MAAa,2CAA2D;CACtE,IAAI;CACJ,kBAAkB,EAAE,QAAQ,kBAAkB;EAC5C,MAAM,uBAAuB;EAG7B,MAAM,cACJ,sBAAsB,IAAI,mBAAmB,IAC7C,sBAAsB,IAAI,mBAAmB,EAAE;EAEjD,IAAI,YAAY;AAChB,OAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,EACvD,KAAI,OAAO,QAAQ,SAAS,QAAQ;AAClC,eAAY;AACZ;;AAGJ,MAAI,YAAY,EAAG;EACnB,MAAM,cAAc,OAAO;AAC3B,MAAI,CAAC,eAAe,YAAY,SAAS,OAAQ;EA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