1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! UX-22: turn-finish notifications (desktop + optional email).
//!
//! supercode gives no signal when a long turn finishes — no bell, no
//! desktop popup. This module adds both, entirely opt-in and best-effort:
//!
//! - **Desktop**: shells out to `notify-send` (the standard libnotify CLI
//! on Linux desktops), the same zero-new-dependency shape as
//! `terminal_title.rs`'s raw OSC escapes — no `notify-rust`/dbus crate.
//! `osascript` (macOS) / a toast API (Windows) are out of scope: this
//! codebase only ships/tests on Linux (see `Cargo.toml`), and the box
//! this was built on is headless Linux with no guaranteed dbus session —
//! see [`fire_desktop`]'s doc for exactly how that's handled.
//! - **Bell**: a plain `BEL` (`\x07`) to stderr, the low-tech fallback the
//! backlog's approach sketch pairs with the desktop notification.
//! - **Email** (optional/stretch per the backlog item): a minimal,
//! dependency-free SMTP client — see [`fire_email`]'s doc for its scope
//! and honest limitations (no TLS/STARTTLS).
//!
//! ## Gating (the AC)
//!
//! [`should_notify`] is the single choke point, mirroring
//! `terminal_title::should_set_title` / `spinner::should_show_spinner`'s
//! "one pure predicate, every call site funnels through it" shape:
//! off unless explicitly enabled (flag/env/config), never for a machine
//! output format (`json`/`stream-json`), never when stderr isn't a real
//! terminal (piped/CI — the AC's "non-interactive/piped" case), and only
//! for turns that actually ran long enough to matter.
//!
//! ## Never blocks, never breaks the turn
//!
//! [`maybe_fire`] is called AFTER a turn's own result is already decided
//! (the reply is already printed/persisted by the caller) — everything it
//! does is either near-instant (the `notify-send` `spawn()` call itself:
//! fork+exec, no wait for the child) or pushed onto a detached background
//! thread ([`fire_desktop`]'s reap, all of [`fire_email`]) whose failure
//! or slowness is invisible to (and can never fail) the turn that already
//! finished. Nothing here ever panics or returns a `Result` the caller
//! must handle — every failure mode (notifier absent, PATH lookup fails,
//! SMTP connect refused, ...) is swallowed at the source.
//!
//! ## Honest headless caveat
//!
//! This box has no guaranteed dbus session / `notify-send` binary. The
//! integration test (`crates/cli/tests/notify_cli.rs`) proves the WIRING —
//! a fake `notify-send` script on `PATH` receives the exact title/body —
//! and separately proves the "no `notify-send` on `PATH` at all" case
//! degrades to a silent no-op. Neither proves a real desktop popup was
//! ever rendered on a real display; that half is unverifiable here by
//! construction (no display, no dbus, no windowing system on this box).
use Write;
use ;
use Duration;
/// Default "long turn" threshold (seconds) — a turn that finishes faster
/// than this is assumed to still be watched, so no notification fires.
/// Overridable via `--notify-threshold-secs` / `notify_threshold_secs`
/// config.
pub const DEFAULT_THRESHOLD_SECS: u64 = 30;
/// Cap on the reply/prompt preview folded into a notification body — a
/// short "safe summary" per the driver directive, never the full session.
pub const SUMMARY_MAX_CHARS: usize = 80;
/// Resolved notification settings for one CLI invocation — already merged
/// (flag > env > config > default), the same shape as `main.rs`'s other
/// `effective_*` helpers (e.g. `effective_reduced`).
/// SMTP settings for the optional email channel. The account password is
/// deliberately NOT a field here (see `fire_email`'s doc) — it's read only
/// from the `SUPERCODE_NOTIFY_EMAIL_PASSWORD` env var at send time, so it
/// never has to live in a plaintext `config.toml`.
/// Pure gating decision — no I/O, unit-testable without a real tty,
/// notify-send, or network. A notification is suppressed unless ALL of:
///
/// - `enabled` — explicit opt-in (`--notify`, `SUPERCODE_NOTIFY`, or
/// `notify = true` in config). Off by default (AC dev/02).
/// - `!machine_format` — `--output-format json`/`stream-json` never
/// notifies. Those are scripted/wrapper callers; a stray notify-send
/// spawn (or, worse, any byte near stdout) is exactly the kind of side
/// effect a machine caller doesn't want.
/// - `stderr_is_tty` — the rest of "non-interactive/piped" (AC dev/02):
/// redirected/piped stderr (or CI) means nobody's at the terminal to
/// see a desktop notification anyway — the same non-tty gate
/// `terminal_title::should_set_title` uses.
/// - `elapsed >= threshold` — only turns long enough that the user might
/// plausibly have looked away (the backlog's "long-running turn").
/// Strip control characters and cap length. A crafted assistant reply (or
/// user prompt) must never be able to smuggle control bytes into a
/// notify-send argument or an SMTP header, and the AC/driver directive
/// both call for a short SAFE summary, not the raw session content.
/// Build the `(title, body)` for a finished turn. `reply_preview` is the
/// model's OWN final reply text — truncated and control-stripped so at
/// most a short, safe preview ever leaves the process, never the full
/// history/session.
/// Desktop notification via `notify-send`. The `Command::spawn()` call
/// itself runs SYNCHRONOUSLY on the caller's thread — that's just a
/// PATH-lookup + fork+exec, sub-millisecond in practice, and critically
/// must happen before this function returns: if it were pushed onto a
/// background thread instead, a fast-exiting `run` invocation could reach
/// `std::process::exit` before the OS ever scheduled that thread, and the
/// notify-send process would never launch at all. Once spawned, though,
/// `notify-send` is a fully independent OS process — supercode exiting
/// (or this Rust process's threads dying) afterward can't stop it or
/// prevent it from actually showing the popup.
///
/// Only the REAPING (`.wait()`, so the child doesn't sit as a zombie for
/// the rest of a long-lived `chat` REPL process) is pushed to a detached
/// background thread — that part is allowed to be slow/never-observed
/// without affecting anything (worst case for a short-lived `run`
/// process: the zombie is reparented to init on exit and reaped there,
/// same as any other orphaned child).
///
/// Degrades completely silently when `notify-send` isn't on `PATH`, dbus
/// isn't reachable, or spawning fails for any other reason — `spawn()`
/// returning `Err` is the ordinary "notifier absent" case, not an error
/// condition worth surfacing (AC dev/02: "never break the run if the
/// notifier is absent").
/// Best-effort terminal bell (`BEL`) — the backlog's approach sketch pairs
/// this with the desktop notification. Stderr only, never stdout, and only
/// ever called from behind the same `should_notify` gate as the desktop
/// notification, so it inherits the same non-machine/interactive-only
/// discipline.
/// Fire-and-forget email notification (optional/stretch channel): a
/// minimal, dependency-free SMTP client (EHLO / optional AUTH LOGIN /
/// MAIL FROM / RCPT TO / DATA / QUIT) over a plain `TcpStream`.
///
/// **Honest scope**: this speaks UNENCRYPTED SMTP only — no STARTTLS, no
/// implicit TLS. It works against a local unauthenticated relay
/// (postfix/msmtp/sendmail on port 25) or a relay that accepts AUTH LOGIN
/// over a plaintext channel — it will NOT work against a TLS-required
/// provider like `smtp.gmail.com:587`. Adding STARTTLS would need a TLS
/// implementation (a new dependency, cargo-deny-relevant), which is out
/// of scope for a "prefer no new dep" stretch channel. This matches the
/// backlog's own framing of email as a stretch, config-gated addition,
/// not a production MTA client.
///
/// Runs entirely on a detached background thread — the SMTP round trip is
/// real network I/O (bounded by a 5s connect/read/write timeout, but
/// still potentially slow), so it must never run on the turn's own
/// thread. Any failure (DNS, connect refused, timeout, relay rejection)
/// is swallowed inside [`send_email_blocking`]'s `Result` and never
/// propagates — email is a best-effort side channel, same discipline as
/// the desktop notification.
///
/// Known limitation: because this is fully backgrounded, a single-shot
/// `run` invocation that exits immediately after printing its result can
/// race the SMTP conversation to completion — there's no bounded join at
/// the call site (unlike the desktop path's synchronous `spawn()`, the
/// email path has no equivalent "at least got launched" guarantee against
/// process exit). `chat`'s longer-lived REPL process gives this far more
/// headroom in practice. Config-gated and off by default, so this is a
/// documented trade-off rather than a silent one.
/// Dispatch whatever's configured (bell + desktop + optional email) for a
/// finished turn, subject to [`should_notify`]'s gating. The single call
/// site every command path (`run`, `chat`, `resume`) should use.
// ---- minimal SMTP client ----------------------------------------------
/// Read one SMTP reply (possibly multi-line, `XXX-` continuation until a
/// final `XXX ` line) and return the 3-digit status code. Bails with an
/// `InvalidData` error on a code outside 200-399 (SMTP failure), so the
/// caller's `?`-chain naturally aborts the conversation on the first
/// rejected step rather than plowing ahead with garbage state.