@healthcloudai/hc-ams 3.6.4 → 3.6.5

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
@@ -228,8 +228,47 @@ notifications, and activity.
228
228
 
229
229
  | Option | Description |
230
230
  | --- | --- |
231
- | `environment` | `"dev"` \| `"uat"` \| `"prod"` — resolves the AMS base URL (`{env-}amsservices.health.cloud/api/ams`, no prefix for `prod`). |
231
+ | `environment` | `"dev"` \| `"uat"` \| `"prod"`. DEV uses AWS `https://dev-ams-services.health.cloud`; UAT retains `https://uat-amsservices.health.cloud`, PROD retains `https://amsservices.health.cloud`. |
232
232
  | `tenantId` | Optional default tenant ID, used by `connectAgentChat` when no `tenantId` is passed per-call. |
233
233
  | `accessToken` | Optional Tenant Admin bearer token for authenticated REST methods. |
234
- | `baseUrlOverride` | Overrides the resolved AMS base URL (e.g. for local/staging testing). |
234
+ | `baseUrlOverride` | Complete AMS API base including `/api/ams` (or a custom API mount). Used by every public/admin REST client. Its origin also selects the default WebSocket origin. |
235
+ | `authBaseUrlOverride` | Independent AMS auth base including `/api/auth`. Otherwise uses the configured environment's auth endpoint; changing the API URL never silently changes the login target. |
236
+ | `wssBaseUrlOverride` | Explicit WebSocket base, optionally including a proxy prefix, without `/ws`. Overrides the origin derived from the API base. A per-chat `baseUrlOverride` takes precedence. |
235
237
  | `timeout` | Request timeout in milliseconds. Defaults to 30000. |
238
+
239
+ DEV defaults are `https://dev-ams-services.health.cloud/api/ams` for REST,
240
+ `https://dev-ams-services.health.cloud/api/auth` for AMS authentication, and
241
+ `wss://dev-ams-services.health.cloud` for WebSocket chat. There is no fallback
242
+ to the former DigitalOcean DEV host.
243
+
244
+ ```ts
245
+ const sdk = new HCAmsSDK({
246
+ environment: "dev",
247
+ baseUrlOverride: "https://api.example.test/proxy/api/ams/",
248
+ authBaseUrlOverride: "https://identity.example.test/api/auth/",
249
+ wssBaseUrlOverride: "wss://runtime.example.test/proxy/",
250
+ });
251
+ ```
252
+
253
+ These are placeholder hosts. Overrides are validated and copied at construction;
254
+ changing the input object later does not retarget the SDK. API base paths are
255
+ retained, trailing slashes normalized, and auth requests use their own base path.
256
+ Without an explicit WS base, a selected API `https://host/proxy/api/ams` uses
257
+ `wss://host/ws`; API mount paths are not assumed to be WebSocket proxy prefixes.
258
+ Use `wssBaseUrlOverride` when a deployment mounts WebSocket under a prefix.
259
+
260
+ URL rules match the main Python/npm SDKs: HTTPS/WSS, with HTTP/WS allowed only
261
+ on literal loopback `127.0.0.1` or `[::1]`. Credential-bearing URLs, query strings,
262
+ fragments, controls, ambiguous hosts and unsafe paths fail before networking,
263
+ without echoing the input. TLS verification remains enabled. HTTP redirects are
264
+ refused before following them; redirect bodies and Location headers are not
265
+ included in SDK errors. Native WebSocket TLS/redirect behavior is verified in
266
+ Node; custom WebSocket implementations must preserve those guarantees.
267
+
268
+ **Compatibility:** existing `baseUrlOverride` and per-chat `baseUrlOverride`
269
+ remain supported. Previously the API override was incorrectly reused as an auth
270
+ base, so an API base ending `/api/ams` produced `/api/ams/login`. That behavior
271
+ is fixed. Callers intentionally overriding authentication must now explicitly
272
+ set `authBaseUrlOverride`; selecting another API server leaves the environment's
273
+ auth target unchanged. An API override now also selects the WebSocket origin
274
+ unless an SDK/per-chat WS override is provided. UAT/PROD defaults are unchanged.
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  assertEnvironment: () => assertEnvironment,
40
40
  assertTimeout: () => assertTimeout,
41
41
  resolveAmsAuthBaseUrl: () => resolveAmsAuthBaseUrl,
42
+ resolveAmsOrigin: () => resolveAmsOrigin,
42
43
  resolveBaseUrl: () => resolveBaseUrl,
43
44
  resolveWssBaseUrl: () => resolveWssBaseUrl
44
45
  });
@@ -47,17 +48,20 @@ module.exports = __toCommonJS(index_exports);
47
48
  // src/config/SDKConfig.ts
48
49
  var SERVICE_NAME = "ams";
49
50
  var DEFAULT_TIMEOUT_MS = 3e4;
50
- function resolveBaseUrl(environment) {
51
+ function resolveAmsOrigin(environment) {
52
+ assertEnvironment(environment);
53
+ if (environment === "dev") return "https://dev-ams-services.health.cloud";
51
54
  const prefix = environment === "prod" ? "" : `${environment}-`;
52
- return `https://${prefix}amsservices.health.cloud/api/ams`;
55
+ return `https://${prefix}amsservices.health.cloud`;
56
+ }
57
+ function resolveBaseUrl(environment) {
58
+ return `${resolveAmsOrigin(environment)}/api/ams`;
53
59
  }
54
60
  function resolveAmsAuthBaseUrl(environment) {
55
- const prefix = environment === "prod" ? "" : `${environment}-`;
56
- return `https://${prefix}amsservices.health.cloud/api/auth`;
61
+ return `${resolveAmsOrigin(environment)}/api/auth`;
57
62
  }
58
63
  function resolveWssBaseUrl(environment) {
59
- const prefix = environment === "prod" ? "" : `${environment}-`;
60
- return `wss://${prefix}amsservices.health.cloud`;
64
+ return resolveAmsOrigin(environment).replace(/^https:/, "wss:");
61
65
  }
62
66
  function assertEnvironment(environment) {
63
67
  if (environment !== "dev" && environment !== "uat" && environment !== "prod") {
@@ -70,6 +74,65 @@ function assertTimeout(timeout, label = "timeout") {
70
74
  }
71
75
  }
72
76
 
77
+ // src/config/ServiceUrls.ts
78
+ function normalizeBaseUrl(value) {
79
+ const message = "Invalid service base URL: expected HTTPS (or literal loopback HTTP); no credentials, query or fragment";
80
+ try {
81
+ if (typeof value !== "string" || /[^\x21-\x7e]|[\\?#]/.test(value) || !/^https?:\/\//i.test(value)) {
82
+ throw new Error();
83
+ }
84
+ const authority = value.slice(value.indexOf("://") + 3).split("/")[0];
85
+ if (!authority || /[@%]/.test(authority) || authority.endsWith(":")) throw new Error();
86
+ const url = new URL(value);
87
+ const host = url.hostname;
88
+ const allowedScheme = url.protocol === "https:" || url.protocol === "http:" && (host === "127.0.0.1" || host === "[::1]");
89
+ if (!allowedScheme || !host || url.username || url.password || url.port && Number(url.port) < 1) {
90
+ throw new Error();
91
+ }
92
+ if (!host.startsWith("[") && (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host) || host.split(".").some(
93
+ (label) => !label || label.length > 63 || label.startsWith("-") || label.endsWith("-")
94
+ ))) throw new Error();
95
+ const rawHost = authority.startsWith("[") ? authority.slice(0, authority.indexOf("]") + 1) : authority.split(":")[0];
96
+ if (!host.startsWith("[") && host !== rawHost.toLowerCase()) throw new Error();
97
+ const rawPath = value.slice(value.indexOf("://") + 3 + authority.length);
98
+ if (rawPath.includes("//") || /%(?![0-9a-f]{2})|%2f/i.test(rawPath)) throw new Error();
99
+ const decoded = decodePathBytes(rawPath);
100
+ if (hasControls(decoded) || /[\\?#%]/.test(decoded) || decoded.split("/").some((s) => s === "." || s === "..")) {
101
+ throw new Error();
102
+ }
103
+ return `${url.origin}${rawPath.replace(/\/+$/, "")}`;
104
+ } catch {
105
+ throw new Error(message);
106
+ }
107
+ }
108
+ function joinServiceUrl(base, path) {
109
+ if (hasControls(path) || /[\\?#]/.test(path) || path.includes("://") || path.startsWith("//") || path.split("/").some((segment) => {
110
+ const decoded = decodePathBytes(segment);
111
+ return decoded === "." || decoded === "..";
112
+ })) throw new Error("Invalid service request path");
113
+ return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
114
+ }
115
+ function normalizeWssBaseUrl(value) {
116
+ if (typeof value !== "string" || !/^wss?:\/\//i.test(value)) {
117
+ throw new Error("Invalid WebSocket base URL: expected WSS (or literal loopback WS)");
118
+ }
119
+ try {
120
+ return normalizeBaseUrl(value.replace(/^wss:/i, "https:").replace(/^ws:/i, "http:")).replace(/^https:/, "wss:").replace(/^http:/, "ws:");
121
+ } catch {
122
+ throw new Error("Invalid WebSocket base URL: expected WSS (or literal loopback WS)");
123
+ }
124
+ }
125
+ function wssBaseForApi(base) {
126
+ const url = new URL(normalizeBaseUrl(base));
127
+ return url.origin.replace(/^https:/, "wss:").replace(/^http:/, "ws:");
128
+ }
129
+ function hasControls(value) {
130
+ return Array.from(value).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
131
+ }
132
+ function decodePathBytes(value) {
133
+ return value.replace(/%([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
134
+ }
135
+
73
136
  // src/errors/SDKError.ts
74
137
  var SDKError = class extends Error {
75
138
  constructor(params) {
@@ -88,12 +151,15 @@ var SDKError = class extends Error {
88
151
  var HttpClient = class {
89
152
  constructor(state) {
90
153
  this.state = state;
154
+ this.baseUrl = normalizeBaseUrl(
155
+ state.baseUrlOverride === void 0 ? resolveBaseUrl(state.environment) : state.baseUrlOverride
156
+ );
91
157
  }
92
158
  async request(method, path, options = {}) {
93
159
  var _a, _b;
94
160
  const url = this.buildUrl(path, options);
95
161
  const headers = this.buildHeaders(options);
96
- const init = { method, headers };
162
+ const init = { method, headers, redirect: "error" };
97
163
  if (method !== "GET" && method !== "DELETE" && options.body !== void 0) {
98
164
  init.body = this.serializeBody(options.body, headers);
99
165
  }
@@ -110,6 +176,9 @@ var HttpClient = class {
110
176
  let payload;
111
177
  try {
112
178
  response = await fetch(url, init);
179
+ if (response.redirected || response.status >= 300 && response.status < 400 || response.type === "opaqueredirect") {
180
+ throw new SDKError({ message: "Service redirects are not allowed", statusCode: response.status });
181
+ }
113
182
  payload = await this.parseResponse(response);
114
183
  } catch (error) {
115
184
  if (didTimeout) {
@@ -123,7 +192,7 @@ var HttpClient = class {
123
192
  throw error;
124
193
  }
125
194
  throw new SDKError({
126
- message: error instanceof Error ? error.message : "Network request failed.",
195
+ message: "Network request failed.",
127
196
  statusCode: 0,
128
197
  cause: error
129
198
  });
@@ -157,10 +226,9 @@ var HttpClient = class {
157
226
  return headers;
158
227
  }
159
228
  buildUrl(path, options) {
160
- var _a, _b;
229
+ var _a;
161
230
  const normalizedPath = this.resolvePath(path, (_a = options.pathParams) != null ? _a : {});
162
- const base = (_b = this.state.baseUrlOverride) != null ? _b : resolveBaseUrl(this.state.environment);
163
- const url = new URL(`${base}${normalizedPath}`);
231
+ const url = new URL(joinServiceUrl(this.baseUrl, normalizedPath));
164
232
  if (options.query) {
165
233
  for (const [key, value] of Object.entries(options.query)) {
166
234
  this.appendQuery(url, key, value);
@@ -649,17 +717,19 @@ var WssClient = class {
649
717
  // Storage is necessarily untyped across the heterogeneous event map; `on`/`dispatch` restore type safety at the boundary.
650
718
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
651
719
  this.listeners = /* @__PURE__ */ new Map();
652
- var _a, _b, _c, _d;
720
+ var _a, _b, _c;
653
721
  if (options.healthcloudToken === void 0 && options.getAccessToken === void 0) {
654
722
  throw new SDKError({
655
723
  message: "WssClient requires either `healthcloudToken` or `getAccessToken`.",
656
724
  statusCode: 0
657
725
  });
658
726
  }
659
- const base = (_a = options.baseUrlOverride) != null ? _a : resolveWssBaseUrl(options.environment);
727
+ const base = normalizeWssBaseUrl(
728
+ options.baseUrlOverride === void 0 ? resolveWssBaseUrl(options.environment) : options.baseUrlOverride
729
+ );
660
730
  const sessionId = `${options.tenantId}/${options.patientId}`;
661
731
  const path = options.agentId ? `/ws/agents/${encodeURIComponent(options.agentId)}/chat` : "/ws";
662
- const url = new URL(`${base}${path}`);
732
+ const url = new URL(joinServiceUrl(base, path));
663
733
  url.searchParams.set("session_id", sessionId);
664
734
  if (options.lang) url.searchParams.set("lang", options.lang);
665
735
  if (options.voice) url.searchParams.set("voice", "1");
@@ -670,9 +740,9 @@ var WssClient = class {
670
740
  url.searchParams.set("handoff", JSON.stringify(options.handoff));
671
741
  }
672
742
  this.url = url.toString();
673
- this.turnTimeoutMs = (_b = options.turnTimeoutMs) != null ? _b : 6e4;
674
- this.authTimeoutMs = (_c = options.authTimeoutMs) != null ? _c : 1e4;
675
- const ctor = (_d = options.WebSocketImpl) != null ? _d : globalThis.WebSocket;
743
+ this.turnTimeoutMs = (_a = options.turnTimeoutMs) != null ? _a : 6e4;
744
+ this.authTimeoutMs = (_b = options.authTimeoutMs) != null ? _b : 1e4;
745
+ const ctor = (_c = options.WebSocketImpl) != null ? _c : globalThis.WebSocket;
676
746
  if (!ctor) {
677
747
  throw new SDKError({
678
748
  message: 'No WebSocket implementation available. Pass `WebSocketImpl` (e.g. `new WssClient({ ..., WebSocketImpl: require("ws") })`) on runtimes without a global WebSocket (Node < 21).',
@@ -922,18 +992,26 @@ var WssClient = class {
922
992
  // src/HCAmsSDK.ts
923
993
  var HCAmsSDK = class {
924
994
  constructor(config) {
925
- var _a, _b, _c;
995
+ var _a, _b;
926
996
  assertEnvironment(config.environment);
927
997
  assertTimeout((_a = config.timeout) != null ? _a : DEFAULT_TIMEOUT_MS);
998
+ const apiBase = normalizeBaseUrl(
999
+ config.baseUrlOverride === void 0 ? resolveBaseUrl(config.environment) : config.baseUrlOverride
1000
+ );
1001
+ const authBase = normalizeBaseUrl(
1002
+ config.authBaseUrlOverride === void 0 ? resolveAmsAuthBaseUrl(config.environment) : config.authBaseUrlOverride
1003
+ );
1004
+ this.wssBaseUrl = normalizeWssBaseUrl(
1005
+ config.wssBaseUrlOverride === void 0 ? wssBaseForApi(apiBase) : config.wssBaseUrlOverride
1006
+ );
928
1007
  this.state = {
929
1008
  environment: config.environment,
930
1009
  tenantId: config.tenantId,
931
1010
  accessToken: config.accessToken,
932
- baseUrlOverride: config.baseUrlOverride,
1011
+ baseUrlOverride: apiBase,
933
1012
  timeout: (_b = config.timeout) != null ? _b : DEFAULT_TIMEOUT_MS
934
1013
  };
935
1014
  this.http = new HttpClient(this.state);
936
- const authBaseUrlOverride = (_c = config.baseUrlOverride) != null ? _c : resolveAmsAuthBaseUrl(config.environment);
937
1015
  const state = this.state;
938
1016
  const authState = {
939
1017
  get environment() {
@@ -949,7 +1027,7 @@ var HCAmsSDK = class {
949
1027
  state.accessToken = value;
950
1028
  },
951
1029
  get baseUrlOverride() {
952
- return authBaseUrlOverride;
1030
+ return authBase;
953
1031
  },
954
1032
  get timeout() {
955
1033
  return state.timeout;
@@ -984,6 +1062,7 @@ var HCAmsSDK = class {
984
1062
  }
985
1063
  return new WssClient({
986
1064
  ...options,
1065
+ baseUrlOverride: options.baseUrlOverride === void 0 ? this.wssBaseUrl : options.baseUrlOverride,
987
1066
  environment: this.state.environment,
988
1067
  tenantId
989
1068
  });
@@ -1026,6 +1105,7 @@ var HCAmsSDK = class {
1026
1105
  assertEnvironment,
1027
1106
  assertTimeout,
1028
1107
  resolveAmsAuthBaseUrl,
1108
+ resolveAmsOrigin,
1029
1109
  resolveBaseUrl,
1030
1110
  resolveWssBaseUrl
1031
1111
  });
package/dist/index.d.cts CHANGED
@@ -8,6 +8,10 @@ interface AmsSDKConfig {
8
8
  accessToken?: string;
9
9
  /** Overrides the resolved AMS base URL for this SDK instance. */
10
10
  baseUrlOverride?: string;
11
+ /** Independent AMS auth base, including /api/auth; API overrides never retarget login. */
12
+ authBaseUrlOverride?: string;
13
+ /** WSS base (optional proxy prefix). Otherwise follows the selected API origin. */
14
+ wssBaseUrlOverride?: string;
11
15
  /** Request timeout in milliseconds. Defaults to 30000 (30s). */
12
16
  timeout?: number;
13
17
  }
@@ -20,10 +24,10 @@ interface SDKRuntimeState {
20
24
  }
21
25
  declare const DEFAULT_TIMEOUT_MS = 30000;
22
26
  /**
23
- * AMS Services hosts itself at `{env-}amsservices.health.cloud/api/ams`,
24
- * unlike the `{env-}api-<service>.health.cloud` pattern other HealthCloud
25
- * services use — mirrors `resolveBaseUrl` in packages/npm/src/config/SDKConfig.ts.
27
+ * DEV uses the AWS AMS deployment. UAT/PROD retain their existing configuration;
28
+ * all three AMS endpoint families use the same environment origin.
26
29
  */
30
+ declare function resolveAmsOrigin(environment: Environment): string;
27
31
  declare function resolveBaseUrl(environment: Environment): string;
28
32
  /**
29
33
  * AMS mounts its tenant-admin auth routes (`/api/auth/*`) alongside, not
@@ -62,6 +66,7 @@ interface HttpRequestOptions {
62
66
 
63
67
  declare class HttpClient {
64
68
  private readonly state;
69
+ private readonly baseUrl;
65
70
  constructor(state: SDKRuntimeState);
66
71
  request<TResponse>(method: HttpMethod, path: string, options?: HttpRequestOptions): Promise<TResponse>;
67
72
  private buildHeaders;
@@ -903,7 +908,7 @@ interface WssClientOptions {
903
908
  getAccessToken?: () => string | Promise<string>;
904
909
  /** Omit to connect via the tenant's default agent (`/ws`). */
905
910
  agentId?: string;
906
- /** Overrides the resolved WSS base URL (scheme + host, no path). */
911
+ /** Overrides the resolved WSS base URL (optional proxy prefix, without /ws). */
907
912
  baseUrlOverride?: string;
908
913
  /** Defaults to `globalThis.WebSocket`. Required on Node &lt; 21. */
909
914
  WebSocketImpl?: WebSocketImpl;
@@ -991,6 +996,7 @@ declare class HCAmsSDK {
991
996
  private readonly state;
992
997
  private readonly http;
993
998
  private readonly authHttp;
999
+ private readonly wssBaseUrl;
994
1000
  /** AMS application-agent discovery (public). */
995
1001
  readonly ams: AmsClient;
996
1002
  /** Agent CRUD, transfer candidates, conversation history. */
@@ -1046,4 +1052,4 @@ declare class SDKError extends Error {
1046
1052
  toString(): string;
1047
1053
  }
1048
1054
 
1049
- export { type AIAgent, type AIAgentCreate, type AIAgentUpdate, type AIDataSource, type AIGuardrail, type AIGuardrailCreate, type AIGuardrailUpdate, type AISkill, type AISkillCreate, type AISkillUpdate, type AITool, type ActivityEvent, type AgentMode, type AgentPreferredModel, type AgentStatus, type AgentTTSModel, type AgentType, AgentsClient, type AmsApplicationAgentsResponse, type AmsAuditableFields, AmsClient, type AmsSDKConfig, type AmsServiceName, type ArtifactBlockEvent, type AudioChunkEvent, type AudioInputFramePayload, AuthClient, type AuthMessageResponse, type AuthenticatedUser, type ChatEvent, type ChatFramePayload, type ConversationHistory, type ConversationHistoryEntry, DEFAULT_TIMEOUT_MS, DataSourcesClient, type Department, type DepartmentCreate, type DepartmentTeamEvaluation, type DepartmentUpdate, DepartmentsClient, type Environment, type ErrorEvent, type EventReplayEvent, GuardrailsClient, HCAmsSDK, type HandoffFramePayload, type HistoryEvent, type HttpMethod, type HttpRequestBody, type HttpRequestOptions, type JsonObject, type JsonPrimitive, type JsonValue, type LoginRequest, type NotificationEvent, type OutgoingFrameType, type PasswordResetConfirmRequest, type PasswordResetRequest, type PingEvent, PoliciesClient, type Policy, type PolicyCreate, type PolicyUpdate, type QueryParamPrimitive, type QueryParamValue, type QueryParams, type RegistrationRequest, type RegistrationResponse, type ResponseSuggestionsEvent, SDKError, type SDKRuntimeState, SERVICE_NAME, SkillsClient, type Team, type TeamCreate, type TeamUpdate, TeamsClient, type TestPatientCredentialCreate, type TestPatientCredentialEnvironment, type TestPatientCredentialResponse, type TestPatientCredentialUpdate, type TestPatientLoginResponse, TestPersonasClient, type TokenResponse, type ToolConfirmationFramePayload, type ToolResultEvent, ToolsClient, type TransferCandidate, type TransferEvent, type TurnCancelledEvent, type TurnCompletedEvent, type TurnFailedEvent, type TurnResult, type TurnStartedEvent, type VadEvent, type VoiceFramePayload, type VoiceTranscriptEvent, type WebSocketImpl, type WebSocketLike, WssClient, type WssClientOptions, type WssEnvelopeFields, type WssEventMap, type WssEventType, type WssServerFrame, assertEnvironment, assertTimeout, resolveAmsAuthBaseUrl, resolveBaseUrl, resolveWssBaseUrl };
1055
+ export { type AIAgent, type AIAgentCreate, type AIAgentUpdate, type AIDataSource, type AIGuardrail, type AIGuardrailCreate, type AIGuardrailUpdate, type AISkill, type AISkillCreate, type AISkillUpdate, type AITool, type ActivityEvent, type AgentMode, type AgentPreferredModel, type AgentStatus, type AgentTTSModel, type AgentType, AgentsClient, type AmsApplicationAgentsResponse, type AmsAuditableFields, AmsClient, type AmsSDKConfig, type AmsServiceName, type ArtifactBlockEvent, type AudioChunkEvent, type AudioInputFramePayload, AuthClient, type AuthMessageResponse, type AuthenticatedUser, type ChatEvent, type ChatFramePayload, type ConversationHistory, type ConversationHistoryEntry, DEFAULT_TIMEOUT_MS, DataSourcesClient, type Department, type DepartmentCreate, type DepartmentTeamEvaluation, type DepartmentUpdate, DepartmentsClient, type Environment, type ErrorEvent, type EventReplayEvent, GuardrailsClient, HCAmsSDK, type HandoffFramePayload, type HistoryEvent, type HttpMethod, type HttpRequestBody, type HttpRequestOptions, type JsonObject, type JsonPrimitive, type JsonValue, type LoginRequest, type NotificationEvent, type OutgoingFrameType, type PasswordResetConfirmRequest, type PasswordResetRequest, type PingEvent, PoliciesClient, type Policy, type PolicyCreate, type PolicyUpdate, type QueryParamPrimitive, type QueryParamValue, type QueryParams, type RegistrationRequest, type RegistrationResponse, type ResponseSuggestionsEvent, SDKError, type SDKRuntimeState, SERVICE_NAME, SkillsClient, type Team, type TeamCreate, type TeamUpdate, TeamsClient, type TestPatientCredentialCreate, type TestPatientCredentialEnvironment, type TestPatientCredentialResponse, type TestPatientCredentialUpdate, type TestPatientLoginResponse, TestPersonasClient, type TokenResponse, type ToolConfirmationFramePayload, type ToolResultEvent, ToolsClient, type TransferCandidate, type TransferEvent, type TurnCancelledEvent, type TurnCompletedEvent, type TurnFailedEvent, type TurnResult, type TurnStartedEvent, type VadEvent, type VoiceFramePayload, type VoiceTranscriptEvent, type WebSocketImpl, type WebSocketLike, WssClient, type WssClientOptions, type WssEnvelopeFields, type WssEventMap, type WssEventType, type WssServerFrame, assertEnvironment, assertTimeout, resolveAmsAuthBaseUrl, resolveAmsOrigin, resolveBaseUrl, resolveWssBaseUrl };
package/dist/index.d.ts CHANGED
@@ -8,6 +8,10 @@ interface AmsSDKConfig {
8
8
  accessToken?: string;
9
9
  /** Overrides the resolved AMS base URL for this SDK instance. */
10
10
  baseUrlOverride?: string;
11
+ /** Independent AMS auth base, including /api/auth; API overrides never retarget login. */
12
+ authBaseUrlOverride?: string;
13
+ /** WSS base (optional proxy prefix). Otherwise follows the selected API origin. */
14
+ wssBaseUrlOverride?: string;
11
15
  /** Request timeout in milliseconds. Defaults to 30000 (30s). */
12
16
  timeout?: number;
13
17
  }
@@ -20,10 +24,10 @@ interface SDKRuntimeState {
20
24
  }
21
25
  declare const DEFAULT_TIMEOUT_MS = 30000;
22
26
  /**
23
- * AMS Services hosts itself at `{env-}amsservices.health.cloud/api/ams`,
24
- * unlike the `{env-}api-<service>.health.cloud` pattern other HealthCloud
25
- * services use — mirrors `resolveBaseUrl` in packages/npm/src/config/SDKConfig.ts.
27
+ * DEV uses the AWS AMS deployment. UAT/PROD retain their existing configuration;
28
+ * all three AMS endpoint families use the same environment origin.
26
29
  */
30
+ declare function resolveAmsOrigin(environment: Environment): string;
27
31
  declare function resolveBaseUrl(environment: Environment): string;
28
32
  /**
29
33
  * AMS mounts its tenant-admin auth routes (`/api/auth/*`) alongside, not
@@ -62,6 +66,7 @@ interface HttpRequestOptions {
62
66
 
63
67
  declare class HttpClient {
64
68
  private readonly state;
69
+ private readonly baseUrl;
65
70
  constructor(state: SDKRuntimeState);
66
71
  request<TResponse>(method: HttpMethod, path: string, options?: HttpRequestOptions): Promise<TResponse>;
67
72
  private buildHeaders;
@@ -903,7 +908,7 @@ interface WssClientOptions {
903
908
  getAccessToken?: () => string | Promise<string>;
904
909
  /** Omit to connect via the tenant's default agent (`/ws`). */
905
910
  agentId?: string;
906
- /** Overrides the resolved WSS base URL (scheme + host, no path). */
911
+ /** Overrides the resolved WSS base URL (optional proxy prefix, without /ws). */
907
912
  baseUrlOverride?: string;
908
913
  /** Defaults to `globalThis.WebSocket`. Required on Node &lt; 21. */
909
914
  WebSocketImpl?: WebSocketImpl;
@@ -991,6 +996,7 @@ declare class HCAmsSDK {
991
996
  private readonly state;
992
997
  private readonly http;
993
998
  private readonly authHttp;
999
+ private readonly wssBaseUrl;
994
1000
  /** AMS application-agent discovery (public). */
995
1001
  readonly ams: AmsClient;
996
1002
  /** Agent CRUD, transfer candidates, conversation history. */
@@ -1046,4 +1052,4 @@ declare class SDKError extends Error {
1046
1052
  toString(): string;
1047
1053
  }
1048
1054
 
1049
- export { type AIAgent, type AIAgentCreate, type AIAgentUpdate, type AIDataSource, type AIGuardrail, type AIGuardrailCreate, type AIGuardrailUpdate, type AISkill, type AISkillCreate, type AISkillUpdate, type AITool, type ActivityEvent, type AgentMode, type AgentPreferredModel, type AgentStatus, type AgentTTSModel, type AgentType, AgentsClient, type AmsApplicationAgentsResponse, type AmsAuditableFields, AmsClient, type AmsSDKConfig, type AmsServiceName, type ArtifactBlockEvent, type AudioChunkEvent, type AudioInputFramePayload, AuthClient, type AuthMessageResponse, type AuthenticatedUser, type ChatEvent, type ChatFramePayload, type ConversationHistory, type ConversationHistoryEntry, DEFAULT_TIMEOUT_MS, DataSourcesClient, type Department, type DepartmentCreate, type DepartmentTeamEvaluation, type DepartmentUpdate, DepartmentsClient, type Environment, type ErrorEvent, type EventReplayEvent, GuardrailsClient, HCAmsSDK, type HandoffFramePayload, type HistoryEvent, type HttpMethod, type HttpRequestBody, type HttpRequestOptions, type JsonObject, type JsonPrimitive, type JsonValue, type LoginRequest, type NotificationEvent, type OutgoingFrameType, type PasswordResetConfirmRequest, type PasswordResetRequest, type PingEvent, PoliciesClient, type Policy, type PolicyCreate, type PolicyUpdate, type QueryParamPrimitive, type QueryParamValue, type QueryParams, type RegistrationRequest, type RegistrationResponse, type ResponseSuggestionsEvent, SDKError, type SDKRuntimeState, SERVICE_NAME, SkillsClient, type Team, type TeamCreate, type TeamUpdate, TeamsClient, type TestPatientCredentialCreate, type TestPatientCredentialEnvironment, type TestPatientCredentialResponse, type TestPatientCredentialUpdate, type TestPatientLoginResponse, TestPersonasClient, type TokenResponse, type ToolConfirmationFramePayload, type ToolResultEvent, ToolsClient, type TransferCandidate, type TransferEvent, type TurnCancelledEvent, type TurnCompletedEvent, type TurnFailedEvent, type TurnResult, type TurnStartedEvent, type VadEvent, type VoiceFramePayload, type VoiceTranscriptEvent, type WebSocketImpl, type WebSocketLike, WssClient, type WssClientOptions, type WssEnvelopeFields, type WssEventMap, type WssEventType, type WssServerFrame, assertEnvironment, assertTimeout, resolveAmsAuthBaseUrl, resolveBaseUrl, resolveWssBaseUrl };
1055
+ export { type AIAgent, type AIAgentCreate, type AIAgentUpdate, type AIDataSource, type AIGuardrail, type AIGuardrailCreate, type AIGuardrailUpdate, type AISkill, type AISkillCreate, type AISkillUpdate, type AITool, type ActivityEvent, type AgentMode, type AgentPreferredModel, type AgentStatus, type AgentTTSModel, type AgentType, AgentsClient, type AmsApplicationAgentsResponse, type AmsAuditableFields, AmsClient, type AmsSDKConfig, type AmsServiceName, type ArtifactBlockEvent, type AudioChunkEvent, type AudioInputFramePayload, AuthClient, type AuthMessageResponse, type AuthenticatedUser, type ChatEvent, type ChatFramePayload, type ConversationHistory, type ConversationHistoryEntry, DEFAULT_TIMEOUT_MS, DataSourcesClient, type Department, type DepartmentCreate, type DepartmentTeamEvaluation, type DepartmentUpdate, DepartmentsClient, type Environment, type ErrorEvent, type EventReplayEvent, GuardrailsClient, HCAmsSDK, type HandoffFramePayload, type HistoryEvent, type HttpMethod, type HttpRequestBody, type HttpRequestOptions, type JsonObject, type JsonPrimitive, type JsonValue, type LoginRequest, type NotificationEvent, type OutgoingFrameType, type PasswordResetConfirmRequest, type PasswordResetRequest, type PingEvent, PoliciesClient, type Policy, type PolicyCreate, type PolicyUpdate, type QueryParamPrimitive, type QueryParamValue, type QueryParams, type RegistrationRequest, type RegistrationResponse, type ResponseSuggestionsEvent, SDKError, type SDKRuntimeState, SERVICE_NAME, SkillsClient, type Team, type TeamCreate, type TeamUpdate, TeamsClient, type TestPatientCredentialCreate, type TestPatientCredentialEnvironment, type TestPatientCredentialResponse, type TestPatientCredentialUpdate, type TestPatientLoginResponse, TestPersonasClient, type TokenResponse, type ToolConfirmationFramePayload, type ToolResultEvent, ToolsClient, type TransferCandidate, type TransferEvent, type TurnCancelledEvent, type TurnCompletedEvent, type TurnFailedEvent, type TurnResult, type TurnStartedEvent, type VadEvent, type VoiceFramePayload, type VoiceTranscriptEvent, type WebSocketImpl, type WebSocketLike, WssClient, type WssClientOptions, type WssEnvelopeFields, type WssEventMap, type WssEventType, type WssServerFrame, assertEnvironment, assertTimeout, resolveAmsAuthBaseUrl, resolveAmsOrigin, resolveBaseUrl, resolveWssBaseUrl };
package/dist/index.js CHANGED
@@ -1,17 +1,20 @@
1
1
  // src/config/SDKConfig.ts
2
2
  var SERVICE_NAME = "ams";
3
3
  var DEFAULT_TIMEOUT_MS = 3e4;
4
- function resolveBaseUrl(environment) {
4
+ function resolveAmsOrigin(environment) {
5
+ assertEnvironment(environment);
6
+ if (environment === "dev") return "https://dev-ams-services.health.cloud";
5
7
  const prefix = environment === "prod" ? "" : `${environment}-`;
6
- return `https://${prefix}amsservices.health.cloud/api/ams`;
8
+ return `https://${prefix}amsservices.health.cloud`;
9
+ }
10
+ function resolveBaseUrl(environment) {
11
+ return `${resolveAmsOrigin(environment)}/api/ams`;
7
12
  }
8
13
  function resolveAmsAuthBaseUrl(environment) {
9
- const prefix = environment === "prod" ? "" : `${environment}-`;
10
- return `https://${prefix}amsservices.health.cloud/api/auth`;
14
+ return `${resolveAmsOrigin(environment)}/api/auth`;
11
15
  }
12
16
  function resolveWssBaseUrl(environment) {
13
- const prefix = environment === "prod" ? "" : `${environment}-`;
14
- return `wss://${prefix}amsservices.health.cloud`;
17
+ return resolveAmsOrigin(environment).replace(/^https:/, "wss:");
15
18
  }
16
19
  function assertEnvironment(environment) {
17
20
  if (environment !== "dev" && environment !== "uat" && environment !== "prod") {
@@ -24,6 +27,65 @@ function assertTimeout(timeout, label = "timeout") {
24
27
  }
25
28
  }
26
29
 
30
+ // src/config/ServiceUrls.ts
31
+ function normalizeBaseUrl(value) {
32
+ const message = "Invalid service base URL: expected HTTPS (or literal loopback HTTP); no credentials, query or fragment";
33
+ try {
34
+ if (typeof value !== "string" || /[^\x21-\x7e]|[\\?#]/.test(value) || !/^https?:\/\//i.test(value)) {
35
+ throw new Error();
36
+ }
37
+ const authority = value.slice(value.indexOf("://") + 3).split("/")[0];
38
+ if (!authority || /[@%]/.test(authority) || authority.endsWith(":")) throw new Error();
39
+ const url = new URL(value);
40
+ const host = url.hostname;
41
+ const allowedScheme = url.protocol === "https:" || url.protocol === "http:" && (host === "127.0.0.1" || host === "[::1]");
42
+ if (!allowedScheme || !host || url.username || url.password || url.port && Number(url.port) < 1) {
43
+ throw new Error();
44
+ }
45
+ if (!host.startsWith("[") && (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host) || host.split(".").some(
46
+ (label) => !label || label.length > 63 || label.startsWith("-") || label.endsWith("-")
47
+ ))) throw new Error();
48
+ const rawHost = authority.startsWith("[") ? authority.slice(0, authority.indexOf("]") + 1) : authority.split(":")[0];
49
+ if (!host.startsWith("[") && host !== rawHost.toLowerCase()) throw new Error();
50
+ const rawPath = value.slice(value.indexOf("://") + 3 + authority.length);
51
+ if (rawPath.includes("//") || /%(?![0-9a-f]{2})|%2f/i.test(rawPath)) throw new Error();
52
+ const decoded = decodePathBytes(rawPath);
53
+ if (hasControls(decoded) || /[\\?#%]/.test(decoded) || decoded.split("/").some((s) => s === "." || s === "..")) {
54
+ throw new Error();
55
+ }
56
+ return `${url.origin}${rawPath.replace(/\/+$/, "")}`;
57
+ } catch {
58
+ throw new Error(message);
59
+ }
60
+ }
61
+ function joinServiceUrl(base, path) {
62
+ if (hasControls(path) || /[\\?#]/.test(path) || path.includes("://") || path.startsWith("//") || path.split("/").some((segment) => {
63
+ const decoded = decodePathBytes(segment);
64
+ return decoded === "." || decoded === "..";
65
+ })) throw new Error("Invalid service request path");
66
+ return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
67
+ }
68
+ function normalizeWssBaseUrl(value) {
69
+ if (typeof value !== "string" || !/^wss?:\/\//i.test(value)) {
70
+ throw new Error("Invalid WebSocket base URL: expected WSS (or literal loopback WS)");
71
+ }
72
+ try {
73
+ return normalizeBaseUrl(value.replace(/^wss:/i, "https:").replace(/^ws:/i, "http:")).replace(/^https:/, "wss:").replace(/^http:/, "ws:");
74
+ } catch {
75
+ throw new Error("Invalid WebSocket base URL: expected WSS (or literal loopback WS)");
76
+ }
77
+ }
78
+ function wssBaseForApi(base) {
79
+ const url = new URL(normalizeBaseUrl(base));
80
+ return url.origin.replace(/^https:/, "wss:").replace(/^http:/, "ws:");
81
+ }
82
+ function hasControls(value) {
83
+ return Array.from(value).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
84
+ }
85
+ function decodePathBytes(value) {
86
+ return value.replace(/%([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
87
+ }
88
+
27
89
  // src/errors/SDKError.ts
28
90
  var SDKError = class extends Error {
29
91
  constructor(params) {
@@ -42,12 +104,15 @@ var SDKError = class extends Error {
42
104
  var HttpClient = class {
43
105
  constructor(state) {
44
106
  this.state = state;
107
+ this.baseUrl = normalizeBaseUrl(
108
+ state.baseUrlOverride === void 0 ? resolveBaseUrl(state.environment) : state.baseUrlOverride
109
+ );
45
110
  }
46
111
  async request(method, path, options = {}) {
47
112
  var _a, _b;
48
113
  const url = this.buildUrl(path, options);
49
114
  const headers = this.buildHeaders(options);
50
- const init = { method, headers };
115
+ const init = { method, headers, redirect: "error" };
51
116
  if (method !== "GET" && method !== "DELETE" && options.body !== void 0) {
52
117
  init.body = this.serializeBody(options.body, headers);
53
118
  }
@@ -64,6 +129,9 @@ var HttpClient = class {
64
129
  let payload;
65
130
  try {
66
131
  response = await fetch(url, init);
132
+ if (response.redirected || response.status >= 300 && response.status < 400 || response.type === "opaqueredirect") {
133
+ throw new SDKError({ message: "Service redirects are not allowed", statusCode: response.status });
134
+ }
67
135
  payload = await this.parseResponse(response);
68
136
  } catch (error) {
69
137
  if (didTimeout) {
@@ -77,7 +145,7 @@ var HttpClient = class {
77
145
  throw error;
78
146
  }
79
147
  throw new SDKError({
80
- message: error instanceof Error ? error.message : "Network request failed.",
148
+ message: "Network request failed.",
81
149
  statusCode: 0,
82
150
  cause: error
83
151
  });
@@ -111,10 +179,9 @@ var HttpClient = class {
111
179
  return headers;
112
180
  }
113
181
  buildUrl(path, options) {
114
- var _a, _b;
182
+ var _a;
115
183
  const normalizedPath = this.resolvePath(path, (_a = options.pathParams) != null ? _a : {});
116
- const base = (_b = this.state.baseUrlOverride) != null ? _b : resolveBaseUrl(this.state.environment);
117
- const url = new URL(`${base}${normalizedPath}`);
184
+ const url = new URL(joinServiceUrl(this.baseUrl, normalizedPath));
118
185
  if (options.query) {
119
186
  for (const [key, value] of Object.entries(options.query)) {
120
187
  this.appendQuery(url, key, value);
@@ -603,17 +670,19 @@ var WssClient = class {
603
670
  // Storage is necessarily untyped across the heterogeneous event map; `on`/`dispatch` restore type safety at the boundary.
604
671
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
605
672
  this.listeners = /* @__PURE__ */ new Map();
606
- var _a, _b, _c, _d;
673
+ var _a, _b, _c;
607
674
  if (options.healthcloudToken === void 0 && options.getAccessToken === void 0) {
608
675
  throw new SDKError({
609
676
  message: "WssClient requires either `healthcloudToken` or `getAccessToken`.",
610
677
  statusCode: 0
611
678
  });
612
679
  }
613
- const base = (_a = options.baseUrlOverride) != null ? _a : resolveWssBaseUrl(options.environment);
680
+ const base = normalizeWssBaseUrl(
681
+ options.baseUrlOverride === void 0 ? resolveWssBaseUrl(options.environment) : options.baseUrlOverride
682
+ );
614
683
  const sessionId = `${options.tenantId}/${options.patientId}`;
615
684
  const path = options.agentId ? `/ws/agents/${encodeURIComponent(options.agentId)}/chat` : "/ws";
616
- const url = new URL(`${base}${path}`);
685
+ const url = new URL(joinServiceUrl(base, path));
617
686
  url.searchParams.set("session_id", sessionId);
618
687
  if (options.lang) url.searchParams.set("lang", options.lang);
619
688
  if (options.voice) url.searchParams.set("voice", "1");
@@ -624,9 +693,9 @@ var WssClient = class {
624
693
  url.searchParams.set("handoff", JSON.stringify(options.handoff));
625
694
  }
626
695
  this.url = url.toString();
627
- this.turnTimeoutMs = (_b = options.turnTimeoutMs) != null ? _b : 6e4;
628
- this.authTimeoutMs = (_c = options.authTimeoutMs) != null ? _c : 1e4;
629
- const ctor = (_d = options.WebSocketImpl) != null ? _d : globalThis.WebSocket;
696
+ this.turnTimeoutMs = (_a = options.turnTimeoutMs) != null ? _a : 6e4;
697
+ this.authTimeoutMs = (_b = options.authTimeoutMs) != null ? _b : 1e4;
698
+ const ctor = (_c = options.WebSocketImpl) != null ? _c : globalThis.WebSocket;
630
699
  if (!ctor) {
631
700
  throw new SDKError({
632
701
  message: 'No WebSocket implementation available. Pass `WebSocketImpl` (e.g. `new WssClient({ ..., WebSocketImpl: require("ws") })`) on runtimes without a global WebSocket (Node < 21).',
@@ -876,18 +945,26 @@ var WssClient = class {
876
945
  // src/HCAmsSDK.ts
877
946
  var HCAmsSDK = class {
878
947
  constructor(config) {
879
- var _a, _b, _c;
948
+ var _a, _b;
880
949
  assertEnvironment(config.environment);
881
950
  assertTimeout((_a = config.timeout) != null ? _a : DEFAULT_TIMEOUT_MS);
951
+ const apiBase = normalizeBaseUrl(
952
+ config.baseUrlOverride === void 0 ? resolveBaseUrl(config.environment) : config.baseUrlOverride
953
+ );
954
+ const authBase = normalizeBaseUrl(
955
+ config.authBaseUrlOverride === void 0 ? resolveAmsAuthBaseUrl(config.environment) : config.authBaseUrlOverride
956
+ );
957
+ this.wssBaseUrl = normalizeWssBaseUrl(
958
+ config.wssBaseUrlOverride === void 0 ? wssBaseForApi(apiBase) : config.wssBaseUrlOverride
959
+ );
882
960
  this.state = {
883
961
  environment: config.environment,
884
962
  tenantId: config.tenantId,
885
963
  accessToken: config.accessToken,
886
- baseUrlOverride: config.baseUrlOverride,
964
+ baseUrlOverride: apiBase,
887
965
  timeout: (_b = config.timeout) != null ? _b : DEFAULT_TIMEOUT_MS
888
966
  };
889
967
  this.http = new HttpClient(this.state);
890
- const authBaseUrlOverride = (_c = config.baseUrlOverride) != null ? _c : resolveAmsAuthBaseUrl(config.environment);
891
968
  const state = this.state;
892
969
  const authState = {
893
970
  get environment() {
@@ -903,7 +980,7 @@ var HCAmsSDK = class {
903
980
  state.accessToken = value;
904
981
  },
905
982
  get baseUrlOverride() {
906
- return authBaseUrlOverride;
983
+ return authBase;
907
984
  },
908
985
  get timeout() {
909
986
  return state.timeout;
@@ -938,6 +1015,7 @@ var HCAmsSDK = class {
938
1015
  }
939
1016
  return new WssClient({
940
1017
  ...options,
1018
+ baseUrlOverride: options.baseUrlOverride === void 0 ? this.wssBaseUrl : options.baseUrlOverride,
941
1019
  environment: this.state.environment,
942
1020
  tenantId
943
1021
  });
@@ -979,6 +1057,7 @@ export {
979
1057
  assertEnvironment,
980
1058
  assertTimeout,
981
1059
  resolveAmsAuthBaseUrl,
1060
+ resolveAmsOrigin,
982
1061
  resolveBaseUrl,
983
1062
  resolveWssBaseUrl
984
1063
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@healthcloudai/hc-ams",
3
- "version": "3.6.4",
3
+ "version": "3.6.5",
4
4
  "description": "HealthCloud AMS SDK \u2014 application-agent discovery for AMS Services.",
5
5
  "author": "Healthcheck Systems Inc",
6
6
  "license": "MIT",