@pellux/goodvibes-tui 1.24.2 → 1.26.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 (77) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +1 -1
  3. package/bin/goodvibes-daemon +24 -0
  4. package/docs/foundation-artifacts/operator-contract.json +18234 -12253
  5. package/package.json +8 -7
  6. package/src/cli/help.ts +10 -0
  7. package/src/cli/redaction.ts +68 -3
  8. package/src/config/goodvibes-home.ts +149 -0
  9. package/src/config/secret-config.ts +64 -8
  10. package/src/core/turn-event-wiring.ts +7 -16
  11. package/src/core/workstream-notification.ts +69 -0
  12. package/src/daemon/cli.ts +62 -7
  13. package/src/daemon/handlers/credentials.ts +15 -5
  14. package/src/daemon/handlers/index.ts +7 -6
  15. package/src/daemon/send/channels.ts +200 -0
  16. package/src/daemon/send/command.ts +332 -0
  17. package/src/daemon/send/composition.ts +99 -0
  18. package/src/daemon/send/failure-text.ts +93 -0
  19. package/src/daemon/send/inert-text.ts +225 -0
  20. package/src/daemon/send/stdin.ts +24 -0
  21. package/src/input/commands/calendar-runtime.ts +245 -0
  22. package/src/input/commands/config.ts +68 -2
  23. package/src/input/commands/connection-status.ts +258 -0
  24. package/src/input/commands/local-provider-runtime.ts +9 -1
  25. package/src/input/commands/mail-runtime.ts +267 -0
  26. package/src/input/commands/operator-runtime.ts +6 -1
  27. package/src/input/commands/payment-card-intake.ts +200 -0
  28. package/src/input/commands/profile-render.ts +250 -0
  29. package/src/input/commands/profile-runtime.ts +362 -0
  30. package/src/input/commands/profile-types.ts +381 -0
  31. package/src/input/commands/review-runtime.ts +13 -1
  32. package/src/input/commands.ts +11 -0
  33. package/src/input/composer-editor.ts +4 -0
  34. package/src/input/onboarding/onboarding-wizard-apply.ts +13 -1
  35. package/src/input/payments-config.ts +167 -0
  36. package/src/input/provider-key-intake.ts +10 -2
  37. package/src/input/settings-modal-commit.ts +146 -0
  38. package/src/input/settings-modal-connections.ts +102 -0
  39. package/src/input/settings-modal-data.ts +30 -0
  40. package/src/input/settings-modal-reset.ts +6 -2
  41. package/src/input/settings-modal-secrets.ts +9 -2
  42. package/src/input/settings-modal-types.ts +19 -3
  43. package/src/input/settings-modal.ts +54 -107
  44. package/src/main.ts +7 -2
  45. package/src/panels/modals/marketplace-modal.ts +5 -0
  46. package/src/panels/modals/skills-modal.ts +5 -0
  47. package/src/renderer/settings-modal-connections.ts +63 -0
  48. package/src/renderer/settings-modal-helpers.ts +6 -0
  49. package/src/renderer/settings-modal.ts +21 -1
  50. package/src/runtime/bootstrap-core.ts +1 -1
  51. package/src/runtime/bootstrap.ts +2 -2
  52. package/src/runtime/context.ts +9 -0
  53. package/src/runtime/credential-composition.ts +54 -0
  54. package/src/runtime/daemon-handler-composition.ts +0 -4
  55. package/src/runtime/install-self-check-startup.ts +23 -0
  56. package/src/runtime/mail-composition.ts +65 -0
  57. package/src/runtime/onboarding/types.ts +6 -1
  58. package/src/runtime/path-shadow-startup.ts +243 -0
  59. package/src/runtime/path-shadow.ts +418 -0
  60. package/src/runtime/reachability-notice.ts +100 -0
  61. package/src/runtime/runtime-services-types.ts +243 -0
  62. package/src/runtime/services.ts +30 -224
  63. package/src/shell/ui-openers.ts +7 -0
  64. package/src/verification/verification-ledger.ts +158 -0
  65. package/src/version.ts +1 -1
  66. package/src/daemon/handlers/calendar/caldav-client.ts +0 -662
  67. package/src/daemon/handlers/calendar/ics.ts +0 -556
  68. package/src/daemon/handlers/calendar/index.ts +0 -316
  69. package/src/daemon/handlers/email/config.ts +0 -164
  70. package/src/daemon/handlers/email/imap-connector.ts +0 -441
  71. package/src/daemon/handlers/email/imap-parsing.ts +0 -499
  72. package/src/daemon/handlers/email/index.ts +0 -43
  73. package/src/daemon/handlers/email/read-handlers.ts +0 -80
  74. package/src/daemon/handlers/email/runtime.ts +0 -140
  75. package/src/daemon/handlers/email/smtp-connector.ts +0 -557
  76. package/src/daemon/handlers/email/validation.ts +0 -147
  77. package/src/daemon/handlers/email/write-handlers.ts +0 -133
@@ -0,0 +1,99 @@
1
+ /**
2
+ * composition.ts — the smallest set of services that can put a message on a
3
+ * channel, built from the daemon's own tier.
4
+ *
5
+ * ## Why not `createRuntimeServices`
6
+ *
7
+ * The daemon's full runtime graph starts a LAN scan, a cluster coordinator, an
8
+ * inbox poller, a fleet tick, a memory governor and a config watch. Composing
9
+ * it to send one message would build a second, competing set of that state on a
10
+ * machine that is already running a daemon — the same reason `cluster …` is
11
+ * intercepted before any runtime is constructed (see src/daemon/cli.ts). This
12
+ * builds only the five objects `ChannelDeliveryRouter` needs and starts no
13
+ * timers, binds no sockets and joins no election, so it is safe to run beside a
14
+ * live daemon.
15
+ *
16
+ * ## Why it does not talk to the running daemon over HTTP either
17
+ *
18
+ * That was tried before this command existed: the control-plane API answers
19
+ * `401 AUTH_REQUIRED` to the operator token as stored on disk. More importantly
20
+ * an HTTP-backed send would only work while a daemon is up, and the case this
21
+ * command is for — telling the owner that something has stopped — is exactly
22
+ * when it may not be.
23
+ *
24
+ * ## Where the credentials come from
25
+ *
26
+ * `surfaces.*` is a daemon-owned config prefix, so `ConfigManager` overlays
27
+ * `<home>/.goodvibes/daemon/settings.json` LAST and a bot token stored there is
28
+ * visible here. `SecretsManager` gets the same `daemonHome` the daemon itself
29
+ * resolves, so a `goodvibes://secrets/...` reference in one of those keys
30
+ * resolves against the daemon's store rather than a client silo. Getting that
31
+ * second half wrong is what produced `Missing Telegram bot token` from a
32
+ * machine whose token was present and correct.
33
+ */
34
+
35
+ import { ChannelDeliveryRouter } from '@pellux/goodvibes-sdk/platform/channels';
36
+ import { ArtifactStore } from '@pellux/goodvibes-sdk/platform/artifacts';
37
+ import { ConfigManager, ServiceRegistry, SubscriptionManager } from '@pellux/goodvibes-sdk/platform/config';
38
+ import { createShellPathService } from '@/runtime/index.ts';
39
+ import { SecretsManager } from '../../config/secrets.ts';
40
+ import type { SendDeliver } from './command.ts';
41
+
42
+ export interface SendStackRoots {
43
+ readonly workingDirectory: string;
44
+ /** The GoodVibes tree root — the directory `.goodvibes/` sits under. */
45
+ readonly homeDirectory: string;
46
+ /** The daemon's own state root, holding the daemon-scoped secret stores. */
47
+ readonly daemonHomeDirectory: string;
48
+ }
49
+
50
+ export interface SendStack {
51
+ readonly configManager: ConfigManager;
52
+ readonly deliver: SendDeliver;
53
+ }
54
+
55
+ /**
56
+ * Build the delivery stack for one CLI send.
57
+ *
58
+ * `secretsManager` is passed to `ChannelDeliveryRouter` because the router
59
+ * REQUIRES it and refuses to construct without it. That requirement is the fix
60
+ * for a real defect: while the parameter was optional, two shipped composition
61
+ * roots (goodvibes-tui and goodvibes-agent) omitted it, still type-checked,
62
+ * still delivered on every surface whose credential happens to sit in config or
63
+ * the environment, and failed only on the surfaces that use a secret reference
64
+ * — at send time, as `Missing Telegram bot token`. This composition root does
65
+ * not repeat that.
66
+ */
67
+ export function createSendStack(roots: SendStackRoots): SendStack {
68
+ const configManager = new ConfigManager({
69
+ workingDir: roots.workingDirectory,
70
+ homeDir: roots.homeDirectory,
71
+ surfaceRoot: 'tui',
72
+ });
73
+ const shellPaths = createShellPathService({
74
+ workingDirectory: roots.workingDirectory,
75
+ homeDirectory: roots.homeDirectory,
76
+ });
77
+ const secretsManager = new SecretsManager({
78
+ projectRoot: roots.workingDirectory,
79
+ globalHome: roots.homeDirectory,
80
+ // Threaded, never defaulted: a daemon told to run out of an isolated tree
81
+ // must not read the real home's credential store, and neither must this.
82
+ daemonHome: roots.daemonHomeDirectory,
83
+ configManager,
84
+ });
85
+ const serviceRegistry = new ServiceRegistry(shellPaths.resolveProjectPath('tui', 'services.json'), {
86
+ secretsManager,
87
+ subscriptionManager: new SubscriptionManager(shellPaths.resolveUserPath('tui', 'subscriptions.json')),
88
+ });
89
+ const router = new ChannelDeliveryRouter({
90
+ configManager,
91
+ secretsManager,
92
+ serviceRegistry,
93
+ artifactStore: new ArtifactStore({ configManager }),
94
+ });
95
+ return {
96
+ configManager,
97
+ deliver: (request) => router.deliver(request),
98
+ };
99
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * failure-text.ts — what the operator is told when a send does not happen.
3
+ *
4
+ * ## Why this is not `summarizeError`
5
+ *
6
+ * The SDK's `summarizeError` is the right tool nearly everywhere: it classifies
7
+ * an error, adds a hint, and deliberately drops detail so a transcript stays
8
+ * readable. That is the wrong trade here, and measurably so. Given the real
9
+ * Telegram failure
10
+ *
11
+ * Telegram delivery failed HTTP 401: {"ok":false,"description":"Unauthorized"}
12
+ *
13
+ * it returns `Telegram delivery failed HTTP 401` — its `stripJson` pass removes
14
+ * the `{...}`, which is exactly the part naming what went wrong. Given
15
+ * `connect ECONNREFUSED 149.154.167.220:443` it returns "Cannot connect to the
16
+ * provider. Check whether the service is reachable." — advice in place of the
17
+ * address that was refused.
18
+ *
19
+ * A person debugging a message that did not arrive needs the provider's own
20
+ * words: "Unauthorized", "chat not found", and "Bad Request: message is too
21
+ * long" have three different fixes, and all three flatten to the same summary.
22
+ *
23
+ * ## What is removed, and why that is not the same thing
24
+ *
25
+ * Detail is kept; CREDENTIALS are not. This matters more here than in most
26
+ * places because Telegram puts the bot token in the URL PATH
27
+ * (`api.telegram.org/bot<token>/sendMessage`), so a transport error that echoes
28
+ * the request URL would print the owner's bot token to a terminal and into
29
+ * whatever log or pasted report that terminal output ends up in.
30
+ *
31
+ * `redactSensitiveData` from the SDK covers the shapes it knows (bearer tokens,
32
+ * `sk-`/`xoxb-`/`ghp_` keys, home directories). It has NO pattern for a
33
+ * URL-embedded credential, so the two passes below add them. They run BEFORE
34
+ * the SDK pass, because a redacted string must not then be re-scanned in a way
35
+ * that could reveal structure.
36
+ */
37
+
38
+ import { redactSensitiveData } from '@pellux/goodvibes-sdk/platform/utils';
39
+
40
+ /**
41
+ * A generous cap. The point of this text is diagnosis, so it is far larger than
42
+ * the 240 characters `summarizeError` allows — but an HTML error page or a
43
+ * multi-megabyte body still must not flood the terminal.
44
+ */
45
+ const MAX_FAILURE_TEXT = 2_000;
46
+
47
+ const URL_CREDENTIAL_PATTERNS: ReadonlyArray<{ readonly pattern: RegExp; readonly replacement: string }> = [
48
+ // Telegram: the bot token IS the path segment.
49
+ { pattern: /\/bot\d{5,}:[A-Za-z0-9_-]{10,}/g, replacement: '/bot[REDACTED_BOT_TOKEN]' },
50
+ // Any URL carrying `user:password@host` — BlueBubbles, Mattermost and Matrix
51
+ // base URLs are all operator-supplied and can be written this way.
52
+ { pattern: /(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+:[^/\s@]+@/gi, replacement: '$1[REDACTED_CREDENTIALS]@' },
53
+ // A credential passed as a query parameter — BlueBubbles sends `?password=`.
54
+ {
55
+ pattern: /([?&](?:password|token|secret|access_token|api_?key|auth)=)[^&\s"']+/gi,
56
+ replacement: '$1[REDACTED]',
57
+ },
58
+ ];
59
+
60
+ /** Strip credentials this command can put on the wire but the SDK pass does not know. */
61
+ export function redactUrlCredentials(text: string): string {
62
+ let result = text;
63
+ for (const { pattern, replacement } of URL_CREDENTIAL_PATTERNS) {
64
+ result = result.replace(pattern, replacement);
65
+ }
66
+ return result;
67
+ }
68
+
69
+ /**
70
+ * The provider's own failure text, with credentials removed and nothing else
71
+ * rewritten.
72
+ *
73
+ * Never returns an empty string: an error whose message is blank still has to
74
+ * produce something an operator can act on, because the alternative is an exit
75
+ * code with no explanation beside it.
76
+ */
77
+ export function describeSendFailure(error: unknown): string {
78
+ const raw = error instanceof Error
79
+ ? (error.message.trim().length > 0 ? error.message : error.name)
80
+ : typeof error === 'string'
81
+ ? error
82
+ : (() => { try { return JSON.stringify(error); } catch { return String(error); } })();
83
+ const message = typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : 'the provider failed without saying why';
84
+ // `cause` is where Node and Bun put the real reason for `fetch failed`, and
85
+ // dropping it is how a genuinely diagnosable DNS or TLS failure becomes two
86
+ // useless words.
87
+ const cause = error instanceof Error && error.cause instanceof Error && error.cause.message.trim().length > 0
88
+ ? ` (${error.cause.message.trim()})`
89
+ : '';
90
+ const full = `${message}${cause}`;
91
+ const redacted = redactSensitiveData(redactUrlCredentials(full));
92
+ return redacted.length <= MAX_FAILURE_TEXT ? redacted : `${redacted.slice(0, MAX_FAILURE_TEXT)}…`;
93
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * inert-text.ts — make a message arrive as LITERAL TEXT on whichever channel
3
+ * `goodvibes-daemon send` delivers it to.
4
+ *
5
+ * ## What "inert" means here, and why it is per (surface × transport), not
6
+ * per surface
7
+ *
8
+ * The transform a surface needs depends on what the delivery strategy in
9
+ * `platform/channels/delivery/strategies-core.ts` actually does with the body,
10
+ * not on what the surface is capable of parsing. Two examples that pull in
11
+ * opposite directions:
12
+ *
13
+ * - Telegram's `sendMessage` CAN parse MarkdownV2, but the strategy sends with
14
+ * NO `parse_mode`, which is Telegram's plain-text mode. Running a MarkdownV2
15
+ * escaper over the body on this path would not protect anything — it would
16
+ * put visible backslashes in front of every `.` `-` `!` `(` in the owner's
17
+ * message. The correct transform is identity, and the property that makes it
18
+ * correct is asserted by a test against the real wire payload rather than
19
+ * asserted here in prose (see src/test/daemon/send-command-wire.test.ts).
20
+ *
21
+ * - Discord's `postMessage` renders markdown unconditionally, INCLUDING masked
22
+ * links, so the same body needs real escaping.
23
+ *
24
+ * A single "escape for channel X" table that ignored the transport would get
25
+ * Telegram wrong in the direction that mangles the owner's text, and would get
26
+ * Discord wrong in the direction that renders a link. Hence the split below.
27
+ *
28
+ * ## Provenance of the escaper bodies
29
+ *
30
+ * `escapeDiscordMarkdown` and `escapeSlackMrkdwn` are the escapers written for
31
+ * the inbound-mail structured notices, in the SDK at
32
+ * `packages/sdk/src/platform/email/inbound-notice.ts` — same character classes,
33
+ * same zero-width-space mention break, same rationale. They are reproduced here
34
+ * rather than imported for one reason: that module lives on the unmerged
35
+ * `inbound-email-*` branches and is absent from the published
36
+ * `@pellux/goodvibes-sdk@1.18.1` this product consumes, so there is nothing to
37
+ * import yet.
38
+ *
39
+ * This is a second copy and that is a defect, not a design. When the
40
+ * inbound-mail round merges and an SDK release publishes `platform/email`'s
41
+ * notice escapers, THIS FILE'S `escapeDiscordMarkdown` and `escapeSlackMrkdwn`
42
+ * are to be deleted and the SDK's imported in their place; the surface-kind
43
+ * table below is the only part that should survive that change. The behaviour
44
+ * is pinned by tests either way, so the swap is verifiable rather than hopeful.
45
+ */
46
+
47
+ import type { ChannelDeliverySurfaceKind } from '@pellux/goodvibes-sdk/platform/channels';
48
+
49
+ /**
50
+ * Zero-width space. Used to break a token that a surface would otherwise read
51
+ * as syntax, on surfaces that offer no backslash escape (Slack) or where
52
+ * backslash-escaping demonstrably does not defeat the token (Discord mentions).
53
+ */
54
+ const ZERO_WIDTH_SPACE = '​';
55
+
56
+ /**
57
+ * `@everyone`, `@here`, and raw role/channel/user mentions. Backslash-escaping
58
+ * the `@` does NOT reliably suppress these in every Discord client, so the
59
+ * zero-width break is used instead.
60
+ */
61
+ function breakMentionForms(text: string): string {
62
+ return text
63
+ .replace(/@(everyone|here)/g, (_match, word: string) => `@${ZERO_WIDTH_SPACE}${word}`)
64
+ .replace(/<@[!&]?(\d+)>/g, (_match, id: string) => `<@${ZERO_WIDTH_SPACE}${id}>`)
65
+ .replace(/<#(\d+)>/g, (_match, id: string) => `<#${ZERO_WIDTH_SPACE}${id}>`);
66
+ }
67
+
68
+ /**
69
+ * Discord markdown. Backslash-escaping `* _ ~ \` |` and `>` renders each as its
70
+ * literal character rather than triggering bold/italic/strikethrough/code/
71
+ * spoiler/quote.
72
+ *
73
+ * `[` `]` `(` `)` are escaped too, and this is REQUIRED rather than
74
+ * precautionary: masked links (`[text](url)`) DO render as clickable in
75
+ * bot-sent and webhook messages — which is exactly how this product delivers to
76
+ * Discord — even though they do not render for text a human typed into the
77
+ * client.
78
+ * https://github.com/discord/discord-api-docs/issues/6096
79
+ * https://gist.github.com/matthewzring/9f7bbfd102003963f9be7dbcf7d40e51
80
+ *
81
+ * Without this, a message body assembled from anything the owner did not type
82
+ * arrives in his Discord as a clickable link reading whatever the body said.
83
+ * An escaper that looks optional gets tidied away by the next reader: it is not
84
+ * optional, and it stays.
85
+ *
86
+ * `\` is inside the character class, so a backslash in the input is escaped
87
+ * first and cannot un-escape what follows it.
88
+ */
89
+ function escapeDiscordMarkdown(text: string): string {
90
+ return breakMentionForms(text.replace(/[*_~`|>[\]()\\]/g, (ch) => `\\${ch}`));
91
+ }
92
+
93
+ /**
94
+ * Slack mrkdwn. `&`, `<`, `>` MUST be HTML-entity-escaped per Slack's own
95
+ * formatting reference. That is also what defeats `<url|text>` link syntax and
96
+ * `<!channel>` / `<@id>` mention syntax outright, since both require a literal
97
+ * unescaped `<`.
98
+ *
99
+ * Slack has no backslash escape for `* _ ~ \``, so the zero-width break is
100
+ * applied to those as the best available mitigation — stated as a mitigation,
101
+ * not a guarantee, because Slack's whitespace-adjacency rule for what breaks a
102
+ * delimiter pair is not publicly specified to that precision. The residual risk
103
+ * is cosmetic (accidental bold/italic); the injection class this exists to
104
+ * close — a clickable link or a real mention — is closed by the entity escaping
105
+ * above.
106
+ */
107
+ function escapeSlackMrkdwn(text: string): string {
108
+ const entityEscaped = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
109
+ return entityEscaped.replace(/[*_~`]/g, (ch) => `${ch}${ZERO_WIDTH_SPACE}`);
110
+ }
111
+
112
+ /**
113
+ * Google Chat's `text` field renders `*bold*`, `_italic_`, `~strike~`,
114
+ * `` `code` `` and `<url|text>` links. The `<` entity escape is what defeats
115
+ * the link and `<users/all>` mention forms; the delimiters get the zero-width
116
+ * break, as Google Chat documents no backslash escape either.
117
+ */
118
+ function escapeGoogleChatMarkup(text: string): string {
119
+ const entityEscaped = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
120
+ return entityEscaped.replace(/[*_~`]/g, (ch) => `${ch}${ZERO_WIDTH_SPACE}`);
121
+ }
122
+
123
+ /**
124
+ * WhatsApp Cloud API text messages render `*bold*`, `_italic_`, `~strike~` and
125
+ * ```` ```mono``` ````. There is no masked-link syntax — a URL in the body is
126
+ * auto-linked showing its real address — so the injection class Discord has
127
+ * does not exist here and only the delimiters need neutralizing. WhatsApp
128
+ * documents no backslash escape, so the zero-width break is used.
129
+ */
130
+ function escapeWhatsAppMarkup(text: string): string {
131
+ return text.replace(/[*_~`]/g, (ch) => `${ch}${ZERO_WIDTH_SPACE}`);
132
+ }
133
+
134
+ /**
135
+ * The surfaces whose delivery strategy hands the body to a renderer that parses
136
+ * markup. Every other routable surface is absent DELIBERATELY, and each absence
137
+ * is a checked claim about the strategy, not an oversight:
138
+ *
139
+ * - `telegram` — `sendMessage` without `parse_mode`; Telegram's plain-text
140
+ * mode. Escaping here would corrupt, not protect.
141
+ * - `ntfy` — `publish` sends the body as `text/plain` and never sets the
142
+ * `Markdown` header, so ntfy renders it literally. The title
143
+ * is derived by `titleFromBody` (first non-empty LINE) and
144
+ * passed through `toHeaderSafeTitle`, so no line break or
145
+ * non-ASCII byte from the body can reach an HTTP header.
146
+ * - `webhook` — the body is a JSON string field; the receiver decides what
147
+ * to do with it and there is no markup layer to neutralize.
148
+ *
149
+ * - `signal` — the strategy posts `text` to a signal bridge. Signal renders
150
+ * no markup in a plain message body; styling travels as
151
+ * explicit range metadata the strategy never sends.
152
+ * - `imessage`,
153
+ * `bluebubbles` — both end at iMessage, which renders no markup at all.
154
+ * - `msteams` — the strategy sends `textFormat: 'plain'` alongside the text,
155
+ * which is Teams' own instruction not to parse it.
156
+ * - `matrix` — `msgtype: 'm.text'` with no `format`/`formatted_body`. A
157
+ * Matrix event without the HTML format field is rendered
158
+ * literally by clients, per the spec.
159
+ *
160
+ * `web` is absent for a different reason: its strategy needs a live
161
+ * `ControlPlaneGateway` in the same process, which a short-lived CLI does not
162
+ * have, so the command does not offer it as a channel at all. `telephony` is
163
+ * absent because a CLI `send` to it would place a phone call or an SMS through
164
+ * a paid carrier — a different act from messaging a channel — and because the
165
+ * strategy already XML-escapes the voice path itself via `escapeTwiml`.
166
+ */
167
+ const INERT_TRANSFORMS: Partial<Record<ChannelDeliverySurfaceKind, (text: string) => string>> = {
168
+ // Renders markup, including a masked link: full escaping.
169
+ discord: escapeDiscordMarkdown,
170
+ mattermost: escapeDiscordMarkdown,
171
+ // Renders markup, but has no masked-link syntax: delimiters only.
172
+ slack: escapeSlackMrkdwn,
173
+ 'google-chat': escapeGoogleChatMarkup,
174
+ whatsapp: escapeWhatsAppMarkup,
175
+ // Delivered as plain text by the strategy: transforming would corrupt, not
176
+ // protect. Each of these is a checked claim about the strategy, not a guess —
177
+ // see the list above.
178
+ telegram: (text) => text,
179
+ ntfy: (text) => text,
180
+ webhook: (text) => text,
181
+ signal: (text) => text,
182
+ imessage: (text) => text,
183
+ bluebubbles: (text) => text,
184
+ msteams: (text) => text,
185
+ matrix: (text) => text,
186
+ };
187
+
188
+ /** Surfaces `goodvibes-daemon send` will deliver to, in a stable display order. */
189
+ export const INERT_RENDERABLE_SURFACE_KINDS: readonly ChannelDeliverySurfaceKind[] = [
190
+ 'telegram', 'ntfy', 'discord', 'slack', 'google-chat', 'webhook',
191
+ 'signal', 'whatsapp', 'imessage', 'msteams', 'bluebubbles', 'mattermost', 'matrix',
192
+ ];
193
+
194
+ /**
195
+ * Whether this surface has a verified inert transform.
196
+ *
197
+ * A surface with no entry gets a refusal from the send command, never an
198
+ * untransformed body. Returning the body unchanged for an unknown surface is
199
+ * precisely how a markup-rendering channel acquires a live link: the default
200
+ * has to be "refuse", and it has to be checkable from the caller.
201
+ */
202
+ export function canRenderInert(surfaceKind: ChannelDeliverySurfaceKind): boolean {
203
+ return Object.prototype.hasOwnProperty.call(INERT_TRANSFORMS, surfaceKind);
204
+ }
205
+
206
+ /**
207
+ * Render `text` so it arrives on `surfaceKind` as the literal characters the
208
+ * caller supplied.
209
+ *
210
+ * Throws for a surface with no verified transform. This function has no
211
+ * "pass it through" branch and must never grow one: every caller of the send
212
+ * command reaches the world through here, so a permissive fallback would make
213
+ * the command a way to put live markup on the owner's phone.
214
+ */
215
+ export function inertBodyFor(surfaceKind: ChannelDeliverySurfaceKind, text: string): string {
216
+ const transform = INERT_TRANSFORMS[surfaceKind];
217
+ if (!transform) {
218
+ throw new Error(
219
+ `No verified inert-text transform for surface '${surfaceKind}'. `
220
+ + 'Sending would risk the message being rendered as markup rather than as text, '
221
+ + `so nothing was sent. Supported: ${INERT_RENDERABLE_SURFACE_KINDS.join(', ')}.`,
222
+ );
223
+ }
224
+ return transform(text);
225
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * stdin.ts — read the whole of stdin as the message body.
3
+ *
4
+ * Kept out of command.ts so the command stays a pure function of its arguments
5
+ * and its injected dependencies: every test drives it with a stub rather than
6
+ * having to arrange a real pipe on the process running the suite.
7
+ */
8
+
9
+ /**
10
+ * Read stdin to end, as UTF-8.
11
+ *
12
+ * There is deliberately no timeout. `send` reads stdin only when the operator
13
+ * gave no message argument AND stdin is not a terminal — meaning something is
14
+ * piping into it — so waiting for that producer to finish is the correct
15
+ * behaviour, and cutting it off at an arbitrary deadline would silently
16
+ * truncate a long message.
17
+ */
18
+ export async function readAllStdin(): Promise<string> {
19
+ const chunks: Buffer[] = [];
20
+ for await (const chunk of process.stdin) {
21
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string));
22
+ }
23
+ return Buffer.concat(chunks).toString('utf-8');
24
+ }