Data client SDK
Applies to HENGSHI SENSE 7.0. hengshi-data-agent-client@VERSION.js exposes window.HengshiDataAgent.createClient(options) for HTTP/SSE transport only. It mounts no UI. The customer owns rendering, authentication, interactions, and recovery. HENGSHI owns model execution, permissions, conversations, and tasks.
Complete authentication and CORS prerequisites first. Use the complete UI SDK for a ready-made chat window; loading both is unnecessary.
Create a client and conversation
Replace the service URL, VERSION, resource IDs, and question dates with actual values (see Getting the SDK files and version for the version lookup). Load the SDK script first, then run the JavaScript examples in the same async function or <script type="module">, keeping the client, conversation, and streaming code in one scope.
<script src="https://analytics.example.com/assets/hengshi-data-agent-client@VERSION.js"></script>const agent = window.HengshiDataAgent.createClient({
baseUrl: 'https://analytics.example.com',
credentials: 'include',
// The host supplies the CSRF header required by its Cookie login solution.
// headers: { 'X-CSRF-Token': csrfToken },
});
const capability = await agent.getCapabilities();
if (!capability.available) {
throw new Error(capability.message || 'Data Agent is unavailable');
}
const conversation = await agent.createConversation({
title: 'Sales analysis',
agentContext: {
mode: 'read_only',
scope: { type: 'application', appId: 251 },
},
});
const conversationId = conversation.id;createConversation() returns the conversation directly, with no additional .data wrapper. The service resolves the model profile identity and audit revision; the caller does not select them. Each later turn reads the current profile by that identity.
Choose one of the supported scopes:
{ type: 'application', appId: 251 }
{ type: 'measure_subject', measureSubjectId: 7 }
{ type: 'dashboard', appId: 251, dashboardId: 18 }The dashboard must be saved. For authoring, use agentContext: { mode: 'authoring' } without scope, and mode: 'authoring' on the streaming turn.
Minimal streaming question
Continue the client creation example. Add an output container and cancellation button:
<button id="cancel">Cancel current question</button>
<pre id="answer"></pre>const output = document.getElementById('answer');
const state = { conversationId, runId: null, chatUid: null };
document.getElementById('cancel').onclick = async () => {
if (state.runId) {
await agent.cancelRun({ conversationId, runId: state.runId });
}
};
try {
for await (const event of agent.startInteractiveTurn({
conversationId,
body: {
prompt: 'Show 2025 sales quantity by region',
clientRequestId: crypto.randomUUID(),
},
})) {
const { metadata = {}, data = {} } = event;
if (metadata.runId) state.runId = metadata.runId;
if (metadata.chatUid) state.chatUid = metadata.chatUid;
if (event.event === 'assistant.text.delta') {
output.textContent += data.delta || '';
} else if (event.event === 'lui.error') {
output.textContent += '\n' + (data.message || data.code || 'Execution failed');
} else if (event.event === 'done') {
output.textContent += '\nRun status: ' + (data.status || 'Read the saved chat');
} else if (event.event.startsWith('lui.') || event.event === 'operation.proposed') {
// Display protocol data during integration; implement chart/clarification/confirmation UI for production.
output.textContent += '\n' + JSON.stringify({ event: event.event, data });
}
}
} catch (error) {
output.textContent += '\nConnection error: ' + error.message;
// Retain state and read server state as described below; do not automatically resend.
}This example demonstrates text and protocol integration, not a complete chart or clarification UI. clientRequestId correlates requests; it does not guarantee safe turn POST replay. Persist conversationId, runId, and chatUid in production and read server state after refreshing.
Events and results
SDK events use { id, event, metadata, data }. Read seq, runId, traceId, requestId, conversationId, and chatUid from metadata, not the event's top level.
| Identifier | Purpose |
|---|---|
runId | One turn run. Normal streaming does not require it; persist it to query status or cancel after a disconnect or refresh. getRun returns status/stage/counts, not a replay of streamed text. |
traceId | Server-side tracing for logs and audit; client logic does not use it. |
requestId | Correlates one HTTP/SSE request for troubleshooting. It is not a conversation or run id and cannot resume or cancel a turn. |
clientRequestId in the request body is a client-generated submission correlation id, distinct from the server's event requestId; neither permits replaying the turn POST.
| Event | Client handling |
|---|---|
chat.created | Bind pending messages to the real chatUid and runId |
agent.status / agent.analysis.delta | Display status or user-visible analysis summaries |
tool.call / tool.result | Processing, tool success, and errors |
assistant.text.delta | Append data.delta |
agent.token_usage | Model and Token consumption |
lui.chart / lui.citation | Render charts and sources |
lui.clarification | Render data.questions[] as one form; after confirmation continue with a new ordinary turn |
operation.proposed | Show the proposed operation and wait for explicit confirmation |
lui.error | Display stable error code and message |
done | Stream ended; use status and persisted chat to determine the outcome, not this event alone |
lui.chart carries HENGSHI chart data/configuration; KPI and tables use the same event. It is not generic configuration for any chart library. Adapt it in a custom renderer. A valid text-only or clarification answer is not a chart-delivery failure.
Cancellation, disconnection, and history
cancelRun({ conversationId, runId }) requests server cancellation. An AbortSignal or stopping consumption only affects the client request and is not a substitute for server cancellation.
Transparent SSE resumption is not guaranteed. The SDK makes bounded retries for idempotent reads only; it does not retry turn POSTs. Once identifiers are available, read run state, wait for completion or cancellation, and read the persisted chat:
const run = await agent.getRun({
conversationId: state.conversationId,
runId: state.runId,
});
const chat = state.chatUid
? await agent.getChat(state.conversationId, state.chatUid)
: null;SSE is a live channel, not a replay channel. Text deltas are sent only while connected, and the server does not store a replayable LUI event stream, so a refreshed page cannot resume the original SSE from its last offset. The available recovery path is to query run status with runId and, once finished, read the persisted chat with chatUid (the page's polling of GET /api/conversations/{id}/chats/{chatUid} follows this path). Token-level continuation would require a server-side persisted event endpoint that replays by seq; no such endpoint exists today.
If no real identifiers arrived, inspect listChats(conversationId, { limit: 20 }) before resending. listChats() returns { data, totalHits, offset }; getChat() returns one chat directly. Missing, unpersisted, or active results are not success.
Read history with getConversation(id), listConversations({ offset, limit }), and listChats(id, { offset, limit }). History belongs to the authenticated user. Create a new conversation to change scope or mode, or when its model profile is unavailable. Answer again also uses a new-turn method and keeps the old answer.
Clarification confirmation and operation confirmation
On lui.clarification, data.questions[] carries every unresolved slot of the turn, each with 2-5 options. Render one form; after the user confirms, compose the picks into a new ordinary turn and send it:
const prompt = [
'继续上一个问题,已确认:',
...questions.map(question => `- ${question.question}:${labelOf(question, selections[question.id])}`),
].join('\n');
for await (const event of agent.startInteractiveTurn({
conversationId,
body: {
prompt,
clientRequestId: crypto.randomUUID(),
// The structured picks travel with this turn; the service closes the old
// clarification when it creates the turn.
runtimeContext: {
clarificationResolution: {
clarificationId,
answers: questions.map(question => ({
questionId: question.id,
selectedCandidateIds: selections[question.id],
})),
},
},
},
})) {
// handle events exactly like a normal turn
}
// Explicit close is only needed when the user dismisses the form.
// await agent.abandonClarification({ conversationId, clarificationId });The service keeps the clarification turn's agent session, so the new turn resumes the same thread. Creating the turn also closes any clarification that is still ACTIVE in that conversation and stores the validated picks from runtimeContext.clarificationResolution, so a reload renders the read-only form with the original selections; a plain reply without the resolution closes the old clarification too. abandonClarification is only for an explicit dismissal. The 7.0 SDK no longer exposes answerClarification (the :answer endpoint was removed); integrations still calling it must adopt this flow.
Operation confirmation applies only to service-admitted operations, currently schedule creation. Use getOperation({ operationId }) to display content and expiry. After explicit user confirmation, submit the proposal fingerprint:
const receipt = await agent.confirmOperation({ operationId, fingerprint });Retain and display the terminal result. Do not automatically reconfirm after expiry, content changes, or permission changes. Do not auto-confirm a proposal or construct permissions/arbitrary write requests yourself.
Options and errors
| Option | Default and meaning |
|---|---|
baseUrl | Required HENGSHI service origin |
apiPrefix | /api |
credentials | include; use omit for Bearer-only authentication |
headers | Object or async function; host supplies authentication, CSRF, and required metadata |
fetchImpl | Browser fetch |
retry | At most 2 attempts for idempotent reads by default; configurable maxAttempts, backoffMs, maxBackoffMs |
Methods accept signal and per-request headers. startNonInteractiveTurn({ conversationId, body }) returns { data: chat, version } for callers without progress or interactive choices; questions requiring clarification do not enter an interactive pause.
Errors contain status, code, message, retryable, and available details.requestId. Preserve codes, which may be business numbers or strings. Check login for 401 and permissions for 403. Ask the administrator to diagnose timeouts or unavailable services. retryable does not permit turn POST replay.