@kalangu/sim 0.0.0-stage → 0.1.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdoullah Ndao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @kalangu/sim
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A simulated keypad phone for [Kalangu](https://github.com/utachicodes/kalangu)
4
+ agents: dial codes, read USSD screens, answer, and receive SMS, in your
5
+ terminal or in tests. No gateway account, no network.
6
+
7
+ > Alpha. The API may change before 1.0.
8
+
9
+ ```sh
10
+ pnpm add -D @kalangu/sim
11
+ ```
12
+
13
+ In a terminal:
14
+
15
+ ```ts
16
+ import { runTerminal } from "@kalangu/sim";
17
+
18
+ await runTerminal(agent, { code: "*384*1#", sender: "CLINIC" });
19
+ // Dial> *384*1# x hangs up · sms <text> texts the agent · q quits
20
+ ```
21
+
22
+ In tests:
23
+
24
+ ```ts
25
+ import { createPhone } from "@kalangu/sim";
26
+
27
+ const phone = createPhone(agent, { code: "*384*1#" });
28
+ await phone.dial("*384*1#"); // { text: "Clinic line\n1. ...", end: false }
29
+ await phone.press("1");
30
+ phone.hangUp(); // dial again to resume
31
+ phone.onSms((sms) => console.log(sms.text));
32
+ ```
33
+
34
+ The simulator replaces the agent's channels with its own, so a real SMS
35
+ channel is never called.
36
+
37
+ MIT licensed.
@@ -0,0 +1,7 @@
1
+ export { SIM_SMS_CHANNEL, SIM_USSD_CHANNEL, SimPhone, createPhone } from "./phone.js";
2
+ export type { Screen, SimPhoneOptions, SimSms } from "./phone.js";
3
+ export { box, formatSms, runTerminal } from "./terminal.js";
4
+ export type { TerminalOptions } from "./terminal.js";
5
+ export { createFakeProvider } from "./payments/fakeProvider.js";
6
+ export type { FakeProviderOptions } from "./payments/fakeProvider.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACtF,YAAY,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5D,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAErD,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,YAAY,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { SIM_SMS_CHANNEL, SIM_USSD_CHANNEL, SimPhone, createPhone } from "./phone.js";
2
+ export { box, formatSms, runTerminal } from "./terminal.js";
3
+ export { createFakeProvider } from "./payments/fakeProvider.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtF,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Fake payment provider for the simulator and tests (docs/payments-design.md
3
+ * §10, packages/sim).
4
+ *
5
+ * It settles a payment after a delay. No network, no real money, no pawaPay. Intended for local
6
+ * development only — never configured with a real provider token.
7
+ */
8
+ import type { PaymentProvider } from "@kalangu/core";
9
+ export interface FakeProviderOptions {
10
+ /** Provider code reported to the agent. Default "FAKE_MOMO". */
11
+ readonly provider?: string;
12
+ /** Country reported by resolve. Default "XA". */
13
+ readonly country?: string;
14
+ /** Milliseconds before an initiated payment auto-settles. Default 3000. */
15
+ readonly settleAfterMs?: number;
16
+ /** If true, a payment settles as FAILED instead of COMPLETED. */
17
+ readonly alwaysFail?: boolean;
18
+ /** If true, resolve returns a refusal instead of a provider choice. */
19
+ readonly alwaysRefuse?: boolean;
20
+ }
21
+ /**
22
+ * Creates a fake provider. Outcomes are driven by `status()`. Use
23
+ * `settleAfterMs` to simulate a slow provider; `alwaysFail` / `alwaysRefuse`
24
+ * to simulate failure paths. No network, no real money.
25
+ */
26
+ export declare function createFakeProvider(options?: FakeProviderOptions): PaymentProvider;
27
+ //# sourceMappingURL=fakeProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fakeProvider.d.ts","sourceRoot":"","sources":["../../src/payments/fakeProvider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAEV,eAAe,EAIhB,MAAM,eAAe,CAAC;AAEvB,MAAM,WAAW,mBAAmB;IAClC,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,2EAA2E;IAC3E,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,iEAAiE;IACjE,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B,uEAAuE;IACvE,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,GAAE,mBAAwB,GAChC,eAAe,CAuCjB"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Fake payment provider for the simulator and tests (docs/payments-design.md
3
+ * §10, packages/sim).
4
+ *
5
+ * It settles a payment after a delay. No network, no real money, no pawaPay. Intended for local
6
+ * development only — never configured with a real provider token.
7
+ */
8
+ /**
9
+ * Creates a fake provider. Outcomes are driven by `status()`. Use
10
+ * `settleAfterMs` to simulate a slow provider; `alwaysFail` / `alwaysRefuse`
11
+ * to simulate failure paths. No network, no real money.
12
+ */
13
+ export function createFakeProvider(options = {}) {
14
+ const provider = options.provider ?? "FAKE_MOMO";
15
+ const country = options.country ?? "XA";
16
+ const settleAfterMs = options.settleAfterMs ?? 3000;
17
+ const alwaysFail = options.alwaysFail ?? false;
18
+ const alwaysRefuse = options.alwaysRefuse ?? false;
19
+ const initiatedAt = new Map();
20
+ return {
21
+ id: "fake",
22
+ async resolve(_phone, _amount, _currency) {
23
+ if (alwaysRefuse) {
24
+ const refusal = {
25
+ kind: "provider-closed",
26
+ message: "Payments with your operator are unavailable right now.",
27
+ };
28
+ return refusal;
29
+ }
30
+ const choice = {
31
+ provider,
32
+ phone: _phone.replace(/^\+/, ""),
33
+ country,
34
+ };
35
+ return choice;
36
+ },
37
+ async initiate(payment) {
38
+ // Accepted now; the outcome shows up in status() once the delay has passed.
39
+ if (!initiatedAt.has(payment.id))
40
+ initiatedAt.set(payment.id, Date.now());
41
+ return { status: "ACCEPTED" };
42
+ },
43
+ async status(id) {
44
+ const started = initiatedAt.get(id);
45
+ // Like the real thing, a payment that was never initiated is not found.
46
+ if (started === undefined)
47
+ return { found: false };
48
+ if (Date.now() - started < settleAfterMs)
49
+ return { found: true, status: "PROCESSING" };
50
+ return { found: true, status: alwaysFail ? "FAILED" : "COMPLETED" };
51
+ },
52
+ };
53
+ }
54
+ //# sourceMappingURL=fakeProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fakeProvider.js","sourceRoot":"","sources":["../../src/payments/fakeProvider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAuBH;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAO,GAAwB,EAAE;IAEjC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,WAAW,CAAC;IACjD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC;IACxC,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,IAAI,CAAC;IACpD,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC;IAC/C,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,KAAK,CAAC;IAEnD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE9C,OAAO;QACL,EAAE,EAAE,MAAM;QACV,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAe,EAAE,SAAiB;YAC9D,IAAI,YAAY,EAAE,CAAC;gBACjB,MAAM,OAAO,GAAY;oBACvB,IAAI,EAAE,iBAAiB;oBACvB,OAAO,EAAE,wDAAwD;iBAClE,CAAC;gBACF,OAAO,OAAO,CAAC;YACjB,CAAC;YACD,MAAM,MAAM,GAAmB;gBAC7B,QAAQ;gBACR,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;gBAChC,OAAO;aACR,CAAC;YACF,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,OAAO;YACpB,4EAA4E;YAC5E,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;gBAAE,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;YAC1E,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;QAChC,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,EAAU;YACrB,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpC,wEAAwE;YACxE,IAAI,OAAO,KAAK,SAAS;gBAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;YACnD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,GAAG,aAAa;gBAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;YACvF,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;QACtE,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A simulated keypad phone (docs/design.md §8). It drives the agent
3
+ * directly, with no HTTP and no gateway, through a USSD-style channel for
4
+ * screens and an SMS-style channel whose "sending" lands in the phone's inbox.
5
+ */
6
+ import { type Agent } from "@kalangu/core";
7
+ export interface SimPhoneOptions {
8
+ /** The simulated subscriber's number. Default "+254700000001". */
9
+ phone?: string;
10
+ /** The service code that reaches the agent, e.g. "*384*1#". Any code works when omitted. */
11
+ code?: string;
12
+ /** Characters per USSD screen. Default 160. */
13
+ maxScreenChars?: number;
14
+ /** Shown in the terminal header only. Default "Safaricom KE". */
15
+ operator?: string;
16
+ /** Sender name shown on SMS from the agent. Default "AGENT". */
17
+ sender?: string;
18
+ }
19
+ export interface Screen {
20
+ text: string;
21
+ /** True when the session ended with this screen. */
22
+ end: boolean;
23
+ }
24
+ export interface SimSms {
25
+ from: string;
26
+ text: string;
27
+ at: Date;
28
+ }
29
+ export declare const SIM_USSD_CHANNEL = "sim-ussd";
30
+ export declare const SIM_SMS_CHANNEL = "sim-sms";
31
+ export declare class SimPhone {
32
+ readonly number: string;
33
+ readonly operator: string;
34
+ readonly sender: string;
35
+ readonly inbox: SimSms[];
36
+ /** The agent rewired to the simulator's channels. */
37
+ readonly agent: Agent;
38
+ private readonly code;
39
+ private listeners;
40
+ private session;
41
+ private sessions;
42
+ constructor(agent: Agent, options?: SimPhoneOptions);
43
+ get inSession(): boolean;
44
+ /**
45
+ * Dials a service code. A code with choices in it (`*384*1*2#`) carries
46
+ * them in, as on a real network.
47
+ */
48
+ dial(code: string): Promise<Screen>;
49
+ /** Sends a reply in the current session. */
50
+ press(input: string): Promise<Screen>;
51
+ /** Drops the session, as when the user cancels or the network times out. */
52
+ hangUp(): void;
53
+ /** Sends an SMS to the agent; its reply, if any, lands in the inbox. */
54
+ sendSms(text: string): Promise<void>;
55
+ /** Calls `listener` for every SMS that arrives. Returns an unsubscribe function. */
56
+ onSms(listener: (sms: SimSms) => void): () => void;
57
+ private exchange;
58
+ private receive;
59
+ /** The inputs carried by a dialed code, or null when it doesn't reach the agent. */
60
+ private parseCode;
61
+ }
62
+ export declare function createPhone(agent: Agent, options?: SimPhoneOptions): SimPhone;
63
+ //# sourceMappingURL=phone.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phone.d.ts","sourceRoot":"","sources":["../src/phone.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAA2B,KAAK,KAAK,EAAE,MAAM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G,OAAO,CAAC,MAAM,CAAC,CAI1C;IAED,4EAA4E;IAC5E,MAAM,IAAI,IAAI,CAEb;IAED,wEAAwE;IAClE,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAGzC;IAED,oFAAoF;IACpF,KAAK,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAKjD;YAEa,QAAQ;IAetB,OAAO,CAAC,OAAO;IAMf,oFAAoF;IACpF,OAAO,CAAC,SAAS;CAQlB;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAEjF"}
package/dist/phone.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A simulated keypad phone (docs/design.md §8). It drives the agent
3
+ * directly, with no HTTP and no gateway, through a USSD-style channel for
4
+ * screens and an SMS-style channel whose "sending" lands in the phone's inbox.
5
+ */
6
+ import { smsChannel, ussdChannel } from "@kalangu/core";
7
+ export const SIM_USSD_CHANNEL = "sim-ussd";
8
+ export const SIM_SMS_CHANNEL = "sim-sms";
9
+ export class SimPhone {
10
+ number;
11
+ operator;
12
+ sender;
13
+ inbox = [];
14
+ /** The agent rewired to the simulator's channels. */
15
+ agent;
16
+ code;
17
+ listeners = [];
18
+ session = null;
19
+ sessions = 0;
20
+ constructor(agent, options = {}) {
21
+ this.number = options.phone ?? "+254700000001";
22
+ this.operator = options.operator ?? "Safaricom KE";
23
+ this.sender = options.sender ?? "AGENT";
24
+ this.code = options.code;
25
+ this.agent = agent.withChannels([
26
+ ussdChannel({
27
+ id: SIM_USSD_CHANNEL,
28
+ ...(options.maxScreenChars !== undefined ? { budget: { maxChars: options.maxScreenChars } } : {}),
29
+ }),
30
+ smsChannel({
31
+ id: SIM_SMS_CHANNEL,
32
+ send: async (out) => {
33
+ if (out.to === this.number)
34
+ this.receive(out.text);
35
+ },
36
+ }),
37
+ ]);
38
+ }
39
+ get inSession() {
40
+ return this.session !== null;
41
+ }
42
+ /**
43
+ * Dials a service code. A code with choices in it (`*384*1*2#`) carries
44
+ * them in, as on a real network.
45
+ */
46
+ async dial(code) {
47
+ const inputs = this.parseCode(code.trim());
48
+ if (inputs === null) {
49
+ return { text: "Connection problem or invalid MMI code.", end: true };
50
+ }
51
+ this.sessions += 1;
52
+ this.session = { id: `sim-${this.sessions}`, inputs };
53
+ return this.exchange(inputs.at(-1) ?? "", inputs.length === 0);
54
+ }
55
+ /** Sends a reply in the current session. */
56
+ async press(input) {
57
+ if (!this.session)
58
+ throw new Error("No USSD session; dial a code first");
59
+ this.session.inputs.push(input);
60
+ return this.exchange(input, false);
61
+ }
62
+ /** Drops the session, as when the user cancels or the network times out. */
63
+ hangUp() {
64
+ this.session = null;
65
+ }
66
+ /** Sends an SMS to the agent; its reply, if any, lands in the inbox. */
67
+ async sendSms(text) {
68
+ const outcome = await this.agent.handle({ channel: SIM_SMS_CHANNEL, phone: this.number, input: text });
69
+ this.receive(outcome.text);
70
+ }
71
+ /** Calls `listener` for every SMS that arrives. Returns an unsubscribe function. */
72
+ onSms(listener) {
73
+ this.listeners.push(listener);
74
+ return () => {
75
+ this.listeners = this.listeners.filter((l) => l !== listener);
76
+ };
77
+ }
78
+ async exchange(input, newSession) {
79
+ const session = this.session;
80
+ if (!session)
81
+ throw new Error("No USSD session");
82
+ const outcome = await this.agent.handle({
83
+ channel: SIM_USSD_CHANNEL,
84
+ phone: this.number,
85
+ input,
86
+ inputs: [...session.inputs],
87
+ newSession,
88
+ gatewaySessionId: session.id,
89
+ });
90
+ if (outcome.end)
91
+ this.session = null;
92
+ return { text: outcome.text, end: outcome.end };
93
+ }
94
+ receive(text) {
95
+ const sms = { from: this.sender, text, at: new Date() };
96
+ this.inbox.push(sms);
97
+ for (const listener of this.listeners)
98
+ listener(sms);
99
+ }
100
+ /** The inputs carried by a dialed code, or null when it doesn't reach the agent. */
101
+ parseCode(code) {
102
+ if (!/^\*[0-9*#]*#$/.test(code))
103
+ return null;
104
+ if (!this.code)
105
+ return [];
106
+ if (code === this.code)
107
+ return [];
108
+ const prefix = this.code.slice(0, -1) + "*";
109
+ if (!code.startsWith(prefix))
110
+ return null;
111
+ return code.slice(prefix.length, -1).split("*");
112
+ }
113
+ }
114
+ export function createPhone(agent, options = {}) {
115
+ return new SimPhone(agent, options);
116
+ }
117
+ //# sourceMappingURL=phone.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phone.js","sourceRoot":"","sources":["../src/phone.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAc,MAAM,eAAe,CAAC;AA2BpE,MAAM,CAAC,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAC3C,MAAM,CAAC,MAAM,eAAe,GAAG,SAAS,CAAC;AAEzC,MAAM,OAAO,QAAQ;IACV,MAAM,CAAS;IACf,QAAQ,CAAS;IACjB,MAAM,CAAS;IACf,KAAK,GAAa,EAAE,CAAC;IAC9B,qDAAqD;IAC5C,KAAK,CAAQ;IAEL,IAAI,CAAqB;IAClC,SAAS,GAAiC,EAAE,CAAC;IAC7C,OAAO,GAA4C,IAAI,CAAC;IACxD,QAAQ,GAAG,CAAC,CAAC;IAErB,YAAY,KAAY,EAAE,OAAO,GAAoB,EAAE;QACrD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,IAAI,eAAe,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,cAAc,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC;QACxC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC;YAC9B,WAAW,CAAC;gBACV,EAAE,EAAE,gBAAgB;gBACpB,GAAG,CAAC,OAAO,CAAC,cAAc,KAAK,SAAS,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>` texts the
4
+ * agent, `q` quits.
5
+ */
6
+ import type { Agent } from "@kalangu/core";
7
+ import { SimPhone, type Screen, type SimPhoneOptions, type SimSms } from "./phone.js";
8
+ export interface TerminalOptions extends SimPhoneOptions {
9
+ input?: NodeJS.ReadableStream;
10
+ output?: NodeJS.WritableStream;
11
+ /** Width of the screen box's text area. Default 34. */
12
+ width?: number;
13
+ }
14
+ /** Runs the simulator until the user quits or input ends. */
15
+ export declare function runTerminal(agent: Agent, options?: TerminalOptions): Promise<SimPhone>;
16
+ /** Draws a screen in a box, wrapping long lines. Final screens show `END`. */
17
+ export declare function box(screen: Screen, width?: number): string;
18
+ export declare function formatSms(sms: SimSms): string;
19
+ //# sourceMappingURL=terminal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,KAAK,MAAM,EAAE,KAAK,eAAe,EAAE,KAAK,MAAM,EAAE,MAAM,YAAY,CAAC;AAEtF,MAAM,WAAW,eAAgB,SAAQ,eAAe;IACtD,KAAK,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;IAC/B,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,6DAA6D;AAC7D,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwE1F;AAED,8EAA8E;AAC9E,wBAAgB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,SAAK,GAAG,MAAM,CAKtD;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE7C"}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The terminal front end for `SimPhone`: dial, read boxed screens, answer,
3
+ * and watch SMS arrive. Commands: `x` hangs up, `sms <text>` texts the
4
+ * agent, `q` quits.
5
+ */
6
+ import { createInterface } from "node:readline";
7
+ import { SimPhone } from "./phone.js";
8
+ /** Runs the simulator until the user quits or input ends. */
9
+ export function runTerminal(agent, options = {}) {
10
+ const input = options.input ?? process.stdin;
11
+ const output = options.output ?? process.stdout;
12
+ const width = options.width ?? 34;
13
+ const phone = new SimPhone(agent, options);
14
+ const tty = output.isTTY === true;
15
+ const rl = createInterface({ input, output, terminal: tty });
16
+ const write = (text) => output.write(`${text}\n`);
17
+ let prompt = "Dial> ";
18
+ let busy = false;
19
+ const showPrompt = () => {
20
+ rl.setPrompt(prompt);
21
+ rl.prompt();
22
+ };
23
+ phone.onSms((sms) => {
24
+ // Print above whatever the user is typing, then restore the prompt.
25
+ if (tty)
26
+ output.write("\r\x1b[K");
27
+ else
28
+ output.write("\n");
29
+ write(formatSms(sms));
30
+ if (!busy)
31
+ showPrompt();
32
+ });
33
+ write(`│ Simulated phone: ${formatNumber(phone.number)} (${phone.operator})`);
34
+ write(`│ Dial ${options.code ?? "a code such as *384#"} · x hangs up · sms <text> texts the agent · q quits`);
35
+ showPrompt();
36
+ return new Promise((resolve) => {
37
+ let queue = Promise.resolve();
38
+ rl.on("line", (line) => {
39
+ queue = queue.then(async () => {
40
+ busy = true;
41
+ const keep = await handleLine(line.trim());
42
+ busy = false;
43
+ if (keep)
44
+ showPrompt();
45
+ else
46
+ rl.close();
47
+ });
48
+ });
49
+ rl.on("close", () => {
50
+ void queue.then(() => resolve(phone));
51
+ });
52
+ });
53
+ async function handleLine(line) {
54
+ if (line === "q")
55
+ return false;
56
+ if (line === "x") {
57
+ if (phone.inSession)
58
+ write("… hung up. Dial again to resume where you left off.");
59
+ phone.hangUp();
60
+ prompt = "Dial> ";
61
+ return true;
62
+ }
63
+ if (line.startsWith("sms ")) {
64
+ await phone.sendSms(line.slice(4));
65
+ return true;
66
+ }
67
+ if (line === "")
68
+ return true;
69
+ let screen;
70
+ try {
71
+ screen = phone.inSession ? await phone.press(line) : await phone.dial(line);
72
+ }
73
+ catch (err) {
74
+ write(`! ${err instanceof Error ? err.message : String(err)}`);
75
+ return true;
76
+ }
77
+ write(box(screen, width));
78
+ prompt = screen.end ? "Dial> " : looksLikeMenu(screen.text) ? "Choice> " : "Input> ";
79
+ return true;
80
+ }
81
+ }
82
+ /** Draws a screen in a box, wrapping long lines. Final screens show `END`. */
83
+ export function box(screen, width = 34) {
84
+ const text = screen.end ? `END ${screen.text}` : screen.text;
85
+ const lines = text.split("\n").flatMap((line) => wrap(line, width));
86
+ const edge = "─".repeat(width + 2);
87
+ return [`┌${edge}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${edge}┘`].join("\n");
88
+ }
89
+ export function formatSms(sms) {
90
+ return `✉ SMS from ${sms.from}: ${sms.text}`;
91
+ }
92
+ function wrap(line, width) {
93
+ if (line.length <= width)
94
+ return [line];
95
+ const out = [];
96
+ let current = "";
97
+ for (const word of line.split(" ")) {
98
+ if (word.length > width) {
99
+ if (current)
100
+ out.push(current);
101
+ for (let i = 0; i < word.length; i += width)
102
+ out.push(word.slice(i, i + width));
103
+ current = out.pop() ?? "";
104
+ continue;
105
+ }
106
+ if (current === "")
107
+ current = word;
108
+ else if (current.length + 1 + word.length <= width)
109
+ current += ` ${word}`;
110
+ else {
111
+ out.push(current);
112
+ current = word;
113
+ }
114
+ }
115
+ if (current)
116
+ out.push(current);
117
+ return out;
118
+ }
119
+ function looksLikeMenu(text) {
120
+ return text.split("\n").some((line) => /^\d+\. /.test(line));
121
+ }
122
+ function formatNumber(phone) {
123
+ const m = /^\+(\d{3})(\d{3})(\d{3})(\d{3})$/.exec(phone);
124
+ return m ? `+${m[1]} ${m[2]} ${m[3]} ${m[4]}` : phone;
125
+ }
126
+ //# sourceMappingURL=terminal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.js","sourceRoot":"","sources":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IAAI,OAAO,KAAK,EAAE;YAAE,OAAO,GAAG,IAAI,CAAC;aAC9B,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK;YAAE,OAAO,IAAI,IAAI,IAAI,EAAE,CAAC;aACrE,CAAC;YACJ,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAClB,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IACD,IAAI,OAAO;QAAE,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/B,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,CAAC,GAAG,kCAAkC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzD,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AACxD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@kalangu/sim",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Terminal keypad-phone simulator for Kalangu agents. No gateway, no network.",
5
+ "keywords": [
6
+ "ussd",
7
+ "sms",
8
+ "simulator",
9
+ "testing",
10
+ "agents",
11
+ "keypad"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Abdoullah Ndao",
15
+ "homepage": "https://github.com/utachicodes/kalangu/tree/main/packages/sim#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/utachicodes/kalangu.git",
19
+ "directory": "packages/sim"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/utachicodes/kalangu/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "types": "./dist/index.d.ts",
36
+ "files": [
37
+ "dist",
38
+ "src",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "tag": "alpha"
45
+ },
46
+ "dependencies": {
47
+ "@kalangu/core": "0.1.0-alpha.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "typecheck": "tsc -p tsconfig.json --noEmit",
52
+ "test": "vitest run"
53
+ }
6
54
  }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { SIM_SMS_CHANNEL, SIM_USSD_CHANNEL, SimPhone, createPhone } from "./phone.js";
2
+ export type { Screen, SimPhoneOptions, SimSms } from "./phone.js";
3
+ export { box, formatSms, runTerminal } from "./terminal.js";
4
+ export type { TerminalOptions } from "./terminal.js";
5
+
6
+ export { createFakeProvider } from "./payments/fakeProvider.js";
7
+ export type { FakeProviderOptions } from "./payments/fakeProvider.js";
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Fake payment provider for the simulator and tests (docs/payments-design.md
3
+ * §10, packages/sim).
4
+ *
5
+ * It settles a payment after a delay. No network, no real money, no pawaPay. Intended for local
6
+ * development only — never configured with a real provider token.
7
+ */
8
+
9
+ import type {
10
+ InitiateResult,
11
+ PaymentProvider,
12
+ ProviderChoice,
13
+ Refusal,
14
+ StatusResult,
15
+ } from "@kalangu/core";
16
+
17
+ export interface FakeProviderOptions {
18
+ /** Provider code reported to the agent. Default "FAKE_MOMO". */
19
+ readonly provider?: string;
20
+ /** Country reported by resolve. Default "XA". */
21
+ readonly country?: string;
22
+ /** Milliseconds before an initiated payment auto-settles. Default 3000. */
23
+ readonly settleAfterMs?: number;
24
+ /** If true, a payment settles as FAILED instead of COMPLETED. */
25
+ readonly alwaysFail?: boolean;
26
+ /** If true, resolve returns a refusal instead of a provider choice. */
27
+ readonly alwaysRefuse?: boolean;
28
+ }
29
+
30
+ /**
31
+ * Creates a fake provider. Outcomes are driven by `status()`. Use
32
+ * `settleAfterMs` to simulate a slow provider; `alwaysFail` / `alwaysRefuse`
33
+ * to simulate failure paths. No network, no real money.
34
+ */
35
+ export function createFakeProvider(
36
+ options: FakeProviderOptions = {},
37
+ ): PaymentProvider {
38
+ const provider = options.provider ?? "FAKE_MOMO";
39
+ const country = options.country ?? "XA";
40
+ const settleAfterMs = options.settleAfterMs ?? 3000;
41
+ const alwaysFail = options.alwaysFail ?? false;
42
+ const alwaysRefuse = options.alwaysRefuse ?? false;
43
+
44
+ const initiatedAt = new Map<string, number>();
45
+
46
+ return {
47
+ id: "fake",
48
+ async resolve(_phone: string, _amount: string, _currency: string) {
49
+ if (alwaysRefuse) {
50
+ const refusal: Refusal = {
51
+ kind: "provider-closed",
52
+ message: "Payments with your operator are unavailable right now.",
53
+ };
54
+ return refusal;
55
+ }
56
+ const choice: ProviderChoice = {
57
+ provider,
58
+ phone: _phone.replace(/^\+/, ""),
59
+ country,
60
+ };
61
+ return choice;
62
+ },
63
+ async initiate(payment): Promise<InitiateResult> {
64
+ // Accepted now; the outcome shows up in status() once the delay has passed.
65
+ if (!initiatedAt.has(payment.id)) initiatedAt.set(payment.id, Date.now());
66
+ return { status: "ACCEPTED" };
67
+ },
68
+ async status(id: string): Promise<StatusResult> {
69
+ const started = initiatedAt.get(id);
70
+ // Like the real thing, a payment that was never initiated is not found.
71
+ if (started === undefined) return { found: false };
72
+ if (Date.now() - started < settleAfterMs) return { found: true, status: "PROCESSING" };
73
+ return { found: true, status: alwaysFail ? "FAILED" : "COMPLETED" };
74
+ },
75
+ };
76
+ }
package/src/phone.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * A simulated keypad phone (docs/design.md §8). It drives the agent
3
+ * directly, with no HTTP and no gateway, through a USSD-style channel for
4
+ * screens and an SMS-style channel whose "sending" lands in the phone's inbox.
5
+ */
6
+
7
+ import { smsChannel, ussdChannel, type Agent } from "@kalangu/core";
8
+
9
+ export interface SimPhoneOptions {
10
+ /** The simulated subscriber's number. Default "+254700000001". */
11
+ phone?: string;
12
+ /** The service code that reaches the agent, e.g. "*384*1#". Any code works when omitted. */
13
+ code?: string;
14
+ /** Characters per USSD screen. Default 160. */
15
+ maxScreenChars?: number;
16
+ /** Shown in the terminal header only. Default "Safaricom KE". */
17
+ operator?: string;
18
+ /** Sender name shown on SMS from the agent. Default "AGENT". */
19
+ sender?: string;
20
+ }
21
+
22
+ export interface Screen {
23
+ text: string;
24
+ /** True when the session ended with this screen. */
25
+ end: boolean;
26
+ }
27
+
28
+ export interface SimSms {
29
+ from: string;
30
+ text: string;
31
+ at: Date;
32
+ }
33
+
34
+ export const SIM_USSD_CHANNEL = "sim-ussd";
35
+ export const SIM_SMS_CHANNEL = "sim-sms";
36
+
37
+ export class SimPhone {
38
+ readonly number: string;
39
+ readonly operator: string;
40
+ readonly sender: string;
41
+ readonly inbox: SimSms[] = [];
42
+ /** The agent rewired to the simulator's channels. */
43
+ readonly agent: Agent;
44
+
45
+ private readonly code: string | undefined;
46
+ private listeners: Array<(sms: SimSms) => void> = [];
47
+ private session: { id: string; inputs: string[] } | null = null;
48
+ private sessions = 0;
49
+
50
+ constructor(agent: Agent, options: SimPhoneOptions = {}) {
51
+ this.number = options.phone ?? "+254700000001";
52
+ this.operator = options.operator ?? "Safaricom KE";
53
+ this.sender = options.sender ?? "AGENT";
54
+ this.code = options.code;
55
+ this.agent = agent.withChannels([
56
+ ussdChannel({
57
+ id: SIM_USSD_CHANNEL,
58
+ ...(options.maxScreenChars !== undefined ? { budget: { maxChars: options.maxScreenChars } } : {}),
59
+ }),
60
+ smsChannel({
61
+ id: SIM_SMS_CHANNEL,
62
+ send: async (out) => {
63
+ if (out.to === this.number) this.receive(out.text);
64
+ },
65
+ }),
66
+ ]);
67
+ }
68
+
69
+ get inSession(): boolean {
70
+ return this.session !== null;
71
+ }
72
+
73
+ /**
74
+ * Dials a service code. A code with choices in it (`*384*1*2#`) carries
75
+ * them in, as on a real network.
76
+ */
77
+ async dial(code: string): Promise<Screen> {
78
+ const inputs = this.parseCode(code.trim());
79
+ if (inputs === null) {
80
+ return { text: "Connection problem or invalid MMI code.", end: true };
81
+ }
82
+ this.sessions += 1;
83
+ this.session = { id: `sim-${this.sessions}`, inputs };
84
+ return this.exchange(inputs.at(-1) ?? "", inputs.length === 0);
85
+ }
86
+
87
+ /** Sends a reply in the current session. */
88
+ async press(input: string): Promise<Screen> {
89
+ if (!this.session) throw new Error("No USSD session; dial a code first");
90
+ this.session.inputs.push(input);
91
+ return this.exchange(input, false);
92
+ }
93
+
94
+ /** Drops the session, as when the user cancels or the network times out. */
95
+ hangUp(): void {
96
+ this.session = null;
97
+ }
98
+
99
+ /** Sends an SMS to the agent; its reply, if any, lands in the inbox. */
100
+ async sendSms(text: string): Promise<void> {
101
+ const outcome = await this.agent.handle({ channel: SIM_SMS_CHANNEL, phone: this.number, input: text });
102
+ this.receive(outcome.text);
103
+ }
104
+
105
+ /** Calls `listener` for every SMS that arrives. Returns an unsubscribe function. */
106
+ onSms(listener: (sms: SimSms) => void): () => void {
107
+ this.listeners.push(listener);
108
+ return () => {
109
+ this.listeners = this.listeners.filter((l) => l !== listener);
110
+ };
111
+ }
112
+
113
+ private async exchange(input: string, newSession: boolean): Promise<Screen> {
114
+ const session = this.session;
115
+ if (!session) throw new Error("No USSD session");
116
+ const outcome = await this.agent.handle({
117
+ channel: SIM_USSD_CHANNEL,
118
+ phone: this.number,
119
+ input,
120
+ inputs: [...session.inputs],
121
+ newSession,
122
+ gatewaySessionId: session.id,
123
+ });
124
+ if (outcome.end) this.session = null;
125
+ return { text: outcome.text, end: outcome.end };
126
+ }
127
+
128
+ private receive(text: string): void {
129
+ const sms: SimSms = { from: this.sender, text, at: new Date() };
130
+ this.inbox.push(sms);
131
+ for (const listener of this.listeners) listener(sms);
132
+ }
133
+
134
+ /** The inputs carried by a dialed code, or null when it doesn't reach the agent. */
135
+ private parseCode(code: string): string[] | null {
136
+ if (!/^\*[0-9*#]*#$/.test(code)) return null;
137
+ if (!this.code) return [];
138
+ if (code === this.code) return [];
139
+ const prefix = this.code.slice(0, -1) + "*";
140
+ if (!code.startsWith(prefix)) return null;
141
+ return code.slice(prefix.length, -1).split("*");
142
+ }
143
+ }
144
+
145
+ export function createPhone(agent: Agent, options: SimPhoneOptions = {}): SimPhone {
146
+ return new SimPhone(agent, options);
147
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The terminal front end for `SimPhone`: dial, read boxed screens, answer,
3
+ * and watch SMS arrive. Commands: `x` hangs up, `sms <text>` texts the
4
+ * agent, `q` quits.
5
+ */
6
+
7
+ import { createInterface } from "node:readline";
8
+ import type { Agent } from "@kalangu/core";
9
+ import { SimPhone, type Screen, type SimPhoneOptions, type SimSms } from "./phone.js";
10
+
11
+ export interface TerminalOptions extends SimPhoneOptions {
12
+ input?: NodeJS.ReadableStream;
13
+ output?: NodeJS.WritableStream;
14
+ /** Width of the screen box's text area. Default 34. */
15
+ width?: number;
16
+ }
17
+
18
+ /** Runs the simulator until the user quits or input ends. */
19
+ export function runTerminal(agent: Agent, options: TerminalOptions = {}): Promise<SimPhone> {
20
+ const input = options.input ?? process.stdin;
21
+ const output = options.output ?? process.stdout;
22
+ const width = options.width ?? 34;
23
+ const phone = new SimPhone(agent, options);
24
+ const tty = (output as { isTTY?: boolean }).isTTY === true;
25
+ const rl = createInterface({ input, output, terminal: tty });
26
+
27
+ const write = (text: string) => output.write(`${text}\n`);
28
+ let prompt = "Dial> ";
29
+ let busy = false;
30
+
31
+ const showPrompt = () => {
32
+ rl.setPrompt(prompt);
33
+ rl.prompt();
34
+ };
35
+
36
+ phone.onSms((sms) => {
37
+ // Print above whatever the user is typing, then restore the prompt.
38
+ if (tty) output.write("\r\x1b[K");
39
+ else output.write("\n");
40
+ write(formatSms(sms));
41
+ if (!busy) showPrompt();
42
+ });
43
+
44
+ write(`│ Simulated phone: ${formatNumber(phone.number)} (${phone.operator})`);
45
+ write(
46
+ `│ Dial ${options.code ?? "a code such as *384#"} · x hangs up · sms <text> texts the agent · q quits`,
47
+ );
48
+ showPrompt();
49
+
50
+ return new Promise((resolve) => {
51
+ let queue = Promise.resolve();
52
+ rl.on("line", (line) => {
53
+ queue = queue.then(async () => {
54
+ busy = true;
55
+ const keep = await handleLine(line.trim());
56
+ busy = false;
57
+ if (keep) showPrompt();
58
+ else rl.close();
59
+ });
60
+ });
61
+ rl.on("close", () => {
62
+ void queue.then(() => resolve(phone));
63
+ });
64
+ });
65
+
66
+ async function handleLine(line: string): Promise<boolean> {
67
+ if (line === "q") return false;
68
+ if (line === "x") {
69
+ if (phone.inSession) write("… hung up. Dial again to resume where you left off.");
70
+ phone.hangUp();
71
+ prompt = "Dial> ";
72
+ return true;
73
+ }
74
+ if (line.startsWith("sms ")) {
75
+ await phone.sendSms(line.slice(4));
76
+ return true;
77
+ }
78
+ if (line === "") return true;
79
+
80
+ let screen: Screen;
81
+ try {
82
+ screen = phone.inSession ? await phone.press(line) : await phone.dial(line);
83
+ } catch (err) {
84
+ write(`! ${err instanceof Error ? err.message : String(err)}`);
85
+ return true;
86
+ }
87
+ write(box(screen, width));
88
+ prompt = screen.end ? "Dial> " : looksLikeMenu(screen.text) ? "Choice> " : "Input> ";
89
+ return true;
90
+ }
91
+ }
92
+
93
+ /** Draws a screen in a box, wrapping long lines. Final screens show `END`. */
94
+ export function box(screen: Screen, width = 34): string {
95
+ const text = screen.end ? `END ${screen.text}` : screen.text;
96
+ const lines = text.split("\n").flatMap((line) => wrap(line, width));
97
+ const edge = "─".repeat(width + 2);
98
+ return [`┌${edge}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${edge}┘`].join("\n");
99
+ }
100
+
101
+ export function formatSms(sms: SimSms): string {
102
+ return `✉ SMS from ${sms.from}: ${sms.text}`;
103
+ }
104
+
105
+ function wrap(line: string, width: number): string[] {
106
+ if (line.length <= width) return [line];
107
+ const out: string[] = [];
108
+ let current = "";
109
+ for (const word of line.split(" ")) {
110
+ if (word.length > width) {
111
+ if (current) out.push(current);
112
+ for (let i = 0; i < word.length; i += width) out.push(word.slice(i, i + width));
113
+ current = out.pop() ?? "";
114
+ continue;
115
+ }
116
+ if (current === "") current = word;
117
+ else if (current.length + 1 + word.length <= width) current += ` ${word}`;
118
+ else {
119
+ out.push(current);
120
+ current = word;
121
+ }
122
+ }
123
+ if (current) out.push(current);
124
+ return out;
125
+ }
126
+
127
+ function looksLikeMenu(text: string): boolean {
128
+ return text.split("\n").some((line) => /^\d+\. /.test(line));
129
+ }
130
+
131
+ function formatNumber(phone: string): string {
132
+ const m = /^\+(\d{3})(\d{3})(\d{3})(\d{3})$/.exec(phone);
133
+ return m ? `+${m[1]} ${m[2]} ${m[3]} ${m[4]}` : phone;
134
+ }