@connextar/house 0.26.0 → 0.27.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.
Files changed (87) hide show
  1. package/README.md +74 -0
  2. package/dist/voice/handoff.d.ts +20 -0
  3. package/dist/voice/handoff.d.ts.map +1 -0
  4. package/dist/voice/handoff.js +18 -0
  5. package/dist/voice/handoff.js.map +1 -0
  6. package/dist/voice/index.d.ts +16 -0
  7. package/dist/voice/index.d.ts.map +1 -0
  8. package/dist/voice/index.js +16 -0
  9. package/dist/voice/index.js.map +1 -0
  10. package/dist/voice/opening-hours.d.ts +23 -0
  11. package/dist/voice/opening-hours.d.ts.map +1 -0
  12. package/dist/voice/opening-hours.js +117 -0
  13. package/dist/voice/opening-hours.js.map +1 -0
  14. package/dist/voice/out-of-hours.d.ts +29 -0
  15. package/dist/voice/out-of-hours.d.ts.map +1 -0
  16. package/dist/voice/out-of-hours.js +20 -0
  17. package/dist/voice/out-of-hours.js.map +1 -0
  18. package/dist/voice/phone.d.ts +33 -0
  19. package/dist/voice/phone.d.ts.map +1 -0
  20. package/dist/voice/phone.js +62 -0
  21. package/dist/voice/phone.js.map +1 -0
  22. package/dist/voice/relay/agent-client.d.ts +24 -0
  23. package/dist/voice/relay/agent-client.d.ts.map +1 -0
  24. package/dist/voice/relay/agent-client.js +45 -0
  25. package/dist/voice/relay/agent-client.js.map +1 -0
  26. package/dist/voice/relay/model.d.ts +124 -0
  27. package/dist/voice/relay/model.d.ts.map +1 -0
  28. package/dist/voice/relay/model.js +304 -0
  29. package/dist/voice/relay/model.js.map +1 -0
  30. package/dist/voice/relay/protocol.d.ts +44 -0
  31. package/dist/voice/relay/protocol.d.ts.map +1 -0
  32. package/dist/voice/relay/protocol.js +16 -0
  33. package/dist/voice/relay/protocol.js.map +1 -0
  34. package/dist/voice/relay/sentence-gate.d.ts +24 -0
  35. package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
  36. package/dist/voice/relay/sentence-gate.js +65 -0
  37. package/dist/voice/relay/sentence-gate.js.map +1 -0
  38. package/dist/voice/relay/server.d.ts +71 -0
  39. package/dist/voice/relay/server.d.ts.map +1 -0
  40. package/dist/voice/relay/server.js +192 -0
  41. package/dist/voice/relay/server.js.map +1 -0
  42. package/dist/voice/relay/transfer-line.d.ts +33 -0
  43. package/dist/voice/relay/transfer-line.d.ts.map +1 -0
  44. package/dist/voice/relay/transfer-line.js +116 -0
  45. package/dist/voice/relay/transfer-line.js.map +1 -0
  46. package/dist/voice/relay-index.d.ts +13 -0
  47. package/dist/voice/relay-index.d.ts.map +1 -0
  48. package/dist/voice/relay-index.js +13 -0
  49. package/dist/voice/relay-index.js.map +1 -0
  50. package/dist/voice/session-token.d.ts +58 -0
  51. package/dist/voice/session-token.d.ts.map +1 -0
  52. package/dist/voice/session-token.js +152 -0
  53. package/dist/voice/session-token.js.map +1 -0
  54. package/dist/voice/transfer.d.ts +123 -0
  55. package/dist/voice/transfer.d.ts.map +1 -0
  56. package/dist/voice/transfer.js +95 -0
  57. package/dist/voice/transfer.js.map +1 -0
  58. package/dist/voice/twilio-request.d.ts +30 -0
  59. package/dist/voice/twilio-request.d.ts.map +1 -0
  60. package/dist/voice/twilio-request.js +46 -0
  61. package/dist/voice/twilio-request.js.map +1 -0
  62. package/dist/voice/twilio-signature.d.ts +8 -0
  63. package/dist/voice/twilio-signature.d.ts.map +1 -0
  64. package/dist/voice/twilio-signature.js +22 -0
  65. package/dist/voice/twilio-signature.js.map +1 -0
  66. package/dist/voice/twiml.d.ts +93 -0
  67. package/dist/voice/twiml.d.ts.map +1 -0
  68. package/dist/voice/twiml.js +107 -0
  69. package/dist/voice/twiml.js.map +1 -0
  70. package/package.json +15 -1
  71. package/src/voice/handoff.ts +34 -0
  72. package/src/voice/index.ts +78 -0
  73. package/src/voice/opening-hours.ts +125 -0
  74. package/src/voice/out-of-hours.ts +48 -0
  75. package/src/voice/phone.ts +68 -0
  76. package/src/voice/relay/agent-client.ts +64 -0
  77. package/src/voice/relay/model.ts +412 -0
  78. package/src/voice/relay/protocol.ts +52 -0
  79. package/src/voice/relay/sentence-gate.ts +64 -0
  80. package/src/voice/relay/server.ts +242 -0
  81. package/src/voice/relay/transfer-line.ts +114 -0
  82. package/src/voice/relay-index.ts +46 -0
  83. package/src/voice/session-token.ts +205 -0
  84. package/src/voice/transfer.ts +171 -0
  85. package/src/voice/twilio-request.ts +60 -0
  86. package/src/voice/twilio-signature.ts +27 -0
  87. package/src/voice/twiml.ts +184 -0
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Minimal TwiML builders. Every interpolated value is XML-escaped, so a caller's
3
+ * name or a business's greeting can never close a tag or add a verb.
4
+ *
5
+ * Lifted from PharmaLineAI (0.27.7). New here: `gather`, `play`, `<Number url>`
6
+ * call screening and a `timeout` on `dial` (PharmaLine's was fixed at 25 s,
7
+ * which is still the default).
8
+ */
9
+ export function escapeXml(value) {
10
+ return value
11
+ .replace(/&/g, "&amp;")
12
+ .replace(/</g, "&lt;")
13
+ .replace(/>/g, "&gt;")
14
+ .replace(/"/g, "&quot;")
15
+ .replace(/'/g, "&apos;");
16
+ }
17
+ function attrs(values) {
18
+ return Object.entries(values)
19
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
20
+ .map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`)
21
+ .join("");
22
+ }
23
+ /** A whole TwiML document around verbs already built. */
24
+ export function response(body) {
25
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${body}</Response>`;
26
+ }
27
+ /** The default `<Say>` voice: Polly's British English neural voice, as PharmaLine has always used. */
28
+ export const DEFAULT_SAY_VOICE = { language: "en-GB", voice: "Polly.Amy-Neural" };
29
+ /** A `<Say>` verb (not a document). */
30
+ export function say(text, voice = DEFAULT_SAY_VOICE) {
31
+ return `<Say${attrs({ language: voice.language, voice: voice.voice })}>${escapeXml(text)}</Say>`;
32
+ }
33
+ /** A `<Play>` verb (not a document): pre-rendered audio at an absolute URL. */
34
+ export function play(url) {
35
+ return `<Play>${escapeXml(url)}</Play>`;
36
+ }
37
+ /** Speak a message and hang up. */
38
+ export function sayAndHangup(text, voice) {
39
+ return response(`${say(text, voice)}<Hangup/>`);
40
+ }
41
+ /** Play or say verbs already built, then hang up. */
42
+ export function thenHangup(verbs) {
43
+ return response(`${verbs}<Hangup/>`);
44
+ }
45
+ export function hangup() {
46
+ return response("<Hangup/>");
47
+ }
48
+ /**
49
+ * Turn the call away unanswered. As the first and only verb, Twilio never
50
+ * answers, so the call isn't billed: `rejected` plays a not-in-service message,
51
+ * `busy` a busy tone. For a transfer that diverted back to the line it came
52
+ * from, `busy` is what the transferring `<Dial>` sees.
53
+ */
54
+ export function reject(reason = "busy") {
55
+ return response(`<Reject${attrs({ reason })}/>`);
56
+ }
57
+ /** Ask the caller for a key press or a few words. A document. */
58
+ export function gather(o) {
59
+ const open = `<Gather${attrs({
60
+ input: o.input ?? "dtmf",
61
+ action: o.actionUrl,
62
+ method: "POST",
63
+ numDigits: o.numDigits,
64
+ timeout: o.timeout,
65
+ language: o.language,
66
+ hints: o.hints?.length ? o.hints.join(", ") : undefined,
67
+ speechTimeout: o.speechTimeout,
68
+ partialResultCallback: o.partialResultCallback,
69
+ actionOnEmptyResult: true,
70
+ })}>`;
71
+ return response(`${open}${o.prompt}</Gather>`);
72
+ }
73
+ /** Hand the call to the AI via ConversationRelay; `action` runs when the AI session ends. */
74
+ export function connectConversationRelay(o) {
75
+ const params = Object.entries(o.parameters)
76
+ .map(([name, value]) => `<Parameter${attrs({ name, value })}/>`)
77
+ .join("");
78
+ const relay = `<ConversationRelay${attrs({
79
+ url: o.relayUrl,
80
+ welcomeGreeting: o.welcomeGreeting,
81
+ language: o.language,
82
+ ttsProvider: o.ttsProvider,
83
+ voice: o.voice,
84
+ transcriptionProvider: o.transcriptionProvider,
85
+ interruptible: "any",
86
+ dtmfDetection: true,
87
+ })}>${params}</ConversationRelay>`;
88
+ const record = o.recordingCallbackUrl
89
+ ? `<Start><Recording${attrs({ recordingStatusCallback: o.recordingCallbackUrl, recordingStatusCallbackEvent: "completed" })}/></Start>`
90
+ : "";
91
+ return response(`${o.preamble ?? ""}${record}<Connect${attrs({ action: o.actionUrl })}>${relay}</Connect>`);
92
+ }
93
+ /** Put the caller through to a person; `action` decides what happens if nobody accepts. */
94
+ export function dial(o) {
95
+ const lead = o.preambleVerbs ?? (o.preamble ? say(o.preamble, o.sayVoice) : "");
96
+ const number = `<Number${attrs({
97
+ url: o.screenUrl,
98
+ method: o.screenUrl ? "POST" : undefined,
99
+ statusCallback: o.statusCallback,
100
+ statusCallbackMethod: o.statusCallback ? "POST" : undefined,
101
+ statusCallbackEvent: o.statusCallback
102
+ ? (o.statusCallbackEvent ?? "initiated ringing answered completed")
103
+ : undefined,
104
+ })}>${escapeXml(o.number)}</Number>`;
105
+ return response(`${lead}<Dial${attrs({ callerId: o.callerId, timeout: o.timeout ?? 25, action: o.actionUrl })}>${number}</Dial>`);
106
+ }
107
+ //# sourceMappingURL=twiml.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"twiml.js","sourceRoot":"","sources":["../../src/voice/twiml.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,UAAU,SAAS,CAAC,KAAa;IACrC,OAAO,KAAK;SACT,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAC7B,CAAC;AAID,SAAS,KAAK,CAAC,MAAiC;IAC9C,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;SAC1B,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;S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CAAC,MAAM,CAAC,WAAW,CAAC;IACrC,OAAO,QAAQ,CACb,GAAG,IAAI,QAAQ,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,IAAI,MAAM,SAAS,CACjH,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@connextar/house",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "The pieces every app we build needs and none of them should own a copy of.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -200,6 +200,14 @@
200
200
  "types": "./dist/maintenance/react-index.d.ts",
201
201
  "default": "./dist/maintenance/react-index.js"
202
202
  },
203
+ "./voice": {
204
+ "types": "./dist/voice/index.d.ts",
205
+ "default": "./dist/voice/index.js"
206
+ },
207
+ "./voice/relay": {
208
+ "types": "./dist/voice/relay-index.d.ts",
209
+ "default": "./dist/voice/relay-index.js"
210
+ },
203
211
  "./house.css": {
204
212
  "style": "./dist/house.css",
205
213
  "default": "./dist/house.css"
@@ -228,6 +236,7 @@
228
236
  "react": "^19.0.0",
229
237
  "react-dom": "^19.0.0",
230
238
  "react-hook-form": "^7.60.0",
239
+ "ws": "^8.18.0",
231
240
  "zod": "^3.25.0 || ^4.0.0"
232
241
  },
233
242
  "peerDependenciesMeta": {
@@ -248,6 +257,9 @@
248
257
  },
249
258
  "zod": {
250
259
  "optional": true
260
+ },
261
+ "ws": {
262
+ "optional": true
251
263
  }
252
264
  },
253
265
  "devDependencies": {
@@ -260,6 +272,7 @@
260
272
  "@types/node": "^26.4.1",
261
273
  "@types/react": "^19.2.0",
262
274
  "@types/react-dom": "^19.3.0",
275
+ "@types/ws": "^8.18.2",
263
276
  "@typescript-eslint/eslint-plugin": "^8.0.0",
264
277
  "@typescript-eslint/parser": "^8.0.0",
265
278
  "better-auth": "1.7.2",
@@ -278,6 +291,7 @@
278
291
  "typescript": "^5.7.0",
279
292
  "typescript-eslint": "^8.69.0",
280
293
  "vitest": "^4.0.0",
294
+ "ws": "^8.23.0",
281
295
  "zod": "^4.6.5"
282
296
  },
283
297
  "publishConfig": {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The relay ends an AI session with `{ "type": "end", "handoffData": "<json>" }`;
3
+ * Twilio passes that string to the `<Connect action>` webhook as `HandoffData`.
4
+ * Never put personal data in it: the webhook looks anything else up by CallSid.
5
+ */
6
+ export interface HandoffData {
7
+ reasonCode: "transfer" | "completed";
8
+ reason?: string;
9
+ /** The caller described an emergency and was told to call 999: say it again if nobody answers. */
10
+ emergency?: boolean;
11
+ }
12
+
13
+ export interface ParsedHandoff {
14
+ /** `unknown` for anything unexpected, including a session that failed: treat it as a transfer. */
15
+ reasonCode: HandoffData["reasonCode"] | "unknown";
16
+ reason?: string;
17
+ emergency: boolean;
18
+ }
19
+
20
+ /** Read `HandoffData` defensively: anything unexpected is "unknown", which transfers to a person. */
21
+ export function parseHandoff(raw: string | undefined): ParsedHandoff {
22
+ if (!raw) return { reasonCode: "unknown", emergency: false };
23
+ try {
24
+ const data = JSON.parse(raw) as { reasonCode?: unknown; reason?: unknown; emergency?: unknown };
25
+ const reasonCode = data.reasonCode === "transfer" || data.reasonCode === "completed" ? data.reasonCode : "unknown";
26
+ return {
27
+ reasonCode,
28
+ reason: typeof data.reason === "string" ? data.reason.slice(0, 200) : undefined,
29
+ emergency: data.emergency === true,
30
+ };
31
+ } catch {
32
+ return { reasonCode: "unknown", emergency: false };
33
+ }
34
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `@connextar/house/voice`: the app side of a Twilio voice line. TwiML builders,
3
+ * webhook signatures, per-call session tokens, UK phone rules, opening hours and
4
+ * the transfer policy. Imports only `node:crypto`, so a Next route handler takes
5
+ * it without the relay's WebSocket server or any model SDK.
6
+ */
7
+ export {
8
+ connectConversationRelay,
9
+ DEFAULT_SAY_VOICE,
10
+ dial,
11
+ escapeXml,
12
+ gather,
13
+ hangup,
14
+ play,
15
+ reject,
16
+ response,
17
+ say,
18
+ sayAndHangup,
19
+ thenHangup,
20
+ type DialOptions,
21
+ type GatherOptions,
22
+ type RelayTwimlOptions,
23
+ type SayVoice,
24
+ } from "./twiml.js";
25
+ export { computeTwilioSignature, isValidTwilioSignature } from "./twilio-signature.js";
26
+ export {
27
+ createTwilioWebhooks,
28
+ twiml,
29
+ type TwilioParams,
30
+ type TwilioReadResult,
31
+ type TwilioWebhookConfig,
32
+ } from "./twilio-request.js";
33
+ export {
34
+ generateVoiceSessionKeys,
35
+ isUsablePublicKey,
36
+ isVoiceSessionToken,
37
+ publicKeyFor,
38
+ signVoiceSession,
39
+ verifyVoiceSession,
40
+ VOICE_SESSION_TTL_SECONDS,
41
+ type VoiceSession,
42
+ type VoiceSigner,
43
+ type VoiceVerifier,
44
+ } from "./session-token.js";
45
+ export {
46
+ divertsToAiLine,
47
+ isAllowedTransferNumber,
48
+ presentedNumber,
49
+ toE164,
50
+ TRANSFER_NUMBER_RULE,
51
+ type CallForwardingMode,
52
+ } from "./phone.js";
53
+ export {
54
+ DAY_KEYS,
55
+ describeOpeningHours,
56
+ hasOpeningHours,
57
+ isOpenAt,
58
+ nextOpening,
59
+ parseOpeningHours,
60
+ spokenTime,
61
+ type DayKey,
62
+ type OpeningHours,
63
+ } from "./opening-hours.js";
64
+ export { lineStatus, teamReachable, transferTarget, type LineHours, type LineStatus } from "./out-of-hours.js";
65
+ export { parseHandoff, type HandoffData, type ParsedHandoff } from "./handoff.js";
66
+ export {
67
+ dialTarget,
68
+ isTransferComingBack,
69
+ LOOP_WINDOW_MS,
70
+ plannedTransfer,
71
+ type ComingBackStore,
72
+ type DialRefusal,
73
+ type TransferLine,
74
+ type TransferRefusal,
75
+ type TransferRule,
76
+ type TransferRules,
77
+ type TransferStore,
78
+ } from "./transfer.js";
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Opening hours as an app stores them (JSON on its line or business row):
3
+ * `{ mon: [["09:00","18:00"]], …, sun: [] }` — a list of open intervals per day.
4
+ */
5
+ export type OpeningHours = Partial<Record<DayKey, [string, string][]>>;
6
+
7
+ export const DAY_KEYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
8
+ export type DayKey = (typeof DAY_KEYS)[number];
9
+
10
+ const DAY_NAMES: Record<DayKey, string> = {
11
+ mon: "Monday",
12
+ tue: "Tuesday",
13
+ wed: "Wednesday",
14
+ thu: "Thursday",
15
+ fri: "Friday",
16
+ sat: "Saturday",
17
+ sun: "Sunday",
18
+ };
19
+
20
+ export function parseOpeningHours(value: unknown): OpeningHours | null {
21
+ if (!value || typeof value !== "object") return null;
22
+ const hours: OpeningHours = {};
23
+ for (const day of DAY_KEYS) {
24
+ const intervals = (value as Record<string, unknown>)[day];
25
+ if (!Array.isArray(intervals)) continue;
26
+ hours[day] = intervals.filter(
27
+ (i): i is [string, string] =>
28
+ Array.isArray(i) && i.length === 2 && i.every((t) => typeof t === "string" && /^\d{2}:\d{2}$/.test(t)),
29
+ );
30
+ }
31
+ return hours;
32
+ }
33
+
34
+ /** "09:00" → "9am", "17:30" → "5:30pm", "12:00" → "12pm" — how people say times. */
35
+ export function spokenTime(hhmm: string): string {
36
+ const [h, m] = hhmm.split(":").map(Number) as [number, number];
37
+ const suffix = h >= 12 ? "pm" : "am";
38
+ const hour12 = h % 12 === 0 ? 12 : h % 12;
39
+ return m === 0 ? `${hour12}${suffix}` : `${hour12}:${String(m).padStart(2, "0")}${suffix}`;
40
+ }
41
+
42
+ function daySentence(intervals: [string, string][] | undefined): string {
43
+ if (!intervals || intervals.length === 0) return "closed";
44
+ return intervals.map(([open, close]) => `${spokenTime(open)} to ${spokenTime(close)}`).join(" and ");
45
+ }
46
+
47
+ /** "Monday to Friday 9am to 6pm, Saturday 9am to 1pm, and closed on Sunday." */
48
+ export function describeOpeningHours(hours: OpeningHours | null): string {
49
+ if (!hours) return "Opening hours haven't been set up yet.";
50
+ const groups: { from: DayKey; to: DayKey; text: string }[] = [];
51
+ for (const day of DAY_KEYS) {
52
+ const text = daySentence(hours[day]);
53
+ const last = groups[groups.length - 1];
54
+ if (last && last.text === text) last.to = day;
55
+ else groups.push({ from: day, to: day, text });
56
+ }
57
+ const parts = groups.map((g) => {
58
+ const days = g.from === g.to ? DAY_NAMES[g.from] : `${DAY_NAMES[g.from]} to ${DAY_NAMES[g.to]}`;
59
+ return g.text === "closed" ? `closed on ${days}` : `${days} ${g.text}`;
60
+ });
61
+ const sentence = parts.length > 1 ? `${parts.slice(0, -1).join(", ")}, and ${parts[parts.length - 1]}` : parts[0]!;
62
+ return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}.`;
63
+ }
64
+
65
+ /** Whether the line is open at `at` in its own timezone. */
66
+ export function isOpenAt(hours: OpeningHours | null, at: Date, timeZone = "Europe/London"): boolean {
67
+ if (!hours) return false;
68
+ const parts = new Intl.DateTimeFormat("en-GB", {
69
+ timeZone,
70
+ weekday: "short",
71
+ hour: "2-digit",
72
+ minute: "2-digit",
73
+ hourCycle: "h23",
74
+ }).formatToParts(at);
75
+ const weekday = parts
76
+ .find((p) => p.type === "weekday")
77
+ ?.value.toLowerCase()
78
+ .slice(0, 3) as DayKey | undefined;
79
+ const time = `${parts.find((p) => p.type === "hour")?.value}:${parts.find((p) => p.type === "minute")?.value}`;
80
+ if (!weekday) return false;
81
+ return (hours[weekday] ?? []).some(([open, close]) => time >= open && time < close);
82
+ }
83
+
84
+ /** Whether any opening hours are set. With none, the line is never treated as closed. */
85
+ export function hasOpeningHours(hours: OpeningHours | null): hours is OpeningHours {
86
+ return Boolean(hours && DAY_KEYS.some((d) => (hours[d] ?? []).length > 0));
87
+ }
88
+
89
+ /** The weekday and "HH:MM" at `at` in a timezone. */
90
+ function localDayAndTime(at: Date, timeZone: string): { day: number; time: string } {
91
+ const parts = new Intl.DateTimeFormat("en-GB", {
92
+ timeZone,
93
+ weekday: "short",
94
+ hour: "2-digit",
95
+ minute: "2-digit",
96
+ hourCycle: "h23",
97
+ }).formatToParts(at);
98
+ const weekday = parts
99
+ .find((p) => p.type === "weekday")
100
+ ?.value.toLowerCase()
101
+ .slice(0, 3) as DayKey;
102
+ const time = `${parts.find((p) => p.type === "hour")?.value}:${parts.find((p) => p.type === "minute")?.value}`;
103
+ return { day: DAY_KEYS.indexOf(weekday), time };
104
+ }
105
+
106
+ /**
107
+ * When the line next opens after `at`, as a caller would be told it: "at 9am today",
108
+ * "at 9am tomorrow", "at 9am on Monday". Null when no opening hours are set. Bank holidays aren't
109
+ * known here, so a bank holiday is treated as the weekday it falls on.
110
+ */
111
+ export function nextOpening(hours: OpeningHours | null, at: Date, timeZone = "Europe/London"): string | null {
112
+ if (!hasOpeningHours(hours)) return null;
113
+ const { day, time } = localDayAndTime(at, timeZone);
114
+ for (let ahead = 0; ahead <= 7; ahead++) {
115
+ const key = DAY_KEYS[(day + ahead) % 7]!;
116
+ const opens = (hours[key] ?? [])
117
+ .map(([open]) => open)
118
+ .filter((open) => ahead > 0 || open > time)
119
+ .sort()[0];
120
+ if (!opens) continue;
121
+ const when = ahead === 0 ? "today" : ahead === 1 ? "tomorrow" : `on ${DAY_NAMES[key]}`;
122
+ return `at ${spokenTime(opens)} ${when}`;
123
+ }
124
+ return null;
125
+ }
@@ -0,0 +1,48 @@
1
+ import { hasOpeningHours, isOpenAt, nextOpening, parseOpeningHours } from "./opening-hours.js";
2
+ import { toE164 } from "./phone.js";
3
+
4
+ /**
5
+ * Whether a line is open now, and where a transfer goes when it isn't.
6
+ *
7
+ * Decided here, from the opening hours, rather than by the model: whether a
8
+ * caller is put through to a person can't depend on how a reply was worded. A
9
+ * line with no opening hours set is never treated as closed.
10
+ *
11
+ * What a caller hears when a line is closed is the app's own wording, so none is
12
+ * here (PharmaLine's names NHS 111; a switchboard says when it will call back).
13
+ */
14
+
15
+ export interface LineHours {
16
+ openingHours: unknown;
17
+ timezone: string;
18
+ /** Where transfers go while closed, or null for no transfer. */
19
+ outOfHoursTransferNumber: string | null;
20
+ }
21
+
22
+ export interface LineStatus {
23
+ open: boolean;
24
+ /** "at 9am tomorrow": null while open or when no hours are set. */
25
+ opensAgain: string | null;
26
+ /** Where transfers go while closed (E.164), or null for no transfer. */
27
+ outOfHoursNumber: string | null;
28
+ }
29
+
30
+ export function lineStatus(line: LineHours, now: Date = new Date()): LineStatus {
31
+ const hours = parseOpeningHours(line.openingHours);
32
+ const open = !hasOpeningHours(hours) || isOpenAt(hours, now, line.timezone);
33
+ return {
34
+ open,
35
+ opensAgain: open ? null : nextOpening(hours, now, line.timezone),
36
+ outOfHoursNumber: toE164(line.outOfHoursTransferNumber),
37
+ };
38
+ }
39
+
40
+ /** Whether a transfer reaches a person right now: open, or closed with an out-of-hours number. */
41
+ export function teamReachable(status: LineStatus): boolean {
42
+ return status.open || Boolean(status.outOfHoursNumber);
43
+ }
44
+
45
+ /** The number a transfer rings now, or null when the caller should hear the closed line instead. */
46
+ export function transferTarget(status: LineStatus, transferNumber: string | null): string | null {
47
+ return status.open ? toE164(transferNumber) : status.outOfHoursNumber;
48
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Normalise a UK-style or international phone number to E.164 (`+441614960000`) so numbers typed
3
+ * into Settings ("0161 496 0000") match what the carrier sends. Returns null when it can't be a
4
+ * phone number.
5
+ */
6
+ export function toE164(value: string | null | undefined, defaultCountryCode = "44"): string | null {
7
+ if (!value) return null;
8
+ const trimmed = value.trim();
9
+ const digits = trimmed.replace(/\D/g, "");
10
+ if (!digits) return null;
11
+
12
+ let e164: string;
13
+ if (trimmed.startsWith("+")) e164 = `+${digits}`;
14
+ else if (digits.startsWith("00")) e164 = `+${digits.slice(2)}`;
15
+ else if (digits.startsWith("0")) e164 = `+${defaultCountryCode}${digits.slice(1)}`;
16
+ else e164 = `+${digits}`;
17
+
18
+ // E.164 allows up to 15 digits; anything shorter than 8 isn't a dialable line.
19
+ const length = e164.length - 1;
20
+ return length >= 8 && length <= 15 ? e164 : null;
21
+ }
22
+
23
+ /**
24
+ * Whether the platform may dial this number to put a caller through to staff.
25
+ *
26
+ * Every transfer is dialled from the app's own Twilio account, and an owner sets the transfer
27
+ * and out-of-hours numbers themselves — so a number that earns money when called (premium 09,
28
+ * revenue-sharing 084/087, personal 070) or costs a lot to reach (international) would let anyone
29
+ * who can make the line transfer run up the platform's bill (security round 3, finding 7). A
30
+ * team answers on a UK landline (01, 02), a non-geographic 03, a mobile (07, but not 070
31
+ * personal numbers or 076 pagers), or freephone (0800, 0808). Takes an E.164 number.
32
+ */
33
+ export function isAllowedTransferNumber(e164: string | null | undefined): boolean {
34
+ return Boolean(e164 && /^\+44(?:1\d{8,9}|2\d{9}|3\d{9}|7[1-57-9]\d{8}|80[08]\d{6,7})$/.test(e164));
35
+ }
36
+
37
+ /**
38
+ * Carrier stand-ins for a number that isn't presented — withheld, restricted, unavailable — which
39
+ * Twilio sends in place of a caller ID. Thousands of callers share each, so none is a caller.
40
+ */
41
+ const NOT_A_CALLER = new Set(["+266696687", "+86282452253", "+7378742833", "+2562533", "+8656696"]);
42
+
43
+ /** A caller's own number as presented, or null when it is withheld or not a number. */
44
+ export function presentedNumber(value: string | null | undefined): string | null {
45
+ const digits = value?.replace(/[^\d+]/g, "");
46
+ if (!digits || !/^\+\d{8,15}$/.test(digits) || NOT_A_CALLER.has(digits)) return null;
47
+ return digits;
48
+ }
49
+
50
+ /** What an owner is told when a number is refused. */
51
+ export const TRANSFER_NUMBER_RULE =
52
+ "Use a UK landline, mobile or freephone number (01, 02, 03, 07 or 0800/0808) — premium, personal and international numbers can't be used";
53
+
54
+ /** How a line's own number reaches the AI line (PharmaLine's `Organization.callForwarding`). */
55
+ export type CallForwardingMode = "EVERY_CALL" | "EVERY_CALL_EXCEPT_AI_LINE" | "BUSY_OR_UNANSWERED";
56
+
57
+ /**
58
+ * Whether ringing `number` reaches the AI line again rather than a person: it is the line's own
59
+ * number, and every call to that is diverted to the AI line. `dialTarget` never dials it, and an
60
+ * app's settings should warn when a transfer number is one.
61
+ */
62
+ export function divertsToAiLine(
63
+ line: { phone: string | null; callForwarding: CallForwardingMode | null },
64
+ number: string | null,
65
+ ): boolean {
66
+ const own = toE164(line.phone);
67
+ return line.callForwarding === "EVERY_CALL" && Boolean(own) && toE164(number) === own;
68
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The relay's side of an app's agent API: JSON over HTTPS with the call's
3
+ * session token as a Bearer token, and every answer in the `{ success, data }`
4
+ * shape the house apps use. The routes and their bodies are the app's own.
5
+ */
6
+
7
+ export class AgentApiError extends Error {
8
+ constructor(
9
+ message: string,
10
+ readonly status?: number,
11
+ ) {
12
+ super(message);
13
+ this.name = "AgentApiError";
14
+ }
15
+ }
16
+
17
+ export interface AgentFetch {
18
+ get<T>(path: string): Promise<T>;
19
+ post<T>(path: string, body: unknown): Promise<T>;
20
+ }
21
+
22
+ export interface AgentFetchOptions {
23
+ /** The app's base URL, such as `https://support.example.com`. */
24
+ baseUrl: string;
25
+ /** The call's session token. */
26
+ sessionToken: string;
27
+ /** Per-request timeout. Default 8 s: a caller is waiting. */
28
+ timeoutMs?: number;
29
+ fetch?: typeof fetch;
30
+ }
31
+
32
+ export function createAgentFetch(o: AgentFetchOptions): AgentFetch {
33
+ const timeoutMs = o.timeoutMs ?? 8_000;
34
+ const doFetch = o.fetch ?? fetch;
35
+
36
+ async function call<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
37
+ const response = await doFetch(new URL(path, o.baseUrl), {
38
+ method,
39
+ headers: {
40
+ authorization: `Bearer ${o.sessionToken}`,
41
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
42
+ },
43
+ body: body === undefined ? undefined : JSON.stringify(body),
44
+ signal: AbortSignal.timeout(timeoutMs),
45
+ });
46
+ type Answer = { success?: boolean; data?: T; error?: { message?: string } | string };
47
+ let json: Answer | null;
48
+ try {
49
+ json = (await response.json()) as Answer;
50
+ } catch {
51
+ json = null;
52
+ }
53
+ if (!response.ok || !json || json.success === false) {
54
+ const message = typeof json?.error === "string" ? json.error : json?.error?.message;
55
+ throw new AgentApiError(message ?? `Agent API ${method} ${path} failed (${response.status})`, response.status);
56
+ }
57
+ return json.data as T;
58
+ }
59
+
60
+ return {
61
+ get: (path) => call("GET", path),
62
+ post: (path, body) => call("POST", path, body),
63
+ };
64
+ }