@case-framework/survey-assistant 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{capabilities-DZ0a_o2y.mjs → capabilities-DKbNCnBf.mjs} +2 -2
- package/dist/{capabilities-DZ0a_o2y.mjs.map → capabilities-DKbNCnBf.mjs.map} +1 -1
- package/dist/capabilities-default.d.mts +1 -1
- package/dist/capabilities-default.mjs +1 -1
- package/dist/{constants-56jf_4ls.d.mts → constants-CgV4cTg5.d.mts} +7 -7
- package/dist/constants-CgV4cTg5.d.mts.map +1 -0
- package/dist/{controller-proxy-ClsY4lFI.mjs → controller-proxy-0WJZUZYx.mjs} +2 -2
- package/dist/{controller-proxy-ClsY4lFI.mjs.map → controller-proxy-0WJZUZYx.mjs.map} +1 -1
- package/dist/{controller-proxy-2VH0b_5E.d.mts → controller-proxy-BzpEOygv.d.mts} +2 -2
- package/dist/{controller-proxy-2VH0b_5E.d.mts.map → controller-proxy-BzpEOygv.d.mts.map} +1 -1
- package/dist/{engine-DQrCO_ur.mjs → engine-0AJrv0hI.mjs} +543 -76
- package/dist/engine-0AJrv0hI.mjs.map +1 -0
- package/dist/engine.d.mts +2 -2
- package/dist/engine.mjs +3 -3
- package/dist/{index-C_x686M7.d.mts → index-BNdvGEaq.d.mts} +3 -3
- package/dist/{index-C_x686M7.d.mts.map → index-BNdvGEaq.d.mts.map} +1 -1
- package/dist/{index-B_x2IYi7.d.mts → index-BUF-sE8j.d.mts} +1 -10
- package/dist/index-BUF-sE8j.d.mts.map +1 -0
- package/dist/{index-DZ6KBwVR.d.mts → index-BdXb6jER.d.mts} +45 -14
- package/dist/index-BdXb6jER.d.mts.map +1 -0
- package/dist/{index-DVxVyhAu.d.mts → index-BiTT71Xp.d.mts} +1 -9
- package/dist/{index-DVxVyhAu.d.mts.map → index-BiTT71Xp.d.mts.map} +1 -1
- package/dist/{memory-thread-repository-Cm1BJyRw.mjs → memory-thread-repository-1ocPOda8.mjs} +17 -17
- package/dist/memory-thread-repository-1ocPOda8.mjs.map +1 -0
- package/dist/{protocol-7EEgcYja.mjs → protocol-DpCYmCjr.mjs} +1 -8
- package/dist/{protocol-7EEgcYja.mjs.map → protocol-DpCYmCjr.mjs.map} +1 -1
- package/dist/protocol.d.mts +1 -1
- package/dist/protocol.mjs +1 -1
- package/dist/{react-B_5smfiK.mjs → react-DXK5zWNo.mjs} +3 -3
- package/dist/{react-B_5smfiK.mjs.map → react-DXK5zWNo.mjs.map} +1 -1
- package/dist/react-integration.d.mts +1 -1
- package/dist/react-integration.mjs +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.mjs +2 -2
- package/dist/references/assistant-operations.md +9 -14
- package/dist/references/localization.md +2 -0
- package/dist/references/source-material-surveys.md +1 -1
- package/dist/{request-context-BDBw4-Gw.mjs → request-context-BBzU3VdG.mjs} +17 -10
- package/dist/request-context-BBzU3VdG.mjs.map +1 -0
- package/dist/server-agent.d.mts +2 -10
- package/dist/server-agent.mjs +13 -13
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +4 -4
- package/dist/server-runtime.mjs +2 -2
- package/dist/server-tasks.d.mts +1 -1
- package/dist/server-tasks.mjs +1 -1
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +6 -6
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +2 -2
- package/dist/{tasks-COQnhSeT.d.mts → tasks-BuLnWrR4.d.mts} +3 -3
- package/dist/{tasks-COQnhSeT.d.mts.map → tasks-BuLnWrR4.d.mts.map} +1 -1
- package/dist/thread-documents-BlxNjc7S.d.mts.map +1 -1
- package/dist/{thread-handlers-l79JBl5m.d.mts → thread-handlers-6L8sAreR.d.mts} +3 -3
- package/dist/{thread-handlers-l79JBl5m.d.mts.map → thread-handlers-6L8sAreR.d.mts.map} +1 -1
- package/dist/{tools-DDXaJ8Za.mjs → tools-wgLen05n.mjs} +97 -103
- package/dist/tools-wgLen05n.mjs.map +1 -0
- package/dist/ui.css +1 -1
- package/dist/ui.d.mts +3 -3
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +36 -6
- package/dist/ui.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/constants-56jf_4ls.d.mts.map +0 -1
- package/dist/engine-DQrCO_ur.mjs.map +0 -1
- package/dist/index-B_x2IYi7.d.mts.map +0 -1
- package/dist/index-DZ6KBwVR.d.mts.map +0 -1
- package/dist/memory-thread-repository-Cm1BJyRw.mjs.map +0 -1
- package/dist/request-context-BDBw4-Gw.mjs.map +0 -1
- package/dist/tools-DDXaJ8Za.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-B_5smfiK.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: \"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 !== \"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\";\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\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 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 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 read(threadId: 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 read(threadId) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, { 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 type {\n ApplyReceipt,\n SurveyApplyResult,\n SurveyAssistantApplyPolicy,\n SurveyAssistantTurnFinal,\n 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\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\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 /** 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 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 [state, dispatch] = useReducer(reduceSurveyAssistantSessionState, \"idle\");\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\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 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\n if (turnAuthorization.status !== \"completed\" || turnAuthorization.changeSets.length === 0) {\n dispatch({ type: \"completed\" });\n return;\n }\n if (applyPolicy === \"deny\") {\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 reportAuthorizationError(\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 );\n return;\n }\n if (!approved) {\n dispatch({ type: \"completed\" });\n return;\n }\n }\n\n if (!controller?.applyAssistantChange && !controller?.applyAssistantChanges) {\n reportAuthorizationError(\"No survey editor apply adapter is available.\");\n return;\n }\n const beforeSnapshot = controller.getSnapshot();\n if (!beforeSnapshot) {\n reportAuthorizationError(\n \"The editor state was unavailable when applying the assistant change.\",\n );\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 dispatch({ type: \"completed\" });\n return;\n }\n try {\n await onSettleApply?.({\n changeSets: turnAuthorization.changeSets,\n receipts,\n turnFinal,\n });\n dispatch({ type: \"applied\" });\n } catch {\n reportAuthorizationError(\n \"The assistant changes were applied locally but could not be settled by the host.\",\n );\n }\n })();\n }, [\n applyPolicy,\n controller,\n isStreaming,\n onApplyReceipts,\n onReviewChangeSets,\n onSettleApply,\n reportAuthorizationError,\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 ({ files, text: rawText, uiContext }: 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\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 ...(modelId ? { modelId } : {}),\n },\n });\n return true;\n },\n [\n authorizationError,\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 ...(modelId ? { modelId } : {}),\n },\n });\n }, [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 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;AAChC,SAAQ,MAAM,MAAd;EACE,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C,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;EACD"}
|
|
1
|
+
{"version":3,"file":"react-DXK5zWNo.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: \"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 !== \"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\";\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\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 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 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 read(threadId: 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 read(threadId) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, { 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 type {\n ApplyReceipt,\n SurveyApplyResult,\n SurveyAssistantApplyPolicy,\n SurveyAssistantTurnFinal,\n 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\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\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 /** 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 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 [state, dispatch] = useReducer(reduceSurveyAssistantSessionState, \"idle\");\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\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 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\n if (turnAuthorization.status !== \"completed\" || turnAuthorization.changeSets.length === 0) {\n dispatch({ type: \"completed\" });\n return;\n }\n if (applyPolicy === \"deny\") {\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 reportAuthorizationError(\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 );\n return;\n }\n if (!approved) {\n dispatch({ type: \"completed\" });\n return;\n }\n }\n\n if (!controller?.applyAssistantChange && !controller?.applyAssistantChanges) {\n reportAuthorizationError(\"No survey editor apply adapter is available.\");\n return;\n }\n const beforeSnapshot = controller.getSnapshot();\n if (!beforeSnapshot) {\n reportAuthorizationError(\n \"The editor state was unavailable when applying the assistant change.\",\n );\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 dispatch({ type: \"completed\" });\n return;\n }\n try {\n await onSettleApply?.({\n changeSets: turnAuthorization.changeSets,\n receipts,\n turnFinal,\n });\n dispatch({ type: \"applied\" });\n } catch {\n reportAuthorizationError(\n \"The assistant changes were applied locally but could not be settled by the host.\",\n );\n }\n })();\n }, [\n applyPolicy,\n controller,\n isStreaming,\n onApplyReceipts,\n onReviewChangeSets,\n onSettleApply,\n reportAuthorizationError,\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 ({ files, text: rawText, uiContext }: 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\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 ...(modelId ? { modelId } : {}),\n },\n });\n return true;\n },\n [\n authorizationError,\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 ...(modelId ? { modelId } : {}),\n },\n });\n }, [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 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;AAChC,SAAQ,MAAM,MAAd;EACE,KAAK,SACH,QAAO;EACT,KAAK,iBACH,QAAO;EACT,KAAK,YACH,QAAO;EACT,KAAK,gBACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK,QACH,QAAO,MAAM,gBAAgB,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GAAY,CAK/B;EACZ;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-
|
|
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-BzpEOygv.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-
|
|
2
|
+
import { i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-0WJZUZYx.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-
|
|
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-
|
|
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-BNdvGEaq.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-BzpEOygv.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-
|
|
3
|
-
import { c as SurveyAssistantClientError, i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-
|
|
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-DXK5zWNo.mjs";
|
|
3
|
+
import { c as SurveyAssistantClientError, i as createSurveyAssistantTaskExecutor, n as createSurveyAssistantControllerProxy, r as createSurveyAssistantTaskClient, s as createSurveyAssistantThreadLauncher, t as createSurveyAssistantControllerBridge } from "./controller-proxy-0WJZUZYx.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,14 +1,9 @@
|
|
|
1
1
|
# Assistant Operations
|
|
2
2
|
|
|
3
|
-
Use `survey_change` for
|
|
4
|
-
`action: "prepare"` for expression mutations
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
candidate ids for browser apply.
|
|
8
|
-
|
|
9
|
-
Expressions for items created in the current turn are the deliberate exception: embed them in the
|
|
10
|
-
new item's raw structure inside the same `survey_change` proposal. A later tool call cannot inspect
|
|
11
|
-
an item that has not been applied yet.
|
|
3
|
+
Use `survey_change` for typed survey mutations and `survey_expression` with
|
|
4
|
+
`action: "prepare"` for expression mutations. Both tools submit deltas to one
|
|
5
|
+
request-scoped draft. Only successful completion of the whole turn authorizes
|
|
6
|
+
the latest cumulative change set for browser apply.
|
|
12
7
|
|
|
13
8
|
## Common Workflow
|
|
14
9
|
|
|
@@ -16,12 +11,12 @@ an item that has not been applied yet.
|
|
|
16
11
|
2. Use `survey_inspect` for revision, selected item, root group, locale, available item types, response slots, item details, or focused raw JSON.
|
|
17
12
|
3. For existing items, inspect item details or exact raw paths before editing.
|
|
18
13
|
For image assets, use `survey_inspect` with `action: "assets"`; it returns each explicit `assetId`, metadata, and usage locations without embedded bytes.
|
|
19
|
-
4. Prefer typed `survey_change` operations for
|
|
14
|
+
4. Prefer typed `survey_change` operations for supported edits.
|
|
20
15
|
5. Use `survey_expression` for expression mutations on existing state.
|
|
21
16
|
6. Use `survey-json-patch` through `survey_change` only for assistant-editable fields not covered by
|
|
22
17
|
typed or expression operations.
|
|
23
|
-
7.
|
|
24
|
-
8.
|
|
18
|
+
7. Mutation calls submit deltas to one request-scoped draft. Each successful call automatically accumulates with earlier successful calls, and later calls may target ids or assets introduced by the draft.
|
|
19
|
+
8. A rejected delta leaves the validated draft unchanged and blocks turn authorization. Correct the same target in another mutation call; an unrelated valid edit does not clear the block. Successful turn completion authorizes only the latest cumulative draft for one editor apply.
|
|
25
20
|
|
|
26
21
|
## `survey_change` Typed Operations
|
|
27
22
|
|
|
@@ -36,7 +31,7 @@ operation catalog.
|
|
|
36
31
|
- Use root group id/key for top-level items.
|
|
37
32
|
- Put visible text in top-level `translations`, not inside `item`.
|
|
38
33
|
- Each translation accepts either `plainText` or a complete structured `content` value.
|
|
39
|
-
- When a new item must contain an image,
|
|
34
|
+
- When a new item must contain an image, prefer putting the `richText` value with the image block directly in `create-item.translations[].content`.
|
|
40
35
|
- Use the actual content locale in `translations[].locale`. Missing locales are introduced when translations are applied.
|
|
41
36
|
- Put item configuration inside `item.config`, not beside `item`.
|
|
42
37
|
- Item key must be unique among siblings.
|
|
@@ -208,7 +203,7 @@ Minimal valid examples:
|
|
|
208
203
|
`set-image-asset`, `update-image-asset-metadata`, `remove-image-asset`
|
|
209
204
|
|
|
210
205
|
- Prefer `survey_asset import-attachment` for binary image imports so the model never copies attachment base64.
|
|
211
|
-
- To use that import in a new item, follow it with
|
|
206
|
+
- To use that import in a new item, follow it with a `survey_change` call and embed `{ "type": "image", "source": { "type": "asset", "assetId": "<returned-id>" } }` directly in the new item's rich-text translation. The import is retained automatically in the turn draft.
|
|
212
207
|
- Metadata and removal are typed and validated. `survey_asset remove` refuses an asset that is still referenced in the immutable snapshot.
|
|
213
208
|
- To remove referenced images and their asset atomically, use one `survey_change` call whose `operations` contain every reference removal first and `{ "kind": "remove-image-asset", "assetId": "..." }` last. For example, deleting an image-only info card and its asset is `[remove-item, remove-image-asset]` in one candidate.
|
|
214
209
|
|
|
@@ -6,6 +6,8 @@ Use this reference when the user asks to translate, localize, add a language, or
|
|
|
6
6
|
|
|
7
7
|
- A target locale may be absent. That is a normal starting state, not an error and not a reason to inspect a nonexistent translation branch.
|
|
8
8
|
- Use the target locale code directly in typed translation operations. The first applied translation creates the locale branch while preserving every existing locale.
|
|
9
|
+
- To remove an existing survey language, load the `remove-survey-locale` operation contract and use that typed operation with the exact locale code. Do not delete translations one item at a time or remove the locale branch with raw JSON Patch.
|
|
10
|
+
- Removing a locale deletes all respondent-facing survey and item translations stored under it. The final remaining locale cannot be removed.
|
|
9
11
|
- Never create a temporary item, placeholder text, blank title, or dummy translation merely to introduce a locale. Introduce it only through the real respondent-visible translations requested by the user.
|
|
10
12
|
- Never put target-language respondent text into an existing source-language locale just because that locale already exists.
|
|
11
13
|
- Coding keys and editor-only item labels are not respondent translations. Translate them only when the user explicitly asks.
|
|
@@ -18,7 +18,7 @@ Use this reference when the user asks to implement, recreate, convert, import, o
|
|
|
18
18
|
- Empty lines, blanks, underscores, table cells intended for handwriting, parenthetical "specify" prompts, and inline write-in areas in actual questions imply an input field. Model them as form fields or embedded option forms as appropriate.
|
|
19
19
|
- Do not create respondent questions for front-cover study identifiers, barcodes, prefilled participant names, prefilled dates of birth, page numbers, institutional logos, or duplicate administrative fields when those values should come from digital participant metadata or are asked later as real survey questions.
|
|
20
20
|
- Printed examples that demonstrate how to fill in a paper form should be preserved as instructional text when useful, not converted into real inputs.
|
|
21
|
-
- Preserve question order, numbering intent, and section structure. For long sources, use multiple
|
|
21
|
+
- Preserve question order, numbering intent, and section structure. For long sources, use multiple bounded mutation calls rather than omitting details. Each successful call automatically extends the same turn draft.
|
|
22
22
|
- Do not use representative sampling, "and similar items", broad paraphrase, or shortened tables for source-derived surveys unless the user explicitly asks for an abbreviated version. Repeated rows, repeated follow-ups, and long option sets still need to be modeled.
|
|
23
23
|
- If the source is too long to hold comfortably in context, work by source/page/section chunks. For each chunk, make a complete implementation decision for every respondent-facing element before moving on.
|
|
24
24
|
- Keep each source-import `survey_change` payload bounded. A good chunk is one source page/section or about 4-8 respondent items, including their options, fields, footnotes, and conditions. Continue with additional chunks instead of constructing one very large tool call.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as surveyDocumentVersionSchema, L as surveyAssistantSnapshotPayloadSchema } from "./protocol-
|
|
2
|
-
import { Q as createSurveyAssistantEngineContext } from "./engine-
|
|
1
|
+
import { B as surveyDocumentVersionSchema, L as surveyAssistantSnapshotPayloadSchema } from "./protocol-DpCYmCjr.mjs";
|
|
2
|
+
import { Q as createSurveyAssistantEngineContext } from "./engine-0AJrv0hI.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
|
|
@@ -38,11 +38,11 @@ const deriveSurveyAssistantDocumentTransition = ({ current, previous }) => {
|
|
|
38
38
|
capabilitiesChanged
|
|
39
39
|
};
|
|
40
40
|
};
|
|
41
|
-
const buildSurveyAssistantRequestContext = ({
|
|
41
|
+
const buildSurveyAssistantRequestContext = ({ turnDraft, identity, snapshot, previousSettledVersion = null, trustedCapabilities = defaultSurveyAssistantCapabilitySet, attachmentAccess, modelAttachments = [], modelSelection }) => {
|
|
42
42
|
const requestContext = new RequestContext();
|
|
43
43
|
requestContext.set("invocation", { kind: "chat" });
|
|
44
|
-
requestContext.set("turnId",
|
|
45
|
-
requestContext.set("
|
|
44
|
+
requestContext.set("turnId", turnDraft.turnId);
|
|
45
|
+
requestContext.set("turnDraft", turnDraft);
|
|
46
46
|
requestContext.set("identity", identity);
|
|
47
47
|
if (identity.authority === "authenticated-host") {
|
|
48
48
|
requestContext.set("authenticatedResourceId", identity.resourceId);
|
|
@@ -60,20 +60,27 @@ const buildSurveyAssistantRequestContext = ({ changeCollector, identity, snapsho
|
|
|
60
60
|
if (modelSelection) requestContext.set("modelSelection", modelSelection);
|
|
61
61
|
if (!snapshot) return requestContext;
|
|
62
62
|
const engineContext = createSurveyAssistantEngineContext(snapshot, trustedCapabilities);
|
|
63
|
+
turnDraft.initialize(engineContext);
|
|
63
64
|
requestContext.set("documentSnapshot", snapshot);
|
|
64
65
|
requestContext.set("engineContext", engineContext);
|
|
65
66
|
return requestContext;
|
|
66
67
|
};
|
|
68
|
+
/**
|
|
69
|
+
* Returns the materialized request-local survey state. The immutable
|
|
70
|
+
* engineContext remains available as the turn baseline, while every tool uses
|
|
71
|
+
* this accessor so successful same-turn mutations are immediately visible.
|
|
72
|
+
*/
|
|
73
|
+
const getSurveyAssistantEngineContext = (requestContext) => requestContext?.get("turnDraft")?.context ?? requestContext?.get("engineContext");
|
|
67
74
|
const requireSurveyAssistantTurnState = (requestContext) => {
|
|
68
75
|
const turnId = requestContext?.get("turnId");
|
|
69
|
-
const
|
|
70
|
-
if (!turnId || !
|
|
76
|
+
const turnDraft = requestContext?.get("turnDraft");
|
|
77
|
+
if (!turnId || !turnDraft || turnDraft.turnId !== turnId) throw new Error("Survey assistant turn context is unavailable or inconsistent.");
|
|
71
78
|
return {
|
|
72
79
|
turnId,
|
|
73
|
-
|
|
80
|
+
turnDraft
|
|
74
81
|
};
|
|
75
82
|
};
|
|
76
83
|
//#endregion
|
|
77
|
-
export {
|
|
84
|
+
export { parseSurveyAssistantSnapshot as a, parseSurveyAssistantPreviousSettledVersion as i, deriveSurveyAssistantDocumentTransition as n, requireSurveyAssistantTurnState as o, getSurveyAssistantEngineContext as r, buildSurveyAssistantRequestContext as t };
|
|
78
85
|
|
|
79
|
-
//# sourceMappingURL=request-context-
|
|
86
|
+
//# sourceMappingURL=request-context-BBzU3VdG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-context-BBzU3VdG.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 {\n surveyAssistantSnapshotPayloadSchema,\n surveyDocumentVersionSchema,\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;\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}\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 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}: {\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}): 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\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":";;;;;AA+EA,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,MAA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,qBAAqB,wCAAwC;EACjE,SAAS;EACT,UAAU;EACX,CAAC;AACF,KAAI,mBACF,gBAAe,IAAI,sBAAsB,mBAAmB;AAE9D,KAAI,oBAAoB,iBAAiB,UAAU,SAAS,EAC1D,gBAAe,IAAI,oBAAoB,iBAAiB;AAE1D,KAAI,iBAAiB,SAAS,EAC5B,gBAAe,IAAI,oBAAoB,iBAAiB;AAE1D,KAAI,eACF,gBAAe,IAAI,kBAAkB,eAAe;AAGtD,KAAI,CAAC,SACH,QAAO;CAGT,MAAM,gBAAgB,mCAAmC,UAAU,oBAAoB;AACvF,WAAU,WAAW,cAAc;AACnC,gBAAe,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"}
|
package/dist/server-agent.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-
|
|
2
|
-
import { n as surveyAssistantTools } from "./index-
|
|
1
|
+
import { o as SurveyAssistantRequestContext, t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CgV4cTg5.mjs";
|
|
2
|
+
import { n as surveyAssistantTools } from "./index-BUF-sE8j.mjs";
|
|
3
3
|
import * as _$_mastra_core_agent0 from "@mastra/core/agent";
|
|
4
4
|
import { Agent, AgentConfig } from "@mastra/core/agent";
|
|
5
5
|
import { Memory } from "@mastra/memory";
|
|
@@ -67,12 +67,8 @@ declare const createSurveyAssistantAgent: ({
|
|
|
67
67
|
result?: unknown;
|
|
68
68
|
}, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_inspect", unknown>;
|
|
69
69
|
survey_change: _$_mastra_core_tools0.Tool<{
|
|
70
|
-
intent: string;
|
|
71
70
|
summary: string;
|
|
72
71
|
operations: unknown[];
|
|
73
|
-
continuationMode?: "replace" | "append" | null | undefined;
|
|
74
|
-
inspectedContext?: string[] | null | undefined;
|
|
75
|
-
notes?: string | null | undefined;
|
|
76
72
|
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_change", unknown>;
|
|
77
73
|
survey_authoring_reference: _$_mastra_core_tools0.Tool<{
|
|
78
74
|
topic: string;
|
|
@@ -94,11 +90,8 @@ declare const createSurveyAssistantAgent: ({
|
|
|
94
90
|
reason?: string | undefined;
|
|
95
91
|
itemIds?: string[] | undefined;
|
|
96
92
|
includeRawLocations?: boolean | undefined;
|
|
97
|
-
intent?: string | undefined;
|
|
98
93
|
summary?: string | undefined;
|
|
99
94
|
mutations?: Record<string, unknown>[] | undefined;
|
|
100
|
-
continuationMode?: "replace" | "append" | undefined;
|
|
101
|
-
inspectedContext?: string[] | undefined;
|
|
102
95
|
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_expression", unknown>;
|
|
103
96
|
survey_attachment: _$_mastra_core_tools0.Tool<{
|
|
104
97
|
documentIds: string[];
|
|
@@ -127,7 +120,6 @@ declare const createSurveyAssistantAgent: ({
|
|
|
127
120
|
name?: string | null | undefined;
|
|
128
121
|
filename?: string | null | undefined;
|
|
129
122
|
alt?: string | null | undefined;
|
|
130
|
-
continuationMode?: "replace" | "append" | undefined;
|
|
131
123
|
}, unknown, unknown, unknown, _$_mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "survey_asset", unknown>;
|
|
132
124
|
}>, undefined, SurveyAssistantRequestContext, _$_mastra_core_agent0.AgentEditorConfig | undefined>;
|
|
133
125
|
//#endregion
|
package/dist/server-agent.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as getDeterministicCreateItemTypes } from "./capabilities-
|
|
1
|
+
import { a as getDeterministicCreateItemTypes } from "./capabilities-DKbNCnBf.mjs";
|
|
2
2
|
import { t as SURVEY_ASSISTANT_AGENT_ID } from "./constants-CFUWrRtl.mjs";
|
|
3
|
-
import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-
|
|
3
|
+
import { n as surveyAssistantTools, t as SURVEY_ASSISTANT_TOOL_IDS } from "./tools-wgLen05n.mjs";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { Agent } from "@mastra/core/agent";
|
|
6
6
|
import { Memory } from "@mastra/memory";
|
|
@@ -122,18 +122,19 @@ const buildInstructions = ({ requestContext }) => {
|
|
|
122
122
|
"You help users inspect, explain, create, and edit CASE surveys in the Survey Editor.",
|
|
123
123
|
"Infer whether the user wants an answer, explanation, critique, clarification, or concrete edit from their message and current editor context. Keep routine answers concise.",
|
|
124
124
|
"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.",
|
|
125
|
-
"Authority order: the
|
|
125
|
+
"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.",
|
|
126
126
|
"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.",
|
|
127
127
|
"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.",
|
|
128
128
|
"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.",
|
|
129
|
-
`Use ${INSPECT_TOOL_NAME} to inspect current context, UI context/highlights, recent editor history, search, item details, image assets, complete paged outlines, response slots, and exact raw JSON paths. Use action "assets" to obtain explicit assetId values, metadata, and usage locations before asset changes; the key of /assets/<key> is the asset ID even though the stored asset object does not repeat it. Never guess what "this", "here", or "the highlighted part" refers to when the
|
|
129
|
+
`Use ${INSPECT_TOOL_NAME} to inspect current draft context, UI context/highlights, recent editor history, search, item details, image assets, complete paged outlines, response slots, and exact raw JSON paths. Successful same-turn edits are immediately visible there. 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.`,
|
|
130
130
|
`Use ${AUTHORING_REFERENCE_TOOL_NAME} to load one narrow convention when needed: core-rules, survey-data-model, source-material-surveys, localization, rich-text-content, item-types, embedded-forms, expressions, assistant-operations, or survey-quality. 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.`,
|
|
131
131
|
`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.`,
|
|
132
|
-
`Use ${CHANGE_TOOL_NAME} for
|
|
132
|
+
`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.`,
|
|
133
133
|
`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.`,
|
|
134
134
|
"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.",
|
|
135
135
|
"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.",
|
|
136
|
-
"
|
|
136
|
+
"Survey languages are locale branches. When the user asks to remove or delete a survey language, use remove-survey-locale with the exact existing locale code; load its assistant-operations contract before proposing the change. Never substitute translation-by-translation deletion or a raw patch. The final remaining locale cannot be removed.",
|
|
137
|
+
"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.",
|
|
137
138
|
"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.",
|
|
138
139
|
"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.",
|
|
139
140
|
"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.",
|
|
@@ -145,13 +146,12 @@ const buildInstructions = ({ requestContext }) => {
|
|
|
145
146
|
"Every form or embedded-form select option needs a visible translation. Do not rely on raw controller values as respondent labels.",
|
|
146
147
|
"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.",
|
|
147
148
|
`Files attached to the current user message are already available directly. When an earlier stored attachment is relevant, call ${ATTACHMENT_TOOL_NAME} with only the needed document ids before answering or editing. Always load the relevant stored source for factual document questions or source-faithful authoring; conversational memory is not a lossless copy. After the tool succeeds, the selected original PDFs/images are attached to your next model input: read them directly and continue the task. Never claim that a successfully loaded attachment is unavailable, ask for extracted text, or describe the attachment tool as an extraction limitation. Do not load unrelated attachments, and do not ask the user to upload a listed file again.`,
|
|
148
|
-
`Use ${ASSET_TOOL_NAME} to import an attached image into
|
|
149
|
-
"For branching, conditions, expression validations, prefills, and template values
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
"
|
|
154
|
-
"Before answering, reconcile every requested target against the final validated candidates. Never claim rejected, superseded, missing, partial, or failed work was completed. If a request remains incomplete, correct it once or state the exact remaining work.",
|
|
149
|
+
`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.`,
|
|
150
|
+
"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.",
|
|
151
|
+
`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.`,
|
|
152
|
+
"A rejected mutation leaves the validated draft unchanged and blocks turn authorization. Correct the same rejected target in another mutation call; unrelated valid edits do not clear the block. Never drop requested behavior merely to obtain validation.",
|
|
153
|
+
"Prefer one mutation call for an ordinary request. Split work only for genuine dependencies or bounded chunks; accumulation is automatic.",
|
|
154
|
+
"Before answering, reconcile every requested target against the latest validated draft. Never claim rejected, missing, partial, or failed work was completed. If a request remains incomplete, correct it once or state the exact remaining work.",
|
|
155
155
|
"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.",
|
|
156
156
|
"For concrete supported edits, inspect the relevant live state, load every reference explicitly required above before the first mutation attempt, prepare the complete change, then summarize only the final validated candidates concisely. Do not ask the user to choose an output mode.",
|
|
157
157
|
"Do not write tool syntax, hidden chain-of-thought, or invented validation results in normal text. Never claim persistence outside the editor.",
|