@healthcloudai/hc-ams 3.6.6 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,9 @@ const agents = await sdk.ams.getAgentsForTenant("<TENANT_ID>");
23
23
 
24
24
  ## Authentication
25
25
 
26
- `ams.getAgentsForTenant` is public and requires no access token.
26
+ `ams.getAgentsForTenant` and native V2's `v2.listPublicAgents` / `v2.createRun`
27
+ are public and require no access token. V2 public admission also requires an
28
+ allowed browser Origin configured by the server.
27
29
 
28
30
  Every other REST client (`agents`, `departments`, `teams`, `skills`,
29
31
  `policies`, `guardrails`, `dataSources`, `tools`, `testPersonas`) requires a
@@ -42,6 +44,7 @@ own patient auth flow in production.
42
44
  | Client | Resource | Notes |
43
45
  | --- | --- | --- |
44
46
  | `sdk.ams` | Public application-agent discovery | No auth required |
47
+ | `sdk.v2` | Native V2 public discovery and owned-run creation | Explicit V2 endpoint; no staff token |
45
48
  | `sdk.agents` | Agent CRUD, transfer candidates, conversation history | `create`/`update`/`delete` may 405 if the tenant has `disable_direct_agent_mutations` enabled (see below) |
46
49
  | `sdk.departments` | Department CRUD + activate/deactivate | |
47
50
  | `sdk.teams` | Team CRUD | |
@@ -224,6 +227,88 @@ department/team/agents/test-persona, logging in as the persona, and
224
227
  validating a multi-turn conversation's turns, transfers, artifacts,
225
228
  notifications, and activity.
226
229
 
230
+ ## Native V2 owned runs
231
+
232
+ Use `connectV2AgentChat` for a native V2 service. `connectAgentChat` remains
233
+ the V1 API. Select the V2 REST base explicitly; WSS follows that origin unless
234
+ you supply an independent WSS proxy base.
235
+
236
+ ```ts
237
+ const sdk = new HCAmsSDK({
238
+ environment: "dev",
239
+ tenantId: "healthcheck",
240
+ baseUrlOverride: "https://dev-ams-v2-services.health.cloud/api/ams",
241
+ });
242
+ const { agents } = await sdk.v2.listPublicAgents("healthcheck");
243
+ const agent = agents[0];
244
+ if (!agent) throw new Error("No public agent is available");
245
+ const run = await sdk.v2.createRun("healthcheck", agent.id);
246
+ const chat = sdk.connectV2AgentChat({
247
+ agentId: agent.id,
248
+ run,
249
+ identity: { kind: "anonymous", sessionId: crypto.randomUUID() },
250
+ capabilities: { platform: "web", supported_actions: ["login"] },
251
+ });
252
+ chat.on("action_request", action => {
253
+ // Render only capabilities that your host actually implements.
254
+ if (action.type === "login") showPatientSignIn(action.action_id);
255
+ });
256
+ chat.on("history", history => renderHistory(history.messages));
257
+ chat.on("chat", delta => renderAssistantDelta(delta));
258
+ const metadata = await chat.connect();
259
+ // auth_ok metadata and handlers are available before same-tick history/replay.
260
+ chat.sendChat({
261
+ content: "I would like help with an appointment",
262
+ turn_id: crypto.randomUUID(),
263
+ previous_turn_id: chat.lastTurnId,
264
+ });
265
+ ```
266
+
267
+ Keep `run` in a private in-memory host holder, together with the connection's
268
+ `replaySince` and acknowledged `lastTurnId`. The claim secret and patient token
269
+ travel only in the first auth frame, never in a URL. Do not log the run or put
270
+ its secret in browser storage, analytics, transcript handoff, or error details.
271
+ Clear the holder on logout, account replacement, or tenant/endpoint changes.
272
+ The client itself hides credentials from ordinary object serialization.
273
+
274
+ `connect()` resolves the typed `auth_ok` metadata, including pending actions,
275
+ protocol, last turn, and server event head. `on("event_replay", ...)` retains
276
+ the server's completeness flag; replayed events also reach their typed handlers
277
+ once per sequence. `turn_ack` advances the accepted predecessor. For an explicit
278
+ retry, retain the command returned by `sendChat` and pass it to `sendCommand`;
279
+ do not generate a replacement UUID or create another run after a disconnect.
280
+ There are no automatic reconnects or retries. Calling `connect()` again after
281
+ close uses the same claim and delivered cursor.
282
+
283
+ The same instance retains sent command terms in memory so an identical original
284
+ command can be retried after acknowledgment or reconnect. Reusing its turn ID
285
+ with changed terms is rejected. Discard the instance when discarding its run.
286
+ Event listener exceptions are isolated: they do not interrupt other listeners,
287
+ authentication, or connection cleanup. Hosts should handle their own observer errors.
288
+
289
+ Browsers supply their application Origin. Node/native callers can pass
290
+ `{ origin: "https://patient.example" }` as the last argument to
291
+ `listPublicAgents` and `createRun`; the server must allow that origin.
292
+
293
+ For an already-bound run, use
294
+ `identity: { kind: "patient", patientId, getAccessToken }`. The token provider
295
+ runs fresh for every connection. `bindPatient` implements the existing
296
+ **offered-login socket** command, including its action, identity proof, and
297
+ delivered predecessor. It does not implement ordinary app-initiated sign-in;
298
+ The backend now provides that separate HTTP contract; maintained SDK methods
299
+ and Patient/CLI integration remain follow-up work in AMS issues #1238 and #1240.
300
+ Preserve the same run through that flow.
301
+
302
+ `sendActionResult` supports the selected protocol's slot/booking wire commands;
303
+ it does not authorize a booking or establish that a tool is enabled. Advertise
304
+ only working host handlers and require server-issued terms and confirmation.
305
+ Binding requires advertised `login`; slot replies require `slot_picker`, and
306
+ booking confirmations/status commands require `confirm`.
307
+ Native V2 does not expose legacy voice/audio or transcript-handoff commands.
308
+ HTTP admission errors retain only a fixed message and status, without arbitrary
309
+ server bodies or transport causes. No endpoint switch or package publication
310
+ is performed by constructing this client.
311
+
227
312
  ## Configuration
228
313
 
229
314
  | Option | Description |
package/dist/index.cjs CHANGED
@@ -3,6 +3,9 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __typeError = (msg) => {
7
+ throw TypeError(msg);
8
+ };
6
9
  var __export = (target, all) => {
7
10
  for (var name in all)
8
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,6 +19,19 @@ var __copyProps = (to, from, except, desc) => {
16
19
  return to;
17
20
  };
18
21
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
23
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
24
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
26
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
27
+ var __privateWrapper = (obj, member, setter, getter) => ({
28
+ set _(value) {
29
+ __privateSet(obj, member, value, setter);
30
+ },
31
+ get _() {
32
+ return __privateGet(obj, member, getter);
33
+ }
34
+ });
19
35
 
20
36
  // src/index.ts
21
37
  var index_exports = {};
@@ -28,6 +44,8 @@ __export(index_exports, {
28
44
  DepartmentsClient: () => DepartmentsClient,
29
45
  GuardrailsClient: () => GuardrailsClient,
30
46
  HCAmsSDK: () => HCAmsSDK,
47
+ NativeV2Client: () => NativeV2Client,
48
+ NativeV2WssClient: () => NativeV2WssClient,
31
49
  PoliciesClient: () => PoliciesClient,
32
50
  SDKError: () => SDKError,
33
51
  SERVICE_NAME: () => SERVICE_NAME,
@@ -989,6 +1007,414 @@ var WssClient = class {
989
1007
  }
990
1008
  };
991
1009
 
1010
+ // src/v2/validation.ts
1011
+ function invalid(message) {
1012
+ return new SDKError({ message, statusCode: 0 });
1013
+ }
1014
+ function record(value) {
1015
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1016
+ }
1017
+ function uuid(value) {
1018
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
1019
+ }
1020
+ function identity(value) {
1021
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
1022
+ }
1023
+ function protocol(value) {
1024
+ return typeof value === "string" && [
1025
+ "dbos_signin_v1",
1026
+ "dbos_signin_cards_v1",
1027
+ "dbos_signin_actions_v1",
1028
+ "dbos_signin_booking_v1",
1029
+ "dbos_signin_cta_v1"
1030
+ ].includes(value);
1031
+ }
1032
+ function cursor(value) {
1033
+ return Number.isSafeInteger(value) && value >= 0;
1034
+ }
1035
+ function ownedRun(value) {
1036
+ if (!record(value) || !uuid(value.run_id) || !protocol(value.protocol) || typeof value.run_secret !== "string" || value.run_secret.length < 32 || value.run_secret.length > 128) {
1037
+ throw invalid("Invalid V2 run credentials or protocol.");
1038
+ }
1039
+ }
1040
+ function onlyKeys(value, allowed) {
1041
+ return Object.keys(value).every((key) => allowed.includes(key));
1042
+ }
1043
+ function capabilities(value) {
1044
+ if (!record(value) || !onlyKeys(value, [
1045
+ "platform",
1046
+ "supported_actions",
1047
+ "patient_flags_confirmation",
1048
+ "intake_confirmation",
1049
+ "encounter_confirmation",
1050
+ "locale",
1051
+ "time_zone"
1052
+ ])) return false;
1053
+ if (value.platform !== void 0 && !["web", "ios", "android", "terminal", "unknown"].includes(value.platform)) return false;
1054
+ if (value.supported_actions !== void 0 && (!Array.isArray(value.supported_actions) || value.supported_actions.length > 16 || !value.supported_actions.every((action) => ["confirm", "insurance_scan", "vitals_import", "slot_picker", "login", "symptom_save", "telehealth_join"].includes(action)))) return false;
1055
+ for (const key of ["patient_flags_confirmation", "intake_confirmation", "encounter_confirmation"]) {
1056
+ if (value[key] !== void 0 && typeof value[key] !== "boolean") return false;
1057
+ }
1058
+ return ["locale", "time_zone"].every((key) => value[key] === void 0 || typeof value[key] === "string" && value[key].length > 0 && value[key].length <= 128);
1059
+ }
1060
+
1061
+ // src/v2/NativeV2Client.ts
1062
+ var NativeV2Client = class {
1063
+ constructor(http) {
1064
+ this.http = http;
1065
+ }
1066
+ async listPublicAgents(tenantId, options = {}) {
1067
+ if (!identity(tenantId)) throw invalid("Invalid V2 tenant identity.");
1068
+ const result = await this.request("GET", "/public/tenants/{tenant_id}/agents", tenantId, options);
1069
+ if (!record(result) || !Array.isArray(result.agents) || !result.agents.every((agent) => record(agent) && identity(agent.id) && typeof agent.name === "string" && protocol(agent.protocol))) {
1070
+ throw invalid("Invalid V2 public discovery response.");
1071
+ }
1072
+ return { agents: result.agents.map((agent) => ({ id: agent.id, name: agent.name, protocol: agent.protocol })) };
1073
+ }
1074
+ async createRun(tenantId, agentId, options = {}) {
1075
+ if (!identity(tenantId) || !identity(agentId)) throw invalid("Invalid V2 tenant or agent identity.");
1076
+ const result = await this.request("POST", "/public/tenants/{tenant_id}/agents/{agent_id}/runs", tenantId, options, agentId);
1077
+ ownedRun(result);
1078
+ return { run_id: result.run_id, run_secret: result.run_secret, protocol: result.protocol };
1079
+ }
1080
+ async request(method, path, tenantId, options, agentId) {
1081
+ if (options.origin !== void 0) {
1082
+ try {
1083
+ const parsed = new URL(options.origin);
1084
+ if (!["https:", "http:"].includes(parsed.protocol) || parsed.origin !== options.origin) throw invalid("Invalid V2 admission origin.");
1085
+ } catch {
1086
+ throw invalid("Invalid V2 admission origin.");
1087
+ }
1088
+ }
1089
+ try {
1090
+ return await this.http.request(method, path, {
1091
+ pathParams: { tenant_id: tenantId, ...agentId ? { agent_id: agentId } : {} },
1092
+ auth: false,
1093
+ ...method === "POST" ? { body: {} } : {},
1094
+ ...options.origin !== void 0 ? { headers: { Origin: options.origin } } : {}
1095
+ });
1096
+ } catch (error) {
1097
+ throw new SDKError({
1098
+ message: "V2 public admission request failed.",
1099
+ statusCode: error instanceof SDKError ? error.statusCode : 0
1100
+ });
1101
+ }
1102
+ }
1103
+ };
1104
+
1105
+ // src/v2/NativeV2WssClient.ts
1106
+ var _options, _socket, _ctor, _base, _authenticated, _lastTurn, _cursor, _sentCommands, _generation, _cleanup, _cancelConnect, _listeners, _NativeV2WssClient_instances, requireConnected_fn, validAuth_fn, receive_fn, dispatch_fn;
1107
+ var NativeV2WssClient = class {
1108
+ constructor(options) {
1109
+ __privateAdd(this, _NativeV2WssClient_instances);
1110
+ __privateAdd(this, _options);
1111
+ __privateAdd(this, _socket);
1112
+ __privateAdd(this, _ctor);
1113
+ __privateAdd(this, _base);
1114
+ __privateAdd(this, _authenticated, false);
1115
+ __privateAdd(this, _lastTurn, null);
1116
+ __privateAdd(this, _cursor);
1117
+ __privateAdd(this, _sentCommands, /* @__PURE__ */ new Map());
1118
+ __privateAdd(this, _generation, 0);
1119
+ __privateAdd(this, _cleanup);
1120
+ __privateAdd(this, _cancelConnect);
1121
+ __privateAdd(this, _listeners, /* @__PURE__ */ new Map());
1122
+ var _a, _b, _c, _d, _e, _f, _g;
1123
+ ownedRun(options.run);
1124
+ const owner = options.identity.kind === "anonymous" ? options.identity.sessionId : options.identity.patientId;
1125
+ if (!identity(options.tenantId) || !identity(options.agentId) || !identity(owner) || options.identity.kind !== "anonymous" && options.identity.kind !== "patient" || options.identity.kind === "patient" && typeof options.identity.getAccessToken !== "function" || !cursor((_a = options.replaySince) != null ? _a : 0)) throw invalid("Invalid V2 connection identity or replay cursor.");
1126
+ if (!capabilities((_b = options.capabilities) != null ? _b : {}) || options.lang !== void 0 && (typeof options.lang !== "string" || !options.lang || options.lang.length > 128)) throw invalid("Invalid V2 client capabilities or language.");
1127
+ assertTimeout((_c = options.authTimeoutMs) != null ? _c : 1e4, "authTimeoutMs");
1128
+ __privateSet(this, _base, normalizeWssBaseUrl((_d = options.baseUrlOverride) != null ? _d : resolveWssBaseUrl(options.environment)));
1129
+ const ctor = (_e = options.WebSocketImpl) != null ? _e : globalThis.WebSocket;
1130
+ if (!ctor) throw invalid("No WebSocket implementation available. Pass WebSocketImpl.");
1131
+ __privateSet(this, _ctor, ctor);
1132
+ __privateSet(this, _cursor, (_f = options.replaySince) != null ? _f : 0);
1133
+ __privateSet(this, _options, {
1134
+ ...options,
1135
+ run: { ...options.run },
1136
+ identity: { ...options.identity },
1137
+ capabilities: JSON.parse(JSON.stringify((_g = options.capabilities) != null ? _g : {}))
1138
+ });
1139
+ }
1140
+ get lastTurnId() {
1141
+ return __privateGet(this, _lastTurn);
1142
+ }
1143
+ get replaySince() {
1144
+ return __privateGet(this, _cursor);
1145
+ }
1146
+ on(type, listener) {
1147
+ if (!__privateGet(this, _listeners).has(type)) __privateGet(this, _listeners).set(type, /* @__PURE__ */ new Set());
1148
+ const entry = listener;
1149
+ __privateGet(this, _listeners).get(type).add(entry);
1150
+ return () => {
1151
+ var _a;
1152
+ (_a = __privateGet(this, _listeners).get(type)) == null ? void 0 : _a.delete(entry);
1153
+ };
1154
+ }
1155
+ connect() {
1156
+ var _a;
1157
+ if (__privateGet(this, _socket) && __privateGet(this, _socket).readyState < 2) return Promise.reject(invalid("V2 connection is already active."));
1158
+ (_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
1159
+ __privateSet(this, _authenticated, false);
1160
+ const generation = ++__privateWrapper(this, _generation)._;
1161
+ const options = __privateGet(this, _options);
1162
+ const owner = options.identity.kind === "anonymous" ? options.identity.sessionId : options.identity.patientId;
1163
+ const url = new URL(joinServiceUrl(__privateGet(this, _base), `/ws/agents/${encodeURIComponent(options.agentId)}/chat`));
1164
+ url.searchParams.set("session_id", `${options.tenantId}/${owner}`);
1165
+ url.searchParams.set("transport", options.run.protocol);
1166
+ url.searchParams.set("run_id", options.run.run_id);
1167
+ url.searchParams.set("replay_since", String(__privateGet(this, _cursor)));
1168
+ if (options.identity.kind === "anonymous") url.searchParams.set("anonymous", "1");
1169
+ if (options.lang) url.searchParams.set("lang", options.lang);
1170
+ return new Promise((resolve, reject) => {
1171
+ var _a2;
1172
+ let socket;
1173
+ try {
1174
+ socket = new (__privateGet(this, _ctor))(url.toString());
1175
+ } catch {
1176
+ reject(invalid("V2 connection could not be opened."));
1177
+ return;
1178
+ }
1179
+ __privateSet(this, _socket, socket);
1180
+ let settled = false;
1181
+ let authSent = false;
1182
+ const current = () => generation === __privateGet(this, _generation) && socket === __privateGet(this, _socket);
1183
+ const timer = setTimeout(() => fail("Authentication timed out."), (_a2 = options.authTimeoutMs) != null ? _a2 : 1e4);
1184
+ const cleanup = () => {
1185
+ clearTimeout(timer);
1186
+ socket.removeEventListener("open", onOpen);
1187
+ socket.removeEventListener("message", onMessage);
1188
+ socket.removeEventListener("close", onClose);
1189
+ socket.removeEventListener("error", onError);
1190
+ };
1191
+ const fail = (message) => {
1192
+ if (!current()) return;
1193
+ clearTimeout(timer);
1194
+ if (!settled) {
1195
+ settled = true;
1196
+ reject(invalid(message));
1197
+ } else __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "error", { code: "v2_transport_error", message });
1198
+ __privateSet(this, _authenticated, false);
1199
+ cleanup();
1200
+ __privateSet(this, _cancelConnect, void 0);
1201
+ socket.close();
1202
+ };
1203
+ const onOpen = () => {
1204
+ void (async () => {
1205
+ try {
1206
+ const token = options.identity.kind === "patient" ? await options.identity.getAccessToken() : "";
1207
+ if (!current() || settled || socket.readyState !== 1) return;
1208
+ if (typeof token !== "string" || token.length > 4096 || options.identity.kind === "patient" && !token) throw invalid("Invalid V2 access token.");
1209
+ socket.send(JSON.stringify({
1210
+ type: "auth",
1211
+ token,
1212
+ run_id: options.run.run_id,
1213
+ run_secret: options.run.run_secret,
1214
+ client: options.capabilities,
1215
+ ...options.identity.kind === "patient" ? { patient_id: options.identity.patientId } : {}
1216
+ }));
1217
+ authSent = true;
1218
+ } catch {
1219
+ fail("V2 authentication credentials could not be resolved.");
1220
+ }
1221
+ })();
1222
+ };
1223
+ const onMessage = (event) => {
1224
+ if (!current()) return;
1225
+ let frame;
1226
+ try {
1227
+ if (typeof event.data !== "string" || event.data.length > 2 * 1024 * 1024) throw invalid("Invalid V2 frame.");
1228
+ frame = JSON.parse(event.data);
1229
+ if (!record(frame) || typeof frame.type !== "string" || !record(frame.payload)) throw invalid("Invalid V2 frame.");
1230
+ } catch {
1231
+ fail("Invalid V2 server message.");
1232
+ return;
1233
+ }
1234
+ if (!__privateGet(this, _authenticated)) {
1235
+ if (frame.type === "error") {
1236
+ fail("V2 authentication failed.");
1237
+ return;
1238
+ }
1239
+ if (frame.type !== "auth_ok") return;
1240
+ if (!authSent || !__privateMethod(this, _NativeV2WssClient_instances, validAuth_fn).call(this, frame.payload)) {
1241
+ fail("Invalid V2 authentication response.");
1242
+ return;
1243
+ }
1244
+ const metadata = frame.payload;
1245
+ __privateSet(this, _lastTurn, metadata.last_turn_id);
1246
+ __privateSet(this, _authenticated, true);
1247
+ clearTimeout(timer);
1248
+ settled = true;
1249
+ __privateSet(this, _cancelConnect, void 0);
1250
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "auth_ok", metadata);
1251
+ resolve(metadata);
1252
+ return;
1253
+ }
1254
+ if (frame.type === "auth_ok") {
1255
+ fail("Unexpected V2 authentication response.");
1256
+ return;
1257
+ }
1258
+ __privateMethod(this, _NativeV2WssClient_instances, receive_fn).call(this, frame.type, frame.payload);
1259
+ };
1260
+ const onClose = (event) => {
1261
+ if (!current()) return;
1262
+ cleanup();
1263
+ __privateSet(this, _authenticated, false);
1264
+ __privateSet(this, _cancelConnect, void 0);
1265
+ if (!settled) {
1266
+ settled = true;
1267
+ reject(invalid("V2 connection closed before authentication."));
1268
+ }
1269
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "close", { code: event.code });
1270
+ };
1271
+ const onError = () => fail("V2 connection failed.");
1272
+ __privateSet(this, _cancelConnect, () => {
1273
+ if (!settled) {
1274
+ settled = true;
1275
+ reject(invalid("V2 connection closed before authentication."));
1276
+ }
1277
+ });
1278
+ __privateSet(this, _cleanup, cleanup);
1279
+ socket.addEventListener("open", onOpen);
1280
+ socket.addEventListener("message", onMessage);
1281
+ socket.addEventListener("close", onClose);
1282
+ socket.addEventListener("error", onError);
1283
+ });
1284
+ }
1285
+ close() {
1286
+ var _a, _b, _c;
1287
+ (_a = __privateGet(this, _cancelConnect)) == null ? void 0 : _a.call(this);
1288
+ __privateSet(this, _cancelConnect, void 0);
1289
+ ++__privateWrapper(this, _generation)._;
1290
+ (_b = __privateGet(this, _cleanup)) == null ? void 0 : _b.call(this);
1291
+ __privateSet(this, _cleanup, void 0);
1292
+ __privateSet(this, _authenticated, false);
1293
+ (_c = __privateGet(this, _socket)) == null ? void 0 : _c.close();
1294
+ __privateSet(this, _socket, void 0);
1295
+ }
1296
+ sendChat(payload) {
1297
+ const command = { type: "chat", payload: { ...payload } };
1298
+ this.sendCommand(command);
1299
+ return command;
1300
+ }
1301
+ sendActionResult(payload) {
1302
+ this.sendCommand({ type: "action_result", payload });
1303
+ }
1304
+ /** Offered-login socket binding; ordinary app sign-in uses its separate HTTP contract. */
1305
+ bindPatient(payload) {
1306
+ this.sendCommand({ type: "bind_patient", payload });
1307
+ }
1308
+ /** Explicit retries resend the caller's original command identity and terms. */
1309
+ sendCommand(command) {
1310
+ var _a, _b, _c, _d, _e, _f;
1311
+ __privateMethod(this, _NativeV2WssClient_instances, requireConnected_fn).call(this);
1312
+ if (!record(command) || !onlyKeys(command, ["type", "payload"]) || !record(command.payload)) {
1313
+ throw invalid("Invalid V2 command.");
1314
+ }
1315
+ const payload = command.payload;
1316
+ const serialized = JSON.stringify(command);
1317
+ const original = __privateGet(this, _sentCommands).get(payload.turn_id);
1318
+ if (!uuid(payload.turn_id) || !(payload.previous_turn_id === null || uuid(payload.previous_turn_id)) || payload.turn_id === payload.previous_turn_id || (original !== void 0 ? original !== serialized : payload.previous_turn_id !== __privateGet(this, _lastTurn))) {
1319
+ throw invalid("Invalid V2 command identity or predecessor.");
1320
+ }
1321
+ if (command.type === "chat") {
1322
+ if (!onlyKeys(payload, ["content", "turn_id", "previous_turn_id", "cta_confirmation"]) || typeof payload.content !== "string" || !payload.content.length || payload.content.length > 16384) throw invalid("Invalid V2 chat command.");
1323
+ if (payload.cta_confirmation !== void 0) {
1324
+ const choice = payload.cta_confirmation;
1325
+ if (__privateGet(this, _options).run.protocol !== "dbos_signin_cta_v1" || payload.previous_turn_id === null || !record(choice) || !onlyKeys(choice, ["offer_id", "action", "option_id"]) || typeof choice.offer_id !== "string" || !/^[0-9a-f]{32}$/.test(choice.offer_id) || typeof choice.action !== "string" || !/^[a-z0-9_-]{1,128}$/.test(choice.action) || ![`${choice.offer_id}:yes`, `${choice.offer_id}:no`].includes(choice.option_id)) throw invalid("Invalid V2 CTA confirmation.");
1326
+ }
1327
+ } else if (command.type === "bind_patient") {
1328
+ if (!((_b = (_a = __privateGet(this, _options).capabilities) == null ? void 0 : _a.supported_actions) == null ? void 0 : _b.includes("login"))) throw invalid("V2 login was not advertised.");
1329
+ if (!onlyKeys(payload, ["action_id", "tenant_id", "patient_id", "token", "run_secret", "identity_proof", "turn_id", "previous_turn_id"]) || !uuid(payload.action_id) || payload.previous_turn_id === null || payload.tenant_id !== __privateGet(this, _options).tenantId || !identity(payload.patient_id) || payload.run_secret !== __privateGet(this, _options).run.run_secret || typeof payload.token !== "string" || !payload.token || payload.token.length > 4096 || typeof payload.identity_proof !== "string" || !payload.identity_proof || payload.identity_proof.length > 2048) throw invalid("Invalid V2 binding command.");
1330
+ } else if (command.type === "action_result") {
1331
+ if (!onlyKeys(payload, ["action_id", "status", "data", "operation", "turn_id", "previous_turn_id"]) || !uuid(payload.action_id) || payload.previous_turn_id === null || !["completed", "cancelled", "failed"].includes(payload.status) || !record(payload.data)) throw invalid("Invalid V2 action command.");
1332
+ const data = payload.data;
1333
+ if ("proposal_id" in data) {
1334
+ if (!((_d = (_c = __privateGet(this, _options).capabilities) == null ? void 0 : _c.supported_actions) == null ? void 0 : _d.includes("confirm"))) throw invalid("V2 confirmation was not advertised.");
1335
+ if (__privateGet(this, _options).run.protocol !== "dbos_signin_booking_v1" || !onlyKeys(data, ["proposal_id", "approved"]) || !uuid(data.proposal_id) || ![void 0, "confirm", "status"].includes(payload.operation) || (payload.operation === "status" ? payload.status !== "completed" || data.approved !== null : typeof data.approved !== "boolean" || payload.status !== "completed" && data.approved)) throw invalid("Invalid V2 booking result.");
1336
+ } else if (!((_f = (_e = __privateGet(this, _options).capabilities) == null ? void 0 : _e.supported_actions) == null ? void 0 : _f.includes("slot_picker")) || !["dbos_signin_actions_v1", "dbos_signin_booking_v1", "dbos_signin_cta_v1"].includes(__privateGet(this, _options).run.protocol) || payload.operation !== void 0 || (payload.status === "completed" ? !onlyKeys(data, ["slot_id"]) || typeof data.slot_id !== "string" || !data.slot_id.length || data.slot_id.length > 256 : Object.keys(data).length > 0)) {
1337
+ throw invalid("Invalid V2 slot result.");
1338
+ }
1339
+ } else throw invalid("Unsupported V2 command.");
1340
+ __privateGet(this, _socket).send(serialized);
1341
+ __privateGet(this, _sentCommands).set(payload.turn_id, serialized);
1342
+ }
1343
+ };
1344
+ _options = new WeakMap();
1345
+ _socket = new WeakMap();
1346
+ _ctor = new WeakMap();
1347
+ _base = new WeakMap();
1348
+ _authenticated = new WeakMap();
1349
+ _lastTurn = new WeakMap();
1350
+ _cursor = new WeakMap();
1351
+ _sentCommands = new WeakMap();
1352
+ _generation = new WeakMap();
1353
+ _cleanup = new WeakMap();
1354
+ _cancelConnect = new WeakMap();
1355
+ _listeners = new WeakMap();
1356
+ _NativeV2WssClient_instances = new WeakSet();
1357
+ requireConnected_fn = function() {
1358
+ var _a;
1359
+ if (!__privateGet(this, _authenticated) || ((_a = __privateGet(this, _socket)) == null ? void 0 : _a.readyState) !== 1) throw invalid("V2 connection is not authenticated.");
1360
+ };
1361
+ validAuth_fn = function(value) {
1362
+ const expectedPatient = __privateGet(this, _options).identity.kind === "patient" ? __privateGet(this, _options).identity.patientId : null;
1363
+ return value.runtime === "dbos" && value.run_id === __privateGet(this, _options).run.run_id && value.protocol === __privateGet(this, _options).run.protocol && value.patient_id === expectedPatient && (value.last_turn_id === null || uuid(value.last_turn_id)) && cursor(value.last_event_seq) && value.last_event_seq >= __privateGet(this, _cursor) && Array.isArray(value.pending_actions) && value.pending_actions.every((action) => record(action) && uuid(action.action_id) && ["login", "slot_picker", "confirm"].includes(action.type) && record(action.payload)) && Array.isArray(value.agent_ids) && value.agent_ids.every(identity) && record(value.agent_names) && Object.values(value.agent_names).every((name) => typeof name === "string");
1364
+ };
1365
+ receive_fn = function(type, payload) {
1366
+ if (type === "ping") {
1367
+ __privateGet(this, _socket).send(JSON.stringify({ type: "pong" }));
1368
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "ping", payload);
1369
+ return;
1370
+ }
1371
+ if (type === "event_replay") {
1372
+ if (!Array.isArray(payload.events) || typeof payload.complete !== "boolean") return;
1373
+ const events = [];
1374
+ for (const frame of payload.events) {
1375
+ if (record(frame) && typeof frame.type === "string" && record(frame.payload) && !["auth_ok", "history", "event_replay", "ping", "close"].includes(frame.type) && cursor(frame.payload.event_seq) && frame.payload.event_seq > __privateGet(this, _cursor)) {
1376
+ events.push(frame);
1377
+ __privateMethod(this, _NativeV2WssClient_instances, receive_fn).call(this, frame.type, frame.payload);
1378
+ }
1379
+ }
1380
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "event_replay", { events, complete: payload.complete });
1381
+ return;
1382
+ }
1383
+ if (type === "turn_ack") {
1384
+ if (!uuid(payload.turn_id) || !cursor(payload.event_seq) || payload.event_seq < __privateGet(this, _cursor)) return;
1385
+ __privateSet(this, _lastTurn, payload.turn_id);
1386
+ __privateSet(this, _cursor, payload.event_seq);
1387
+ } else if (payload.event_seq !== void 0) {
1388
+ if (!cursor(payload.event_seq) || payload.event_seq <= __privateGet(this, _cursor)) return;
1389
+ __privateSet(this, _cursor, payload.event_seq);
1390
+ }
1391
+ if ([
1392
+ "history",
1393
+ "chat",
1394
+ "action_request",
1395
+ "turn_ack",
1396
+ "turn_started",
1397
+ "turn_completed",
1398
+ "activity",
1399
+ "transfer",
1400
+ "artifact_block",
1401
+ "notification",
1402
+ "response_suggestions",
1403
+ "error"
1404
+ ].includes(type)) {
1405
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, type, payload);
1406
+ }
1407
+ };
1408
+ dispatch_fn = function(type, payload) {
1409
+ var _a;
1410
+ for (const listener of [...(_a = __privateGet(this, _listeners).get(type)) != null ? _a : []]) {
1411
+ try {
1412
+ listener(payload);
1413
+ } catch {
1414
+ }
1415
+ }
1416
+ };
1417
+
992
1418
  // src/HCAmsSDK.ts
993
1419
  var HCAmsSDK = class {
994
1420
  constructor(config) {
@@ -1035,6 +1461,7 @@ var HCAmsSDK = class {
1035
1461
  };
1036
1462
  this.authHttp = new HttpClient(authState);
1037
1463
  this.ams = new AmsClient(this.http);
1464
+ this.v2 = new NativeV2Client(this.http);
1038
1465
  this.agents = new AgentsClient(this.http);
1039
1466
  this.departments = new DepartmentsClient(this.http);
1040
1467
  this.teams = new TeamsClient(this.http);
@@ -1067,6 +1494,18 @@ var HCAmsSDK = class {
1067
1494
  tenantId
1068
1495
  });
1069
1496
  }
1497
+ /** Native V2 transport. The existing connectAgentChat remains the V1 API. */
1498
+ connectV2AgentChat(options) {
1499
+ var _a, _b;
1500
+ const tenantId = (_a = options.tenantId) != null ? _a : this.state.tenantId;
1501
+ if (!tenantId) throw new Error("connectV2AgentChat requires a tenantId.");
1502
+ return new NativeV2WssClient({
1503
+ ...options,
1504
+ environment: this.state.environment,
1505
+ tenantId,
1506
+ baseUrlOverride: (_b = options.baseUrlOverride) != null ? _b : this.wssBaseUrl
1507
+ });
1508
+ }
1070
1509
  /** Get the current runtime environment. */
1071
1510
  get environment() {
1072
1511
  return this.state.environment;
@@ -1094,6 +1533,8 @@ var HCAmsSDK = class {
1094
1533
  DepartmentsClient,
1095
1534
  GuardrailsClient,
1096
1535
  HCAmsSDK,
1536
+ NativeV2Client,
1537
+ NativeV2WssClient,
1097
1538
  PoliciesClient,
1098
1539
  SDKError,
1099
1540
  SERVICE_NAME,