@healthcloudai/hc-ams 3.6.6 → 3.8.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/dist/index.js CHANGED
@@ -1,3 +1,20 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ 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);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+ var __privateWrapper = (obj, member, setter, getter) => ({
10
+ set _(value) {
11
+ __privateSet(obj, member, value, setter);
12
+ },
13
+ get _() {
14
+ return __privateGet(obj, member, getter);
15
+ }
16
+ });
17
+
1
18
  // src/config/SDKConfig.ts
2
19
  var SERVICE_NAME = "ams";
3
20
  var DEFAULT_TIMEOUT_MS = 3e4;
@@ -942,6 +959,474 @@ var WssClient = class {
942
959
  }
943
960
  };
944
961
 
962
+ // src/v2/validation.ts
963
+ function invalid(message) {
964
+ return new SDKError({ message, statusCode: 0 });
965
+ }
966
+ function record(value) {
967
+ return typeof value === "object" && value !== null && !Array.isArray(value);
968
+ }
969
+ function uuid(value) {
970
+ 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);
971
+ }
972
+ function identity(value) {
973
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
974
+ }
975
+ function protocol(value) {
976
+ return typeof value === "string" && [
977
+ "dbos_signin_v1",
978
+ "dbos_signin_cards_v1",
979
+ "dbos_signin_actions_v1",
980
+ "dbos_signin_booking_v1",
981
+ "dbos_signin_cta_v1"
982
+ ].includes(value);
983
+ }
984
+ function cursor(value) {
985
+ return Number.isSafeInteger(value) && value >= 0;
986
+ }
987
+ function ownedRun(value) {
988
+ 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) {
989
+ throw invalid("Invalid V2 run credentials or protocol.");
990
+ }
991
+ }
992
+ function onlyKeys(value, allowed) {
993
+ return Object.keys(value).every((key) => allowed.includes(key));
994
+ }
995
+ function capabilities(value) {
996
+ if (!record(value) || !onlyKeys(value, [
997
+ "platform",
998
+ "supported_actions",
999
+ "patient_flags_confirmation",
1000
+ "intake_confirmation",
1001
+ "encounter_confirmation",
1002
+ "locale",
1003
+ "time_zone"
1004
+ ])) return false;
1005
+ if (value.platform !== void 0 && !["web", "ios", "android", "terminal", "unknown"].includes(value.platform)) return false;
1006
+ 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;
1007
+ for (const key of ["patient_flags_confirmation", "intake_confirmation", "encounter_confirmation"]) {
1008
+ if (value[key] !== void 0 && typeof value[key] !== "boolean") return false;
1009
+ }
1010
+ return ["locale", "time_zone"].every((key) => value[key] === void 0 || typeof value[key] === "string" && value[key].length > 0 && value[key].length <= 128);
1011
+ }
1012
+
1013
+ // src/v2/NativeV2Client.ts
1014
+ var BINDING_UNKNOWN = "V2 patient binding outcome unknown; reconcile the original operation.";
1015
+ var NativeV2Client = class {
1016
+ constructor(http) {
1017
+ this.http = http;
1018
+ }
1019
+ async listPublicAgents(tenantId, options = {}) {
1020
+ if (!identity(tenantId)) throw invalid("Invalid V2 tenant identity.");
1021
+ const result = await this.request("GET", "/public/tenants/{tenant_id}/agents", tenantId, options);
1022
+ if (!record(result) || !Array.isArray(result.agents) || !result.agents.every((agent) => record(agent) && identity(agent.id) && typeof agent.name === "string" && protocol(agent.protocol))) {
1023
+ throw invalid("Invalid V2 public discovery response.");
1024
+ }
1025
+ return { agents: result.agents.map((agent) => ({ id: agent.id, name: agent.name, protocol: agent.protocol })) };
1026
+ }
1027
+ async createRun(tenantId, agentId, options = {}) {
1028
+ if (!identity(tenantId) || !identity(agentId)) throw invalid("Invalid V2 tenant or agent identity.");
1029
+ const result = await this.request("POST", "/public/tenants/{tenant_id}/agents/{agent_id}/runs", tenantId, options, agentId);
1030
+ ownedRun(result);
1031
+ return { run_id: result.run_id, run_secret: result.run_secret, protocol: result.protocol };
1032
+ }
1033
+ /**
1034
+ * Ordinary app sign-in. Close the socket after committed delivery first.
1035
+ * Sends once; callers retain the original UUID, claim and predecessor for retry.
1036
+ */
1037
+ async bindPatient(tenantId, agentId, runId, request, options) {
1038
+ let body;
1039
+ let headers;
1040
+ try {
1041
+ if (!record(request) || Object.keys(request).length !== 3 || !onlyKeys(request, ["operation_id", "run_secret", "expected_last_turn_id"]) || !record(options) || !onlyKeys(options, ["origin", "patientAccessToken"]) || !Object.prototype.hasOwnProperty.call(options, "patientAccessToken")) {
1042
+ throw invalid("Invalid V2 patient binding input.");
1043
+ }
1044
+ body = {
1045
+ operation_id: request.operation_id,
1046
+ run_secret: request.run_secret,
1047
+ expected_last_turn_id: request.expected_last_turn_id
1048
+ };
1049
+ const token = options.patientAccessToken;
1050
+ const origin = options.origin;
1051
+ if (!identity(tenantId) || !identity(agentId) || !uuid(runId) || !uuid(body.operation_id) || typeof body.run_secret !== "string" || !/^[A-Za-z0-9_-]{32,128}$/.test(body.run_secret) || !(body.expected_last_turn_id === null || uuid(body.expected_last_turn_id)) || typeof token !== "string" || !/^[!-~]{1,4096}$/.test(token)) {
1052
+ throw invalid("Invalid V2 patient binding input.");
1053
+ }
1054
+ headers = { Authorization: `Bearer ${token}` };
1055
+ if (origin !== void 0) {
1056
+ const parsed = new URL(origin);
1057
+ if (!["https:", "http:"].includes(parsed.protocol) || parsed.origin !== origin) {
1058
+ throw invalid("Invalid V2 patient binding input.");
1059
+ }
1060
+ headers.Origin = origin;
1061
+ }
1062
+ } catch {
1063
+ throw invalid("Invalid V2 patient binding input.");
1064
+ }
1065
+ let result;
1066
+ try {
1067
+ result = await this.http.request("POST", "/tenants/{tenant_id}/agents/{agent_id}/runs/{run_id}/patient-binding", {
1068
+ pathParams: { tenant_id: tenantId, agent_id: agentId, run_id: runId },
1069
+ auth: false,
1070
+ headers,
1071
+ body,
1072
+ timeoutMs: 1e4
1073
+ });
1074
+ } catch (error) {
1075
+ const code = error instanceof SDKError ? error.statusCode : 0;
1076
+ throw new SDKError({
1077
+ message: BINDING_UNKNOWN,
1078
+ statusCode: typeof code === "number" && Number.isInteger(code) && code >= 0 && code <= 599 ? code : 0
1079
+ });
1080
+ }
1081
+ if (!record(result) || result.status !== "bound" || !uuid(result.run_id) || result.run_id !== runId || !uuid(result.operation_id) || result.operation_id !== body.operation_id || typeof result.patient_id !== "string" || !/^[A-Za-z0-9_-]{1,160}$/.test(result.patient_id) || !(result.last_turn_id === null || uuid(result.last_turn_id)) || result.last_turn_id !== body.expected_last_turn_id) {
1082
+ throw new SDKError({ message: BINDING_UNKNOWN, statusCode: 0 });
1083
+ }
1084
+ return {
1085
+ status: "bound",
1086
+ run_id: result.run_id,
1087
+ operation_id: result.operation_id,
1088
+ patient_id: result.patient_id,
1089
+ last_turn_id: result.last_turn_id
1090
+ };
1091
+ }
1092
+ async request(method, path, tenantId, options, agentId) {
1093
+ if (options.origin !== void 0) {
1094
+ try {
1095
+ const parsed = new URL(options.origin);
1096
+ if (!["https:", "http:"].includes(parsed.protocol) || parsed.origin !== options.origin) throw invalid("Invalid V2 admission origin.");
1097
+ } catch {
1098
+ throw invalid("Invalid V2 admission origin.");
1099
+ }
1100
+ }
1101
+ try {
1102
+ return await this.http.request(method, path, {
1103
+ pathParams: { tenant_id: tenantId, ...agentId ? { agent_id: agentId } : {} },
1104
+ auth: false,
1105
+ ...method === "POST" ? { body: {} } : {},
1106
+ ...options.origin !== void 0 ? { headers: { Origin: options.origin } } : {}
1107
+ });
1108
+ } catch (error) {
1109
+ throw new SDKError({
1110
+ message: "V2 public admission request failed.",
1111
+ statusCode: error instanceof SDKError ? error.statusCode : 0
1112
+ });
1113
+ }
1114
+ }
1115
+ };
1116
+
1117
+ // src/v2/NativeV2WssClient.ts
1118
+ var _options, _socket, _ctor, _base, _authenticated, _lastTurn, _cursor, _sentCommands, _generation, _cleanup, _cancelConnect, _listeners, _NativeV2WssClient_instances, requireConnected_fn, validAuth_fn, receive_fn, dispatch_fn;
1119
+ var NativeV2WssClient = class {
1120
+ constructor(options) {
1121
+ __privateAdd(this, _NativeV2WssClient_instances);
1122
+ __privateAdd(this, _options);
1123
+ __privateAdd(this, _socket);
1124
+ __privateAdd(this, _ctor);
1125
+ __privateAdd(this, _base);
1126
+ __privateAdd(this, _authenticated, false);
1127
+ __privateAdd(this, _lastTurn, null);
1128
+ __privateAdd(this, _cursor);
1129
+ __privateAdd(this, _sentCommands, /* @__PURE__ */ new Map());
1130
+ __privateAdd(this, _generation, 0);
1131
+ __privateAdd(this, _cleanup);
1132
+ __privateAdd(this, _cancelConnect);
1133
+ __privateAdd(this, _listeners, /* @__PURE__ */ new Map());
1134
+ var _a, _b, _c, _d, _e, _f, _g;
1135
+ ownedRun(options.run);
1136
+ const owner = options.identity.kind === "anonymous" ? options.identity.sessionId : options.identity.patientId;
1137
+ 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.");
1138
+ 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.");
1139
+ assertTimeout((_c = options.authTimeoutMs) != null ? _c : 1e4, "authTimeoutMs");
1140
+ __privateSet(this, _base, normalizeWssBaseUrl((_d = options.baseUrlOverride) != null ? _d : resolveWssBaseUrl(options.environment)));
1141
+ const ctor = (_e = options.WebSocketImpl) != null ? _e : globalThis.WebSocket;
1142
+ if (!ctor) throw invalid("No WebSocket implementation available. Pass WebSocketImpl.");
1143
+ __privateSet(this, _ctor, ctor);
1144
+ __privateSet(this, _cursor, (_f = options.replaySince) != null ? _f : 0);
1145
+ __privateSet(this, _options, {
1146
+ ...options,
1147
+ run: { ...options.run },
1148
+ identity: { ...options.identity },
1149
+ capabilities: JSON.parse(JSON.stringify((_g = options.capabilities) != null ? _g : {}))
1150
+ });
1151
+ }
1152
+ get lastTurnId() {
1153
+ return __privateGet(this, _lastTurn);
1154
+ }
1155
+ get replaySince() {
1156
+ return __privateGet(this, _cursor);
1157
+ }
1158
+ on(type, listener) {
1159
+ if (!__privateGet(this, _listeners).has(type)) __privateGet(this, _listeners).set(type, /* @__PURE__ */ new Set());
1160
+ const entry = listener;
1161
+ __privateGet(this, _listeners).get(type).add(entry);
1162
+ return () => {
1163
+ var _a;
1164
+ (_a = __privateGet(this, _listeners).get(type)) == null ? void 0 : _a.delete(entry);
1165
+ };
1166
+ }
1167
+ connect() {
1168
+ var _a;
1169
+ if (__privateGet(this, _socket) && __privateGet(this, _socket).readyState < 2) return Promise.reject(invalid("V2 connection is already active."));
1170
+ (_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
1171
+ __privateSet(this, _authenticated, false);
1172
+ const generation = ++__privateWrapper(this, _generation)._;
1173
+ const options = __privateGet(this, _options);
1174
+ const owner = options.identity.kind === "anonymous" ? options.identity.sessionId : options.identity.patientId;
1175
+ const url = new URL(joinServiceUrl(__privateGet(this, _base), `/ws/agents/${encodeURIComponent(options.agentId)}/chat`));
1176
+ url.searchParams.set("session_id", `${options.tenantId}/${owner}`);
1177
+ url.searchParams.set("transport", options.run.protocol);
1178
+ url.searchParams.set("run_id", options.run.run_id);
1179
+ url.searchParams.set("replay_since", String(__privateGet(this, _cursor)));
1180
+ if (options.identity.kind === "anonymous") url.searchParams.set("anonymous", "1");
1181
+ if (options.lang) url.searchParams.set("lang", options.lang);
1182
+ return new Promise((resolve, reject) => {
1183
+ var _a2;
1184
+ let socket;
1185
+ try {
1186
+ socket = new (__privateGet(this, _ctor))(url.toString());
1187
+ } catch {
1188
+ reject(invalid("V2 connection could not be opened."));
1189
+ return;
1190
+ }
1191
+ __privateSet(this, _socket, socket);
1192
+ let settled = false;
1193
+ let authSent = false;
1194
+ const current = () => generation === __privateGet(this, _generation) && socket === __privateGet(this, _socket);
1195
+ const timer = setTimeout(() => fail("Authentication timed out."), (_a2 = options.authTimeoutMs) != null ? _a2 : 1e4);
1196
+ const cleanup = () => {
1197
+ clearTimeout(timer);
1198
+ socket.removeEventListener("open", onOpen);
1199
+ socket.removeEventListener("message", onMessage);
1200
+ socket.removeEventListener("close", onClose);
1201
+ socket.removeEventListener("error", onError);
1202
+ };
1203
+ const fail = (message) => {
1204
+ if (!current()) return;
1205
+ clearTimeout(timer);
1206
+ if (!settled) {
1207
+ settled = true;
1208
+ reject(invalid(message));
1209
+ } else __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "error", { code: "v2_transport_error", message });
1210
+ __privateSet(this, _authenticated, false);
1211
+ cleanup();
1212
+ __privateSet(this, _cancelConnect, void 0);
1213
+ socket.close();
1214
+ };
1215
+ const onOpen = () => {
1216
+ void (async () => {
1217
+ try {
1218
+ const token = options.identity.kind === "patient" ? await options.identity.getAccessToken() : "";
1219
+ if (!current() || settled || socket.readyState !== 1) return;
1220
+ if (typeof token !== "string" || token.length > 4096 || options.identity.kind === "patient" && !token) throw invalid("Invalid V2 access token.");
1221
+ socket.send(JSON.stringify({
1222
+ type: "auth",
1223
+ token,
1224
+ run_id: options.run.run_id,
1225
+ run_secret: options.run.run_secret,
1226
+ client: options.capabilities,
1227
+ ...options.identity.kind === "patient" ? { patient_id: options.identity.patientId } : {}
1228
+ }));
1229
+ authSent = true;
1230
+ } catch {
1231
+ fail("V2 authentication credentials could not be resolved.");
1232
+ }
1233
+ })();
1234
+ };
1235
+ const onMessage = (event) => {
1236
+ if (!current()) return;
1237
+ let frame;
1238
+ try {
1239
+ if (typeof event.data !== "string" || event.data.length > 2 * 1024 * 1024) throw invalid("Invalid V2 frame.");
1240
+ frame = JSON.parse(event.data);
1241
+ if (!record(frame) || typeof frame.type !== "string" || !record(frame.payload)) throw invalid("Invalid V2 frame.");
1242
+ } catch {
1243
+ fail("Invalid V2 server message.");
1244
+ return;
1245
+ }
1246
+ if (!__privateGet(this, _authenticated)) {
1247
+ if (frame.type === "error") {
1248
+ fail("V2 authentication failed.");
1249
+ return;
1250
+ }
1251
+ if (frame.type !== "auth_ok") return;
1252
+ if (!authSent || !__privateMethod(this, _NativeV2WssClient_instances, validAuth_fn).call(this, frame.payload)) {
1253
+ fail("Invalid V2 authentication response.");
1254
+ return;
1255
+ }
1256
+ const metadata = frame.payload;
1257
+ __privateSet(this, _lastTurn, metadata.last_turn_id);
1258
+ __privateSet(this, _authenticated, true);
1259
+ clearTimeout(timer);
1260
+ settled = true;
1261
+ __privateSet(this, _cancelConnect, void 0);
1262
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "auth_ok", metadata);
1263
+ resolve(metadata);
1264
+ return;
1265
+ }
1266
+ if (frame.type === "auth_ok") {
1267
+ fail("Unexpected V2 authentication response.");
1268
+ return;
1269
+ }
1270
+ __privateMethod(this, _NativeV2WssClient_instances, receive_fn).call(this, frame.type, frame.payload);
1271
+ };
1272
+ const onClose = (event) => {
1273
+ if (!current()) return;
1274
+ cleanup();
1275
+ __privateSet(this, _authenticated, false);
1276
+ __privateSet(this, _cancelConnect, void 0);
1277
+ if (!settled) {
1278
+ settled = true;
1279
+ reject(invalid("V2 connection closed before authentication."));
1280
+ }
1281
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "close", { code: event.code });
1282
+ };
1283
+ const onError = () => fail("V2 connection failed.");
1284
+ __privateSet(this, _cancelConnect, () => {
1285
+ if (!settled) {
1286
+ settled = true;
1287
+ reject(invalid("V2 connection closed before authentication."));
1288
+ }
1289
+ });
1290
+ __privateSet(this, _cleanup, cleanup);
1291
+ socket.addEventListener("open", onOpen);
1292
+ socket.addEventListener("message", onMessage);
1293
+ socket.addEventListener("close", onClose);
1294
+ socket.addEventListener("error", onError);
1295
+ });
1296
+ }
1297
+ close() {
1298
+ var _a, _b, _c;
1299
+ (_a = __privateGet(this, _cancelConnect)) == null ? void 0 : _a.call(this);
1300
+ __privateSet(this, _cancelConnect, void 0);
1301
+ ++__privateWrapper(this, _generation)._;
1302
+ (_b = __privateGet(this, _cleanup)) == null ? void 0 : _b.call(this);
1303
+ __privateSet(this, _cleanup, void 0);
1304
+ __privateSet(this, _authenticated, false);
1305
+ (_c = __privateGet(this, _socket)) == null ? void 0 : _c.close();
1306
+ __privateSet(this, _socket, void 0);
1307
+ }
1308
+ sendChat(payload) {
1309
+ const command = { type: "chat", payload: { ...payload } };
1310
+ this.sendCommand(command);
1311
+ return command;
1312
+ }
1313
+ sendActionResult(payload) {
1314
+ this.sendCommand({ type: "action_result", payload });
1315
+ }
1316
+ /** Offered-login socket binding; ordinary app sign-in uses its separate HTTP contract. */
1317
+ bindPatient(payload) {
1318
+ this.sendCommand({ type: "bind_patient", payload });
1319
+ }
1320
+ /** Explicit retries resend the caller's original command identity and terms. */
1321
+ sendCommand(command) {
1322
+ var _a, _b, _c, _d, _e, _f;
1323
+ __privateMethod(this, _NativeV2WssClient_instances, requireConnected_fn).call(this);
1324
+ if (!record(command) || !onlyKeys(command, ["type", "payload"]) || !record(command.payload)) {
1325
+ throw invalid("Invalid V2 command.");
1326
+ }
1327
+ const payload = command.payload;
1328
+ const serialized = JSON.stringify(command);
1329
+ const original = __privateGet(this, _sentCommands).get(payload.turn_id);
1330
+ 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))) {
1331
+ throw invalid("Invalid V2 command identity or predecessor.");
1332
+ }
1333
+ if (command.type === "chat") {
1334
+ 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.");
1335
+ if (payload.cta_confirmation !== void 0) {
1336
+ const choice = payload.cta_confirmation;
1337
+ 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.");
1338
+ }
1339
+ } else if (command.type === "bind_patient") {
1340
+ 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.");
1341
+ 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.");
1342
+ } else if (command.type === "action_result") {
1343
+ 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.");
1344
+ const data = payload.data;
1345
+ if ("proposal_id" in data) {
1346
+ 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.");
1347
+ 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.");
1348
+ } 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)) {
1349
+ throw invalid("Invalid V2 slot result.");
1350
+ }
1351
+ } else throw invalid("Unsupported V2 command.");
1352
+ __privateGet(this, _socket).send(serialized);
1353
+ __privateGet(this, _sentCommands).set(payload.turn_id, serialized);
1354
+ }
1355
+ };
1356
+ _options = new WeakMap();
1357
+ _socket = new WeakMap();
1358
+ _ctor = new WeakMap();
1359
+ _base = new WeakMap();
1360
+ _authenticated = new WeakMap();
1361
+ _lastTurn = new WeakMap();
1362
+ _cursor = new WeakMap();
1363
+ _sentCommands = new WeakMap();
1364
+ _generation = new WeakMap();
1365
+ _cleanup = new WeakMap();
1366
+ _cancelConnect = new WeakMap();
1367
+ _listeners = new WeakMap();
1368
+ _NativeV2WssClient_instances = new WeakSet();
1369
+ requireConnected_fn = function() {
1370
+ var _a;
1371
+ if (!__privateGet(this, _authenticated) || ((_a = __privateGet(this, _socket)) == null ? void 0 : _a.readyState) !== 1) throw invalid("V2 connection is not authenticated.");
1372
+ };
1373
+ validAuth_fn = function(value) {
1374
+ const expectedPatient = __privateGet(this, _options).identity.kind === "patient" ? __privateGet(this, _options).identity.patientId : null;
1375
+ 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");
1376
+ };
1377
+ receive_fn = function(type, payload) {
1378
+ if (type === "ping") {
1379
+ __privateGet(this, _socket).send(JSON.stringify({ type: "pong" }));
1380
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "ping", payload);
1381
+ return;
1382
+ }
1383
+ if (type === "event_replay") {
1384
+ if (!Array.isArray(payload.events) || typeof payload.complete !== "boolean") return;
1385
+ const events = [];
1386
+ for (const frame of payload.events) {
1387
+ 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)) {
1388
+ events.push(frame);
1389
+ __privateMethod(this, _NativeV2WssClient_instances, receive_fn).call(this, frame.type, frame.payload);
1390
+ }
1391
+ }
1392
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, "event_replay", { events, complete: payload.complete });
1393
+ return;
1394
+ }
1395
+ if (type === "turn_ack") {
1396
+ if (!uuid(payload.turn_id) || !cursor(payload.event_seq) || payload.event_seq < __privateGet(this, _cursor)) return;
1397
+ __privateSet(this, _lastTurn, payload.turn_id);
1398
+ __privateSet(this, _cursor, payload.event_seq);
1399
+ } else if (payload.event_seq !== void 0) {
1400
+ if (!cursor(payload.event_seq) || payload.event_seq <= __privateGet(this, _cursor)) return;
1401
+ __privateSet(this, _cursor, payload.event_seq);
1402
+ }
1403
+ if ([
1404
+ "history",
1405
+ "chat",
1406
+ "action_request",
1407
+ "turn_ack",
1408
+ "turn_started",
1409
+ "turn_completed",
1410
+ "activity",
1411
+ "transfer",
1412
+ "artifact_block",
1413
+ "notification",
1414
+ "response_suggestions",
1415
+ "error"
1416
+ ].includes(type)) {
1417
+ __privateMethod(this, _NativeV2WssClient_instances, dispatch_fn).call(this, type, payload);
1418
+ }
1419
+ };
1420
+ dispatch_fn = function(type, payload) {
1421
+ var _a;
1422
+ for (const listener of [...(_a = __privateGet(this, _listeners).get(type)) != null ? _a : []]) {
1423
+ try {
1424
+ listener(payload);
1425
+ } catch {
1426
+ }
1427
+ }
1428
+ };
1429
+
945
1430
  // src/HCAmsSDK.ts
946
1431
  var HCAmsSDK = class {
947
1432
  constructor(config) {
@@ -988,6 +1473,7 @@ var HCAmsSDK = class {
988
1473
  };
989
1474
  this.authHttp = new HttpClient(authState);
990
1475
  this.ams = new AmsClient(this.http);
1476
+ this.v2 = new NativeV2Client(this.http);
991
1477
  this.agents = new AgentsClient(this.http);
992
1478
  this.departments = new DepartmentsClient(this.http);
993
1479
  this.teams = new TeamsClient(this.http);
@@ -1020,6 +1506,18 @@ var HCAmsSDK = class {
1020
1506
  tenantId
1021
1507
  });
1022
1508
  }
1509
+ /** Native V2 transport. The existing connectAgentChat remains the V1 API. */
1510
+ connectV2AgentChat(options) {
1511
+ var _a, _b;
1512
+ const tenantId = (_a = options.tenantId) != null ? _a : this.state.tenantId;
1513
+ if (!tenantId) throw new Error("connectV2AgentChat requires a tenantId.");
1514
+ return new NativeV2WssClient({
1515
+ ...options,
1516
+ environment: this.state.environment,
1517
+ tenantId,
1518
+ baseUrlOverride: (_b = options.baseUrlOverride) != null ? _b : this.wssBaseUrl
1519
+ });
1520
+ }
1023
1521
  /** Get the current runtime environment. */
1024
1522
  get environment() {
1025
1523
  return this.state.environment;
@@ -1046,6 +1544,8 @@ export {
1046
1544
  DepartmentsClient,
1047
1545
  GuardrailsClient,
1048
1546
  HCAmsSDK,
1547
+ NativeV2Client,
1548
+ NativeV2WssClient,
1049
1549
  PoliciesClient,
1050
1550
  SDKError,
1051
1551
  SERVICE_NAME,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@healthcloudai/hc-ams",
3
- "version": "3.6.6",
3
+ "version": "3.8.0",
4
4
  "description": "HealthCloud AMS SDK \u2014 application-agent discovery for AMS Services.",
5
5
  "author": "Healthcheck Systems Inc",
6
6
  "license": "MIT",