niahere 0.4.6 → 0.5.1

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 (60) hide show
  1. package/package.json +2 -2
  2. package/src/agent/backends/claude-normalize.ts +5 -6
  3. package/src/agent/backends/claude.ts +6 -4
  4. package/src/agent/backends/codex-normalize.ts +19 -3
  5. package/src/agent/backends/codex.ts +100 -35
  6. package/src/agent/chain.ts +60 -0
  7. package/src/agent/failure.ts +90 -0
  8. package/src/agent/health.ts +41 -0
  9. package/src/agent/index.ts +3 -1
  10. package/src/agent/mcp-endpoint.ts +5 -3
  11. package/src/agent/models.ts +59 -0
  12. package/src/agent/registry.ts +54 -29
  13. package/src/agent/types.ts +9 -4
  14. package/src/channels/common/chat-session.ts +60 -0
  15. package/src/channels/phone/consult.ts +2 -1
  16. package/src/channels/phone/index.ts +5 -3
  17. package/src/channels/phone/relay.ts +15 -5
  18. package/src/channels/slack.ts +24 -34
  19. package/src/channels/sms.ts +16 -36
  20. package/src/channels/telegram.ts +22 -34
  21. package/src/channels/twilio/media-cache.ts +4 -3
  22. package/src/channels/twilio/rest.ts +0 -31
  23. package/src/channels/twilio/server.ts +0 -5
  24. package/src/channels/twilio/shared.ts +36 -0
  25. package/src/channels/whatsapp.ts +24 -58
  26. package/src/chat/engine.ts +83 -34
  27. package/src/chat/gap-marker.ts +63 -0
  28. package/src/chat/repl.ts +5 -5
  29. package/src/cli/config.ts +71 -0
  30. package/src/cli/index.ts +23 -288
  31. package/src/cli/job.ts +1 -2
  32. package/src/cli/logs.ts +55 -0
  33. package/src/cli/run.ts +74 -0
  34. package/src/cli/skills.ts +13 -0
  35. package/src/cli/status.ts +0 -1
  36. package/src/cli/test.ts +32 -0
  37. package/src/cli/update.ts +79 -0
  38. package/src/commands/backup.ts +1 -2
  39. package/src/commands/init.ts +1 -2
  40. package/src/commands/validate.ts +17 -13
  41. package/src/core/alive.ts +6 -5
  42. package/src/core/consolidator.ts +78 -31
  43. package/src/core/daemon.ts +3 -2
  44. package/src/core/finalizer.ts +9 -5
  45. package/src/core/runner.ts +64 -47
  46. package/src/core/scheduler.ts +19 -4
  47. package/src/core/skills.ts +0 -4
  48. package/src/db/migrations/017_sessions_consolidated_count.ts +9 -0
  49. package/src/db/models/active_engine.ts +0 -7
  50. package/src/db/models/job.ts +3 -2
  51. package/src/db/models/message.ts +10 -0
  52. package/src/db/models/session.ts +12 -0
  53. package/src/mcp/gate.ts +46 -0
  54. package/src/mcp/server.ts +2 -1
  55. package/src/mcp/tools/misc.ts +2 -1
  56. package/src/mcp/tools/send.ts +5 -4
  57. package/src/types/config.ts +4 -4
  58. package/src/utils/config.ts +6 -8
  59. package/src/utils/errors.ts +26 -0
  60. package/src/utils/retry.ts +0 -45
@@ -1,51 +1,76 @@
1
+ import { existsSync } from "fs";
1
2
  import type { AgentBackend } from "./types";
3
+ import type { ChainEntry } from "./chain";
2
4
  import { ClaudeBackend } from "./backends/claude";
3
- import { CodexBackend } from "./backends/codex";
5
+ import { CodexBackend, resolveCodexBin } from "./backends/codex";
4
6
  import { getConfig } from "../utils/config";
7
+ import { resolveModel, providerDefault, PROVIDER_ORDER, type ProviderName } from "./models";
5
8
 
6
- /**
7
- * Backend selection — the ONE place backend identity is resolved. Consumers call
8
- * `getBackend()` and depend only on the `AgentBackend` interface, so no
9
- * `if (backend === …)` ever leaks into the orchestration loop.
10
- *
11
- * Phase 1: always the in-process Claude backend. Phase 2+ adds Codex/Gemini and
12
- * a role/per-job selector; Phase 3 adds the ordered-fallback failover list.
13
- */
9
+ /** The ONE place backend identity is resolved. */
14
10
  let claudeBackend: ClaudeBackend | null = null;
15
11
  let codexBackend: CodexBackend | null = null;
16
12
  let override: AgentBackend | null = null;
17
- let chainOverride: AgentBackend[] | null = null;
13
+ let chainOverride: ChainEntry[] | null = null;
18
14
 
19
- export function getBackend(name?: "claude" | "codex" | "gemini"): AgentBackend {
15
+ export function getBackend(name?: ProviderName): AgentBackend {
20
16
  if (override) return override;
21
- if (name === "codex") {
22
- if (!codexBackend) codexBackend = new CodexBackend();
23
- return codexBackend;
24
- }
25
- if (!claudeBackend) claudeBackend = new ClaudeBackend();
26
- return claudeBackend;
17
+ if (name === "codex") return (codexBackend ??= new CodexBackend());
18
+ return (claudeBackend ??= new ClaudeBackend());
27
19
  }
28
20
 
29
- /** Test seam: force `getBackend()` to return a specific backend; pass null to reset. */
21
+ /** Test seam: force `getBackend()` to return a specific backend; null resets. */
30
22
  export function setBackend(backend: AgentBackend | null): void {
31
23
  override = backend;
32
24
  }
33
25
 
34
- /** Test seam: force `resolveBackends()` to return a specific chain; null resets. */
35
- export function setBackendChain(backends: AgentBackend[] | null): void {
36
- chainOverride = backends;
26
+ /** Test seam: force `resolveChain()` to return a specific chain; null resets. */
27
+ export function setBackendChain(chain: ChainEntry[] | null): void {
28
+ chainOverride = chain;
29
+ }
30
+
31
+ /** Gemini is resolvable in config but has no adapter yet. */
32
+ const IMPLEMENTED: ProviderName[] = ["claude", "codex"];
33
+
34
+ function isAvailable(provider: ProviderName): boolean {
35
+ if (provider === "claude") return true;
36
+ if (provider === "codex") return existsSync(resolveCodexBin());
37
+ return false;
38
+ }
39
+
40
+ export interface ChainDeps {
41
+ available: (provider: ProviderName) => boolean;
37
42
  }
38
43
 
39
44
  /**
40
- * The ordered backend chain for a run: the configured primary first, then any
41
- * fallbacks (provider-down failover), de-duplicated. Consumers try each in order
42
- * until one isn't provider-down.
45
+ * Providers the config never named are appended with their default model, so a
46
+ * bare config still has somewhere to go but only if they can run here.
47
+ * Configured models are always kept, so a misconfiguration surfaces as a real
48
+ * error rather than vanishing.
43
49
  */
44
- export function resolveBackends(): AgentBackend[] {
50
+ export function buildChain(
51
+ model: string,
52
+ fallbackModels: string[],
53
+ deps: ChainDeps = { available: isAvailable },
54
+ ): ChainEntry[] {
55
+ const configured = [model, ...fallbackModels].map(resolveModel);
56
+ const named = new Set(configured.map((r) => r.provider));
57
+ const implicit = PROVIDER_ORDER.filter((p) => !named.has(p) && deps.available(p)).map(providerDefault);
58
+
59
+ const seen = new Set<string>();
60
+ const entries: ChainEntry[] = [];
61
+ for (const ref of [...configured, ...implicit]) {
62
+ if (!IMPLEMENTED.includes(ref.provider)) continue;
63
+ const key = `${ref.provider}:${ref.model ?? ""}`;
64
+ if (seen.has(key)) continue;
65
+ seen.add(key);
66
+ entries.push({ backend: getBackend(ref.provider), model: ref.model });
67
+ }
68
+ return entries;
69
+ }
70
+
71
+ export function resolveChain(): ChainEntry[] {
45
72
  if (chainOverride) return chainOverride;
46
- if (override) return [override];
73
+ if (override) return [{ backend: override }];
47
74
  const cfg = getConfig();
48
- const seen = new Set<string>();
49
- const names = [cfg.runner, ...cfg.fallback].filter((n) => !seen.has(n) && seen.add(n));
50
- return names.map((n) => getBackend(n));
75
+ return buildChain(cfg.model, cfg.fallback_models);
51
76
  }
@@ -32,9 +32,11 @@ export interface AgentUsage {
32
32
  * - `text`/`thinking`: streamed reply / status (→ onStream / onActivity).
33
33
  * - `tool`: a tool-call activity line.
34
34
  * - `result`/`error`: terminal events ending a turn.
35
- * - `error.retryable` (transient API failure → the backend may retry internally)
36
- * and `error.providerDown` (the provider is unavailable failover trigger) are
37
- * INDEPENDENT predicates.
35
+ * - `error.retryable` (the backend may retry in place) is independent of
36
+ * `error.failover`, which scopes how far the chain skips:
37
+ * `"model"` advances one entry (possibly the same provider, another model),
38
+ * `"provider"` skips that provider's remaining entries, absent stops the
39
+ * chain because the task itself failed.
38
40
  */
39
41
  export type AgentEvent =
40
42
  | { type: "session"; backendSessionId: string }
@@ -52,7 +54,10 @@ export type AgentEvent =
52
54
  * Opaque to the orchestrator. */
53
55
  metadata?: Record<string, unknown>;
54
56
  }
55
- | { type: "error"; message: string; retryable: boolean; providerDown: boolean; terminalReason?: string };
57
+ | { type: "error"; message: string; retryable: boolean; failover?: FailoverScope; terminalReason?: string };
58
+
59
+ /** How far the chain skips after a failure. See `AgentEvent`. */
60
+ export type FailoverScope = "model" | "provider";
56
61
 
57
62
  export function isResultEvent(ev: AgentEvent): ev is Extract<AgentEvent, { type: "result" }> {
58
63
  return ev.type === "result";
@@ -54,3 +54,63 @@ export async function rotateRoom(
54
54
  export function chainLock(state: ChatState, fn: () => Promise<void>): void {
55
55
  state.lock = state.lock.then(fn, fn);
56
56
  }
57
+
58
+ /** Seam so the registry is testable without a database. */
59
+ export interface SessionOpener {
60
+ open(prefix: string, build: EngineFactory): Promise<ChatState>;
61
+ rotate(prefix: string, prev: ChatState | undefined, build: EngineFactory): Promise<ChatState>;
62
+ }
63
+
64
+ const defaultOpener: SessionOpener = { open: openChatEngine, rotate: rotateRoom };
65
+
66
+ /**
67
+ * A channel's per-sender chat sessions. Every message-driven channel keeps one
68
+ * of these keyed by sender, and they all want the same four things: open on
69
+ * first use, reuse after, rotate on `/reset`, close everything on shutdown.
70
+ */
71
+ export class ChatSessions<K> {
72
+ private readonly states = new Map<K, ChatState>();
73
+
74
+ constructor(
75
+ private readonly prefixFor: (key: K) => string,
76
+ private readonly build: EngineFactory,
77
+ private readonly opener: SessionOpener = defaultOpener,
78
+ ) {}
79
+
80
+ /** `build` overrides the default options for this call — Slack needs it to
81
+ * thread watch behavior and thread context into a newly opened engine. */
82
+ async get(key: K, build: EngineFactory = this.build): Promise<ChatState> {
83
+ const existing = this.states.get(key);
84
+ if (existing) return existing;
85
+ const state = await this.opener.open(this.prefixFor(key), build);
86
+ this.states.set(key, state);
87
+ return state;
88
+ }
89
+
90
+ /** Start a fresh room for this sender, closing the previous one. */
91
+ async rotate(key: K, build: EngineFactory = this.build): Promise<ChatState> {
92
+ const state = await this.opener.rotate(this.prefixFor(key), this.states.get(key), build);
93
+ this.states.set(key, state);
94
+ return state;
95
+ }
96
+
97
+ /** The cached session, without opening one. */
98
+ peek(key: K): ChatState | undefined {
99
+ return this.states.get(key);
100
+ }
101
+
102
+ /** Whether a session is already open — Slack uses it to tell a live thread
103
+ * from one it should ignore. */
104
+ has(key: K): boolean {
105
+ return this.states.has(key);
106
+ }
107
+
108
+ keys(): Iterable<K> {
109
+ return this.states.keys();
110
+ }
111
+
112
+ closeAll(): void {
113
+ for (const state of this.states.values()) state.engine.close();
114
+ this.states.clear();
115
+ }
116
+ }
@@ -6,6 +6,7 @@
6
6
  * Heavyweight (multi-second latency) by design — keep usage selective.
7
7
  */
8
8
  import Anthropic from "@anthropic-ai/sdk";
9
+ import { errMsg } from "../../utils/errors";
9
10
  import { loadIdentity } from "../../chat/identity";
10
11
  import { log } from "../../utils/log";
11
12
 
@@ -38,6 +39,6 @@ export async function consultClaude(question: string, callerLabel: string): Prom
38
39
  return "(no answer)";
39
40
  } catch (err) {
40
41
  log.error({ err }, "phone: consult_claude failed");
41
- return `error consulting Claude: ${err instanceof Error ? err.message : String(err)}`;
42
+ return `error consulting Claude: ${errMsg(err)}`;
42
43
  }
43
44
  }
@@ -25,6 +25,7 @@ import type { ServerWebSocket } from "bun";
25
25
  import type { Channel, Outbound, PhoneConfig, TwilioConfig } from "../../types";
26
26
  import { getConfig } from "../../utils/config";
27
27
  import { log } from "../../utils/log";
28
+ import { ignore } from "../../utils/errors";
28
29
  import { getChannel } from "../registry";
29
30
  import { Session, Message } from "../../db/models";
30
31
  import { runMigrations } from "../../db/migrate";
@@ -194,9 +195,10 @@ class PhoneChannel implements Channel {
194
195
 
195
196
  if (!allowed) {
196
197
  log.warn({ from, callSid }, "phone: rejecting unauthorized caller");
197
- getChannel("telegram")
198
- ?.deliver({ text: `Phone: rejected call from ${from} (CallSid ${callSid})` })
199
- .catch(() => {});
198
+ const notice = getChannel("telegram")?.deliver({
199
+ text: `Phone: rejected call from ${from} (CallSid ${callSid})`,
200
+ });
201
+ if (notice) void ignore(notice, "notify rejected caller");
200
202
  return twimlResponse(sayAndHangupTwiML("Sorry, this line is not currently accepting calls. Goodbye."));
201
203
  }
202
204
 
@@ -12,6 +12,7 @@
12
12
  * const result = await relay.completion;
13
13
  */
14
14
  import { log } from "../../utils/log";
15
+ import { errMsg } from "../../utils/errors";
15
16
 
16
17
  export interface PhoneToolDefinition {
17
18
  name: string;
@@ -57,6 +58,17 @@ export interface RelayOpts {
57
58
  model: string;
58
59
  voice: string;
59
60
  context: CallContext;
61
+ /** Injectable so the bridge is testable without dialing OpenAI. */
62
+ openAiWsFactory?: (url: string, key: string) => OpenAiSocket;
63
+ }
64
+
65
+ /** The slice of the realtime socket the relay drives. */
66
+ export interface OpenAiSocket extends WebSocketLike {
67
+ addEventListener(type: string, listener: (ev: any) => void): void;
68
+ }
69
+
70
+ function connectOpenAi(url: string, key: string): OpenAiSocket {
71
+ return new WebSocket(url, { headers: { Authorization: `Bearer ${key}` } } as any) as unknown as OpenAiSocket;
60
72
  }
61
73
 
62
74
  export interface WebSocketLike {
@@ -76,7 +88,7 @@ export interface RelayHandle {
76
88
  }
77
89
 
78
90
  export function createRelay(opts: RelayOpts): RelayHandle {
79
- const { twilioWs, openAiKey, model, voice, context } = opts;
91
+ const { twilioWs, openAiKey, model, voice, context, openAiWsFactory = connectOpenAi } = opts;
80
92
  const transcript: TranscriptTurn[] = [];
81
93
  let endedReason: RelayEndReason = "twilio_stop";
82
94
  let errorMsg: string | undefined;
@@ -84,9 +96,7 @@ export function createRelay(opts: RelayOpts): RelayHandle {
84
96
  let pendingAssistantText = "";
85
97
 
86
98
  const openAiUrl = `wss://api.openai.com/v1/realtime?model=${encodeURIComponent(model)}`;
87
- const openAiWs = new WebSocket(openAiUrl, {
88
- headers: { Authorization: `Bearer ${openAiKey}` },
89
- } as any);
99
+ const openAiWs = openAiWsFactory(openAiUrl, openAiKey);
90
100
 
91
101
  /** Whether a response is currently in flight on the OpenAI side. */
92
102
  let responseActive = false;
@@ -268,7 +278,7 @@ export function createRelay(opts: RelayOpts): RelayHandle {
268
278
  try {
269
279
  output = await tool.handler(args);
270
280
  } catch (err) {
271
- output = `error: ${err instanceof Error ? err.message : String(err)}`;
281
+ output = `error: ${errMsg(err)}`;
272
282
  log.error({ err, callSid: context.callSid, toolName }, "phone tool handler failed");
273
283
  }
274
284
  }
@@ -5,11 +5,14 @@ import { relativeTime } from "../utils/format";
5
5
  import { runMigrations } from "../db/migrate";
6
6
  import { Session, Message } from "../db/models";
7
7
  import { log } from "../utils/log";
8
+ import { errMsg, ignore } from "../utils/errors";
8
9
  import { getMcpServers } from "../mcp";
9
- import { chainLock, openChatEngine, rotateRoom } from "./common/chat-session";
10
+ import { ChatSessions, chainLock } from "./common/chat-session";
10
11
  import { SlackAttachmentCache } from "./slack/attachments";
11
12
  import { SlackWatchReloader } from "./slack/watch";
12
13
 
14
+ const logActivity = (status: string) => log.debug({ status }, "slack engine activity");
15
+
13
16
  /** Strip markdown backticks so sentinel tokens like [NO_REPLY] match even when the LLM wraps them. */
14
17
  function cleanSentinel(text: string): string {
15
18
  return text.replace(/`/g, "").trim();
@@ -75,7 +78,7 @@ class SlackChannel implements Channel {
75
78
 
76
79
  this.dmUserId = config.channels.slack.dm_user_id;
77
80
 
78
- const chats = new Map<string, ChatState>();
81
+ const chats = new ChatSessions<string>(roomPrefix, buildEngineOpts());
79
82
  const channelNames = new Map<string, string>();
80
83
 
81
84
  async function resolveChannelName(app: App, channelId: string): Promise<string> {
@@ -111,30 +114,20 @@ class SlackChannel implements Channel {
111
114
  });
112
115
  }
113
116
 
114
- async function getState(
117
+ const getState = (
115
118
  key: string,
116
119
  watchBehavior?: { channel: string; behavior: string },
117
120
  slackCtx?: SlackContext,
118
- ): Promise<ChatState> {
119
- let state = chats.get(key);
120
- if (state) return state;
121
- state = await openChatEngine(roomPrefix(key), buildEngineOpts(watchBehavior, slackCtx));
122
- chats.set(key, state);
123
- return state;
124
- }
121
+ ): Promise<ChatState> => chats.get(key, buildEngineOpts(watchBehavior, slackCtx));
125
122
 
126
- async function restartChat(
123
+ const restartChat = (
127
124
  key: string,
128
125
  watchBehavior?: { channel: string; behavior: string },
129
126
  slackCtx?: SlackContext,
130
- ): Promise<ChatState> {
131
- const state = await rotateRoom(roomPrefix(key), chats.get(key), buildEngineOpts(watchBehavior, slackCtx));
132
- chats.set(key, state);
133
- return state;
134
- }
127
+ ): Promise<ChatState> => chats.rotate(key, buildEngineOpts(watchBehavior, slackCtx));
135
128
 
136
129
  function withLock(key: string, fn: () => Promise<void>): void {
137
- const state = chats.get(key);
130
+ const state = chats.peek(key);
138
131
  if (!state) {
139
132
  fn().catch((err) => log.error({ err, key }, "unhandled error in locked handler"));
140
133
  return;
@@ -177,13 +170,11 @@ class SlackChannel implements Channel {
177
170
  withLock(key, async () => {
178
171
  try {
179
172
  const { result } = await state.engine.send(subcommand, {
180
- onActivity(status) {
181
- log.debug({ status }, "slack engine activity");
182
- },
173
+ onActivity: logActivity,
183
174
  });
184
175
  await respond(result.trim() || "(no response)");
185
176
  } catch (err) {
186
- const errText = err instanceof Error ? err.message : String(err);
177
+ const errText = errMsg(err);
187
178
  await respond(`[error] ${errText}`);
188
179
  }
189
180
  });
@@ -437,9 +428,7 @@ class SlackChannel implements Channel {
437
428
  const { result, messageId, signal } = await state.engine.send(
438
429
  text,
439
430
  {
440
- onActivity(status) {
441
- log.debug({ status }, "slack engine activity");
442
- },
431
+ onActivity: logActivity,
443
432
  },
444
433
  attachments,
445
434
  );
@@ -448,7 +437,7 @@ class SlackChannel implements Channel {
448
437
  await reactToSlackMessage(client, msg.channel, msg.ts, "skull").catch((err) =>
449
438
  log.debug({ err, channel: msg.channel }, "slack: failed to add provider-down reaction"),
450
439
  );
451
- if (messageId) await Message.updateDeliveryStatus(messageId, "sent").catch(() => {});
440
+ if (messageId) await ignore(Message.updateDeliveryStatus(messageId, "sent"), "record sent delivery status");
452
441
  log.info({ channel: msg.channel, key, reaction: "skull" }, "slack provider failure sent as reaction");
453
442
  return;
454
443
  }
@@ -468,7 +457,7 @@ class SlackChannel implements Channel {
468
457
  "slack: [NO_REPLY] sentinel mixed with content; suppressing send",
469
458
  );
470
459
  }
471
- if (messageId) await Message.updateDeliveryStatus(messageId, "sent").catch(() => {});
460
+ if (messageId) await ignore(Message.updateDeliveryStatus(messageId, "sent"), "record sent delivery status");
472
461
  return;
473
462
  }
474
463
 
@@ -482,26 +471,27 @@ class SlackChannel implements Channel {
482
471
  } else {
483
472
  await say(reply);
484
473
  }
485
- if (messageId) await Message.updateDeliveryStatus(messageId, "sent").catch(() => {});
474
+ if (messageId) await ignore(Message.updateDeliveryStatus(messageId, "sent"), "record sent delivery status");
486
475
  log.info({ channel: msg.channel, key, chars: reply.length }, "slack reply sent");
487
476
  } catch (sendErr) {
488
- if (messageId) await Message.updateDeliveryStatus(messageId, "failed").catch(() => {});
477
+ if (messageId) await ignore(Message.updateDeliveryStatus(messageId, "failed"), "record failed delivery status");
489
478
  throw sendErr;
490
479
  }
491
480
  } catch (err) {
492
- const errText = err instanceof Error ? err.message : String(err);
481
+ const errText = errMsg(err);
493
482
  log.error({ err, channel: msg.channel }, "slack message processing failed");
494
483
 
495
484
  if (replyThreadTs) {
496
- await client.chat
497
- .postMessage({
485
+ await ignore(
486
+ client.chat.postMessage({
498
487
  channel: msg.channel,
499
488
  text: `[error] ${errText}`,
500
489
  thread_ts: replyThreadTs,
501
- })
502
- .catch(() => {});
490
+ }),
491
+ "reply engine error in thread",
492
+ );
503
493
  } else {
504
- await say(`[error] ${errText}`).catch(() => {});
494
+ await ignore(say(`[error] ${errText}`), "reply engine error");
505
495
  }
506
496
  } finally {
507
497
  await client.reactions
@@ -16,25 +16,29 @@
16
16
  */
17
17
  import { getMcpServers } from "../mcp";
18
18
  import { runMigrations } from "../db/migrate";
19
- import type { Channel, ChatState, Outbound, TwilioConfig } from "../types";
19
+ import type { Channel, Outbound, TwilioConfig } from "../types";
20
20
  import { getConfig } from "../utils/config";
21
21
  import { log } from "../utils/log";
22
+ import { errMsg, ignore } from "../utils/errors";
22
23
  import { sendMessage as twilioSendMessage } from "./twilio/rest";
23
24
  import { getTwilioServer } from "./twilio/server";
24
- import { chainLock, openChatEngine } from "./common/chat-session";
25
-
26
- const EMPTY_TWIML = '<?xml version="1.0" encoding="UTF-8"?><Response></Response>';
25
+ import { ChatSessions, chainLock } from "./common/chat-session";
26
+ import { ackTwiml, deliveryStatusAck, isAllowedSender } from "./twilio/shared";
27
27
 
28
28
  class SmsChannel implements Channel {
29
29
  name = "sms" as const;
30
30
  private readonly twilio: TwilioConfig;
31
31
  /** Cached resolved "from" number: sms.from_number || phone.from_number */
32
32
  private readonly fromNumber: string;
33
- private readonly chats = new Map<string, ChatState>();
33
+ private readonly chats: ChatSessions<string>;
34
34
 
35
35
  constructor(twilio: TwilioConfig, fromNumber: string) {
36
36
  this.twilio = twilio;
37
37
  this.fromNumber = fromNumber;
38
+ this.chats = new ChatSessions((remote) => `sms-${remote}`, () => ({
39
+ channel: "sms",
40
+ mcpServers: getMcpServers(),
41
+ }));
38
42
  }
39
43
 
40
44
  async start(): Promise<void> {
@@ -70,8 +74,7 @@ class SmsChannel implements Channel {
70
74
  }
71
75
 
72
76
  async stop(): Promise<void> {
73
- for (const state of this.chats.values()) state.engine.close();
74
- this.chats.clear();
77
+ this.chats.closeAll();
75
78
  }
76
79
 
77
80
  /** Outbound — used by send_message MCP tool. SMS is text-only; media is dropped with a warning. */
@@ -92,12 +95,12 @@ class SmsChannel implements Channel {
92
95
  const from = params.From || "";
93
96
  const body = params.Body || "";
94
97
 
95
- if (!this.isAllowed(from)) {
98
+ if (!isAllowedSender(this.twilio, from)) {
96
99
  log.warn({ from }, "sms: rejecting non-allowlisted sender");
97
- return new Response(EMPTY_TWIML, { status: 200, headers: { "Content-Type": "text/xml" } });
100
+ return ackTwiml();
98
101
  }
99
102
 
100
- const state = await this.getState(from);
103
+ const state = await this.chats.get(from);
101
104
  // Ack the webhook immediately; reply via REST asynchronously to avoid
102
105
  // Twilio's ~15s webhook timeout when the engine takes longer.
103
106
  chainLock(state, async () => {
@@ -107,24 +110,15 @@ class SmsChannel implements Channel {
107
110
  await this.sendTo(from, reply);
108
111
  } catch (err) {
109
112
  log.error({ err, from }, "sms: engine error");
110
- await this.sendTo(from, `[error] ${err instanceof Error ? err.message : String(err)}`).catch(() => {});
113
+ await ignore(this.sendTo(from, `[error] ${errMsg(err)}`), "reply engine error");
111
114
  }
112
115
  });
113
116
 
114
- return new Response(EMPTY_TWIML, { status: 200, headers: { "Content-Type": "text/xml" } });
117
+ return ackTwiml();
115
118
  }
116
119
 
117
120
  private handleStatus(params: Record<string, string>): Response {
118
- log.info(
119
- {
120
- messageSid: params.MessageSid,
121
- status: params.MessageStatus,
122
- errorCode: params.ErrorCode,
123
- to: params.To,
124
- },
125
- "sms: delivery status",
126
- );
127
- return new Response("", { status: 204 });
121
+ return deliveryStatusAck("sms", params);
128
122
  }
129
123
 
130
124
  // --- Outbound ---
@@ -153,20 +147,6 @@ class SmsChannel implements Channel {
153
147
  }
154
148
  }
155
149
 
156
- // --- Helpers ---
157
-
158
- private isAllowed(remoteE164: string): boolean {
159
- if (this.twilio.owner_number && remoteE164 === this.twilio.owner_number) return true;
160
- return this.twilio.allowlist.includes(remoteE164);
161
- }
162
-
163
- private async getState(remoteE164: string): Promise<ChatState> {
164
- let state = this.chats.get(remoteE164);
165
- if (state) return state;
166
- state = await openChatEngine(`sms-${remoteE164}`, () => ({ channel: "sms", mcpServers: getMcpServers() }));
167
- this.chats.set(remoteE164, state);
168
- return state;
169
- }
170
150
  }
171
151
 
172
152
  export function createSmsChannel(): SmsChannel | null {