advisers 0.1.0-preview.4 → 0.2.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 (53) hide show
  1. package/LICENSE +131 -21
  2. package/NOTICE +34 -0
  3. package/README-zh.md +40 -9
  4. package/README.md +53 -10
  5. package/THIRD-PARTY-NOTICES.md +277 -0
  6. package/bin/advisers.js +4230 -122
  7. package/index.js +1 -1
  8. package/lib/agent.js +414 -0
  9. package/lib/attachments.js +283 -0
  10. package/lib/capture.js +168 -0
  11. package/lib/context-window.js +123 -0
  12. package/lib/digest.js +27 -0
  13. package/lib/doc-review.js +30 -0
  14. package/lib/egress.js +27 -0
  15. package/lib/evidence.js +1995 -0
  16. package/lib/ical.js +542 -0
  17. package/lib/imap.js +181 -0
  18. package/lib/importers.js +1001 -0
  19. package/lib/learning.js +46 -0
  20. package/lib/mcp-server.js +869 -0
  21. package/lib/model.js +307 -0
  22. package/lib/notify.js +189 -0
  23. package/lib/nudge.js +10 -0
  24. package/lib/ocr.js +47 -0
  25. package/lib/pdf.js +105 -0
  26. package/lib/pet-brief-store.js +51 -0
  27. package/lib/pet-brief.js +644 -0
  28. package/lib/receipt-verify.js +624 -0
  29. package/lib/relative-date.js +393 -0
  30. package/lib/remind.js +690 -0
  31. package/lib/research.js +193 -0
  32. package/lib/review.js +88 -0
  33. package/lib/routine.js +22 -0
  34. package/lib/safety/classifier.js +392 -0
  35. package/lib/safety/explain.js +157 -0
  36. package/lib/safety/index.js +333 -0
  37. package/lib/safety/redact.js +212 -0
  38. package/lib/safety/rules.js +824 -0
  39. package/lib/scheduler.js +399 -0
  40. package/lib/source.js +294 -0
  41. package/lib/sqlite.js +1022 -0
  42. package/lib/sync.js +129 -0
  43. package/lib/timestamp.js +45 -0
  44. package/lib/tos/index.js +332 -0
  45. package/lib/tos/manifest.json +32 -0
  46. package/lib/tos/privacy.zh-CN.md +136 -0
  47. package/lib/tos/safety.zh-CN.md +101 -0
  48. package/lib/tos/summary.zh-CN.md +12 -0
  49. package/lib/tos/terms.zh-CN.md +439 -0
  50. package/lib/ui.js +49 -0
  51. package/lib/undo.js +83 -0
  52. package/lib/vault.js +51 -0
  53. package/package.json +26 -4
package/lib/imap.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * E2-T2: minimal read-only IMAP client.
3
+ *
4
+ * Only LOGIN, EXAMINE, UID SEARCH, UID FETCH (BODY.PEEK[]) and LOGOUT are ever
5
+ * sent. There is no STORE/APPEND/EXPUNGE/COPY/MOVE path; the mailbox is opened
6
+ * with EXAMINE (read-only) by design.
7
+ *
8
+ * The client is intentionally tiny: no OAuth flow, no Gmail API, no cloud SDK.
9
+ * Credentials come from the caller (env in the CLI), are never written to disk
10
+ * and never logged.
11
+ *
12
+ * Robustness (2026-11-17 audit P1-9): one managed inactivity timer instead of a
13
+ * new socket.setTimeout listener per read, a total request deadline, a literal
14
+ * size cap, and the real server UID (parsed from the FETCH UID attribute)
15
+ * instead of the message sequence number.
16
+ */
17
+ import net from 'node:net'
18
+ import tls from 'node:tls'
19
+
20
+ const CRLF = '\r\n'
21
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
22
+ const DEFAULT_TIMEOUT_MS = 30_000
23
+ const MAX_LITERAL_BYTES = 25 * 1024 * 1024
24
+
25
+ export function imapQuote(value) {
26
+ return '"' + String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'
27
+ }
28
+
29
+ export function imapSinceDate(days = 30, now = new Date()) {
30
+ const d = new Date(now.getTime() - Math.max(0, days) * 86_400_000)
31
+ return `${String(d.getUTCDate()).padStart(2, '0')}-${MONTHS[d.getUTCMonth()]}-${d.getUTCFullYear()}`
32
+ }
33
+
34
+ function createReader(socket, { idleTimeoutMs = DEFAULT_TIMEOUT_MS, deadline = Number.POSITIVE_INFINITY, totalTimeoutMs = DEFAULT_TIMEOUT_MS, maxLiteralBytes = MAX_LITERAL_BYTES } = {}) {
35
+ let buffer = Buffer.alloc(0)
36
+ let ended = false
37
+ let error
38
+ let wake = null
39
+ let timer = null
40
+
41
+ const clearTimer = () => {
42
+ if (timer) { clearTimeout(timer); timer = null }
43
+ }
44
+ const wakeUp = () => {
45
+ clearTimer()
46
+ if (wake) { const w = wake; wake = null; w() }
47
+ }
48
+ socket.on('data', (chunk) => { buffer = Buffer.concat([buffer, chunk]); wakeUp() })
49
+ socket.on('end', () => { ended = true; wakeUp() })
50
+ socket.on('error', (e) => { error = e; wakeUp() })
51
+
52
+ const waitData = () => new Promise((resolve) => {
53
+ if (buffer.length || ended || error) return resolve()
54
+ const remaining = deadline - Date.now()
55
+ if (remaining <= 0) {
56
+ error = new Error(`IMAP request timed out after ${totalTimeoutMs}ms`)
57
+ return resolve()
58
+ }
59
+ wake = resolve
60
+ const waitMs = Math.max(1, Math.min(idleTimeoutMs, remaining))
61
+ timer = setTimeout(() => {
62
+ timer = null
63
+ error = remaining <= idleTimeoutMs
64
+ ? new Error(`IMAP request timed out after ${totalTimeoutMs}ms`)
65
+ : new Error(`IMAP connection idle for more than ${idleTimeoutMs}ms`)
66
+ wakeUp()
67
+ }, waitMs)
68
+ })
69
+
70
+ async function readLine() {
71
+ for (;;) {
72
+ const idx = buffer.indexOf('\r\n')
73
+ if (idx >= 0) { const line = buffer.subarray(0, idx).toString('latin1'); buffer = buffer.subarray(idx + 2); return line }
74
+ if (error) throw error
75
+ if (ended) throw new Error('IMAP connection ended before a complete line')
76
+ await waitData()
77
+ }
78
+ }
79
+ async function readBytes(n) {
80
+ if (n > maxLiteralBytes) throw new Error(`IMAP literal is larger than the ${maxLiteralBytes}-byte limit`)
81
+ while (buffer.length < n) {
82
+ if (error) throw error
83
+ if (ended) throw new Error('IMAP connection ended inside a literal')
84
+ await waitData()
85
+ }
86
+ const data = buffer.subarray(0, n); buffer = buffer.subarray(n); return data
87
+ }
88
+ async function response(tag) {
89
+ const untagged = []
90
+ const literals = []
91
+ for (;;) {
92
+ const line = await readLine()
93
+ if (line.startsWith(tag + ' ')) return { untagged, literals, status: line }
94
+ const m = /\{(\d+)\}$/.exec(line)
95
+ untagged.push(line)
96
+ if (m) {
97
+ const size = Number(m[1])
98
+ if (size > maxLiteralBytes) throw new Error(`IMAP literal is larger than the ${maxLiteralBytes}-byte limit`)
99
+ literals.push(await readBytes(size))
100
+ }
101
+ }
102
+ }
103
+ return { readLine, response, clearTimer }
104
+ }
105
+
106
+ export async function fetchImapMessages({
107
+ host, port = 993, secure = true, user, pass, mailbox = 'INBOX', sinceDays = 30, limit = 20,
108
+ rejectUnauthorized = true, connect, timeoutMs = DEFAULT_TIMEOUT_MS, idleTimeoutMs = DEFAULT_TIMEOUT_MS,
109
+ maxLiteralBytes = MAX_LITERAL_BYTES,
110
+ } = {}) {
111
+ if (!host || !user || !pass) throw new Error('IMAP host/user/password are required')
112
+ const socket = await new Promise((resolve, reject) => {
113
+ let settled = false
114
+ const timer = setTimeout(() => {
115
+ if (settled) return
116
+ settled = true
117
+ try { s?.destroy?.() } catch {}
118
+ reject(new Error(`IMAP connect timed out after ${timeoutMs}ms`))
119
+ }, timeoutMs)
120
+ const finish = (fn, value) => {
121
+ if (settled) return
122
+ settled = true
123
+ clearTimeout(timer)
124
+ fn(value)
125
+ }
126
+ const onError = (e) => finish(reject, e)
127
+ let s
128
+ try {
129
+ s = connect ? connect({ host, port, secure }) : secure ? tls.connect({ host, port, rejectUnauthorized }) : net.connect({ host, port })
130
+ } catch (error) {
131
+ finish(reject, error)
132
+ return
133
+ }
134
+ if (typeof s.then === 'function') {
135
+ s.then((x) => finish(resolve, x), (e) => finish(reject, e))
136
+ return
137
+ }
138
+ s.once('error', onError)
139
+ s.once(secure ? 'secureConnect' : 'connect', () => {
140
+ s.off?.('error', onError)
141
+ finish(resolve, s)
142
+ })
143
+ })
144
+ const reader = createReader(socket, { idleTimeoutMs, totalTimeoutMs: timeoutMs, deadline: Date.now() + timeoutMs, maxLiteralBytes })
145
+ let tagNo = 0
146
+ const tag = () => 'A' + (++tagNo)
147
+ const command = async (text) => {
148
+ const t = tag()
149
+ socket.write(`${t} ${text}${CRLF}`)
150
+ const r = await reader.response(t)
151
+ if (!/^OK/i.test(r.status.split(' ').slice(1).join(' '))) throw new Error(`IMAP ${text.split(' ')[0]} failed: ${r.status}`)
152
+ return r
153
+ }
154
+ try {
155
+ const greeting = await reader.readLine()
156
+ if (!/^\* (OK|PREAUTH)/i.test(greeting)) throw new Error(`IMAP greeting failed: ${greeting}`)
157
+ await command(`LOGIN ${imapQuote(user)} ${imapQuote(pass)}`)
158
+ const selected = await command(`EXAMINE ${imapQuote(mailbox)}`)
159
+ const exists = selected.untagged.find((l) => /^\* \d+ EXISTS/i.test(l))
160
+ if (!exists) throw new Error('IMAP EXAMINE did not return EXISTS')
161
+ const search = await command(`UID SEARCH SINCE ${imapSinceDate(sinceDays)}`)
162
+ const searchLine = search.untagged.find((l) => /^\* SEARCH/i.test(l)) ?? ''
163
+ const uids = searchLine.split(/\s+/).slice(2).filter((x) => /^\d+$/.test(x)).map(Number)
164
+ const wanted = uids.slice(-Math.max(0, limit))
165
+ let messages = []
166
+ if (wanted.length) {
167
+ const fetched = await command(`UID FETCH ${wanted.join(',')} (UID BODY.PEEK[])`)
168
+ const fetchLines = fetched.untagged.filter((l) => /^\* \d+ FETCH/i.test(l))
169
+ messages = fetched.literals.map((raw, index) => {
170
+ const uidMatch = /\bUID (\d+)\b/i.exec(fetchLines[index] ?? '')
171
+ return { uid: uidMatch ? Number(uidMatch[1]) : null, raw }
172
+ })
173
+ }
174
+ await command('LOGOUT').catch(() => {})
175
+ return messages
176
+ } finally {
177
+ reader.clearTimer()
178
+ try { socket.end() } catch {}
179
+ try { socket.destroy?.() } catch {}
180
+ }
181
+ }