@pellux/goodvibes-tui 0.25.0 → 0.27.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 (146) hide show
  1. package/CHANGELOG.md +22 -3
  2. package/README.md +12 -7
  3. package/docs/foundation-artifacts/operator-contract.json +2422 -1040
  4. package/package.json +2 -2
  5. package/src/cli/bundle-command.ts +2 -1
  6. package/src/cli/service-posture.ts +2 -1
  7. package/src/core/conversation-rendering.ts +2 -2
  8. package/src/core/conversation.ts +49 -2
  9. package/src/core/session-recovery.ts +24 -18
  10. package/src/core/system-message-router.ts +42 -26
  11. package/src/core/turn-event-wiring.ts +12 -16
  12. package/src/daemon/{calendar → handlers/calendar}/caldav-client.ts +29 -24
  13. package/src/daemon/handlers/calendar/index.ts +316 -0
  14. package/src/daemon/handlers/context.ts +29 -0
  15. package/src/daemon/handlers/contracts.ts +77 -0
  16. package/src/daemon/{channels → handlers}/drafts/draft-store.ts +114 -50
  17. package/src/daemon/handlers/drafts/index.ts +17 -0
  18. package/src/daemon/handlers/drafts/register.ts +331 -0
  19. package/src/daemon/handlers/email/config.ts +164 -0
  20. package/src/daemon/handlers/email/index.ts +43 -0
  21. package/src/daemon/handlers/email/read-handlers.ts +80 -0
  22. package/src/daemon/handlers/email/runtime.ts +140 -0
  23. package/src/daemon/handlers/email/validation.ts +147 -0
  24. package/src/daemon/handlers/email/write-handlers.ts +133 -0
  25. package/src/daemon/handlers/errors.ts +18 -0
  26. package/src/daemon/{channels → handlers}/inbox/cursor-store.ts +58 -66
  27. package/src/daemon/handlers/inbox/index.ts +211 -0
  28. package/src/daemon/{channels → handlers}/inbox/mapping.ts +8 -6
  29. package/src/daemon/{channels → handlers}/inbox/poller.ts +6 -5
  30. package/src/daemon/{channels → handlers}/inbox/provider-adapter.ts +14 -10
  31. package/src/daemon/{channels → handlers}/inbox/providers/discord.ts +10 -11
  32. package/src/daemon/{channels → handlers}/inbox/providers/email.ts +2 -1
  33. package/src/daemon/{channels → handlers}/inbox/providers/imap-client.ts +1 -1
  34. package/src/daemon/{channels → handlers}/inbox/providers/route-util.ts +4 -3
  35. package/src/daemon/{channels → handlers}/inbox/providers/slack.ts +11 -12
  36. package/src/daemon/handlers/index.ts +107 -0
  37. package/src/daemon/handlers/register.ts +161 -0
  38. package/src/daemon/{remote → handlers/remote}/backends/cloud-terminal.ts +8 -3
  39. package/src/daemon/{remote → handlers/remote}/backends/docker.ts +2 -3
  40. package/src/daemon/handlers/remote/backends/index.ts +40 -0
  41. package/src/daemon/{remote → handlers/remote}/backends/process-runner.ts +16 -40
  42. package/src/daemon/{remote → handlers/remote}/backends/ssh.ts +8 -3
  43. package/src/daemon/{remote → handlers/remote}/backends/types.ts +29 -3
  44. package/src/daemon/{remote → handlers/remote}/dispatcher.ts +27 -6
  45. package/src/daemon/handlers/remote/index.ts +119 -0
  46. package/src/daemon/{remote → handlers/remote}/peer-registry.ts +47 -11
  47. package/src/daemon/handlers/remote/service.ts +191 -0
  48. package/src/daemon/{channels → handlers}/routing/inbox-bridge.ts +33 -20
  49. package/src/daemon/handlers/routing/index.ts +261 -0
  50. package/src/daemon/{channels → handlers}/routing/route-store.ts +57 -16
  51. package/src/daemon/{channels → handlers}/routing/routing-resolver.ts +1 -1
  52. package/src/daemon/{operator → handlers}/sqlite-store.ts +5 -5
  53. package/src/daemon/handlers/triage/index.ts +57 -0
  54. package/src/daemon/handlers/triage/integration.ts +213 -0
  55. package/src/daemon/{triage → handlers/triage}/pipeline.ts +60 -71
  56. package/src/daemon/{triage → handlers/triage}/scorer.ts +21 -21
  57. package/src/daemon/handlers/triage/tagger/discord.ts +187 -0
  58. package/src/daemon/handlers/triage/tagger/imap.ts +384 -0
  59. package/src/daemon/handlers/triage/tagger/index.ts +184 -0
  60. package/src/daemon/handlers/triage/tagger/shared.ts +70 -0
  61. package/src/daemon/handlers/triage/tagger/slack.ts +69 -0
  62. package/src/daemon/handlers/triage/types.ts +50 -0
  63. package/src/export/gist-uploader.ts +3 -1
  64. package/src/input/command-registry.ts +1 -0
  65. package/src/input/commands/cloudflare-runtime.ts +2 -1
  66. package/src/input/commands/guidance-runtime.ts +2 -4
  67. package/src/input/commands/health-runtime.ts +13 -7
  68. package/src/input/commands/knowledge.ts +2 -1
  69. package/src/input/commands/runtime-services.ts +40 -10
  70. package/src/input/handler-command-route.ts +1 -1
  71. package/src/input/handler-interactions.ts +2 -1
  72. package/src/input/handler-modal-routes.ts +2 -1
  73. package/src/input/handler-onboarding-cloudflare.ts +2 -1
  74. package/src/input/handler-onboarding.ts +8 -8
  75. package/src/input/handler-ui-state.ts +1 -1
  76. package/src/input/tts-settings-actions.ts +2 -1
  77. package/src/main.ts +52 -59
  78. package/src/panels/agent-inspector-panel.ts +72 -2
  79. package/src/panels/agent-logs-panel.ts +127 -19
  80. package/src/panels/base-panel.ts +2 -1
  81. package/src/panels/builtin/agent.ts +3 -1
  82. package/src/panels/builtin/development.ts +1 -0
  83. package/src/panels/builtin/session.ts +1 -1
  84. package/src/panels/context-visualizer-panel.ts +24 -14
  85. package/src/panels/cost-tracker-panel.ts +7 -13
  86. package/src/panels/debug-panel.ts +11 -22
  87. package/src/panels/docs-panel.ts +14 -24
  88. package/src/panels/file-explorer-panel.ts +2 -1
  89. package/src/panels/file-preview-panel.ts +2 -1
  90. package/src/panels/git-panel.ts +10 -17
  91. package/src/panels/marketplace-panel.ts +2 -1
  92. package/src/panels/memory-panel.ts +2 -1
  93. package/src/panels/project-planning-panel.ts +5 -4
  94. package/src/panels/provider-health-panel.ts +56 -67
  95. package/src/panels/schedule-panel.ts +4 -7
  96. package/src/panels/session-browser-panel.ts +13 -21
  97. package/src/panels/skills-panel.ts +2 -1
  98. package/src/panels/tasks-panel.ts +2 -7
  99. package/src/panels/thinking-panel.ts +6 -11
  100. package/src/panels/token-budget-panel.ts +31 -15
  101. package/src/panels/tool-inspector-panel.ts +10 -18
  102. package/src/panels/work-plan-panel.ts +2 -1
  103. package/src/panels/wrfc-panel.ts +37 -35
  104. package/src/renderer/agent-detail-modal.ts +2 -2
  105. package/src/renderer/modal-utils.ts +0 -10
  106. package/src/renderer/process-modal.ts +2 -2
  107. package/src/runtime/bootstrap-command-context.ts +3 -0
  108. package/src/runtime/bootstrap-command-parts.ts +3 -1
  109. package/src/runtime/bootstrap-core.ts +31 -31
  110. package/src/runtime/bootstrap-shell.ts +1 -0
  111. package/src/runtime/onboarding/apply.ts +4 -3
  112. package/src/runtime/onboarding/snapshot.ts +4 -3
  113. package/src/runtime/process-lifecycle.ts +195 -0
  114. package/src/runtime/services.ts +52 -36
  115. package/src/runtime/wrfc-persistence.ts +20 -5
  116. package/src/shell/ui-openers.ts +3 -2
  117. package/src/verification/live-verifier.ts +4 -3
  118. package/src/version.ts +1 -1
  119. package/src/core/context-auto-compact.ts +0 -110
  120. package/src/daemon/calendar/index.ts +0 -52
  121. package/src/daemon/calendar/register.ts +0 -527
  122. package/src/daemon/channels/drafts/index.ts +0 -22
  123. package/src/daemon/channels/drafts/register.ts +0 -449
  124. package/src/daemon/channels/inbox/index.ts +0 -58
  125. package/src/daemon/channels/inbox/register.ts +0 -247
  126. package/src/daemon/channels/routing/index.ts +0 -39
  127. package/src/daemon/channels/routing/register.ts +0 -296
  128. package/src/daemon/email/index.ts +0 -68
  129. package/src/daemon/email/register.ts +0 -715
  130. package/src/daemon/operator/index.ts +0 -43
  131. package/src/daemon/operator/register-helper.ts +0 -150
  132. package/src/daemon/operator/surfaces.ts +0 -137
  133. package/src/daemon/operator/types.ts +0 -207
  134. package/src/daemon/remote/backends/index.ts +0 -34
  135. package/src/daemon/remote/index.ts +0 -74
  136. package/src/daemon/remote/register.ts +0 -411
  137. package/src/daemon/triage/index.ts +0 -59
  138. package/src/daemon/triage/integration.ts +0 -179
  139. package/src/daemon/triage/register.ts +0 -231
  140. package/src/daemon/triage/tagger.ts +0 -777
  141. /package/src/daemon/{calendar → handlers/calendar}/ics.ts +0 -0
  142. /package/src/daemon/{operator/credential-store.ts → handlers/credentials.ts} +0 -0
  143. /package/src/daemon/{email → handlers/email}/imap-connector.ts +0 -0
  144. /package/src/daemon/{email → handlers/email}/imap-parsing.ts +0 -0
  145. /package/src/daemon/{email → handlers/email}/smtp-connector.ts +0 -0
  146. /package/src/daemon/{remote → handlers/remote}/backends/local-process.ts +0 -0
@@ -10,9 +10,9 @@
10
10
  // pipeline can persist stable triageScore/triageTags values across polls.
11
11
  // ---------------------------------------------------------------------------
12
12
 
13
- import type { InboundChannelItem } from '../operator/index.ts';
13
+ import type { InboundChannelItem, TriageLabel } from './types.ts';
14
14
 
15
- export type TriageLabel = 'spam' | 'priority' | 'normal';
15
+ export type { TriageLabel } from './types.ts';
16
16
 
17
17
  export interface TriageScore {
18
18
  /** Confidence in the assigned label, 0..1 (2-decimal rounded). */
@@ -127,6 +127,10 @@ function normalizeText(item: InboundChannelItem): string {
127
127
  return `${subject} ${subject} ${snippet}`.trim();
128
128
  }
129
129
 
130
+ function escapeRegExp(value: string): string {
131
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
+ }
133
+
130
134
  function countLexicon(text: string, lexicon: ReadonlyMap<string, number>): number {
131
135
  let total = 0;
132
136
  for (const [term, weight] of lexicon) {
@@ -149,10 +153,6 @@ function countLexicon(text: string, lexicon: ReadonlyMap<string, number>): numbe
149
153
  return total;
150
154
  }
151
155
 
152
- function escapeRegExp(value: string): string {
153
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
154
- }
155
-
156
156
  function upperCaseRatio(text: string): number {
157
157
  const letters = text.replace(/[^a-zA-Z]/g, '');
158
158
  if (letters.length < 8) return 0;
@@ -186,6 +186,21 @@ function clamp01(value: number): number {
186
186
  return value;
187
187
  }
188
188
 
189
+ function mergeLexicon(
190
+ base: ReadonlyMap<string, number>,
191
+ extra: readonly string[] | undefined,
192
+ extraWeight: number,
193
+ ): ReadonlyMap<string, number> {
194
+ if (!extra || extra.length === 0) return base;
195
+ const merged = new Map(base);
196
+ for (const term of extra) {
197
+ const key = term.trim().toLowerCase();
198
+ if (key.length === 0) continue;
199
+ merged.set(key, Math.max(merged.get(key) ?? 0, extraWeight));
200
+ }
201
+ return merged;
202
+ }
203
+
189
204
  /**
190
205
  * Score a single inbound item for spam likelihood and priority likelihood,
191
206
  * then resolve a single label. Deterministic and side-effect free.
@@ -259,21 +274,6 @@ export function scoreInboundItem(
259
274
  };
260
275
  }
261
276
 
262
- function mergeLexicon(
263
- base: ReadonlyMap<string, number>,
264
- extra: readonly string[] | undefined,
265
- extraWeight: number,
266
- ): ReadonlyMap<string, number> {
267
- if (!extra || extra.length === 0) return base;
268
- const merged = new Map(base);
269
- for (const term of extra) {
270
- const key = term.trim().toLowerCase();
271
- if (key.length === 0) continue;
272
- merged.set(key, Math.max(merged.get(key) ?? 0, extraWeight));
273
- }
274
- return merged;
275
- }
276
-
277
277
  /** Map a label to the canonical provider-side tag string applied by the tagger. */
278
278
  export function labelToTag(label: TriageLabel): string {
279
279
  switch (label) {
@@ -0,0 +1,187 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Triage tagger — Discord provider.
3
+ //
4
+ // Two paths, in priority order:
5
+ // 1. REAL thread tags: when the item targets a forum/media-channel thread and
6
+ // a forum-tag mapping resolves >=1 tag id, PATCH the thread's applied_tags
7
+ // (read-then-merge — never blind overwrite). Exact fidelity to the
8
+ // contract's "Discord thread tags".
9
+ // 2. Reaction analog: Discord has no arbitrary per-message tags, so otherwise
10
+ // add a unicode reaction (PUT .../reactions/{emoji}/@me).
11
+ //
12
+ // The bot token is resolved per-apply from the daemon credential store and is
13
+ // never logged or returned.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import type { HandlerContext } from '../../context.ts';
17
+ import type { DaemonCredentialStore } from '../../credentials.ts';
18
+ import { HandlerError } from '../../errors.ts';
19
+ import type { InboundChannelItem } from '../types.ts';
20
+ import type { ApplyTagsResult, TaggerProviderConfig } from './shared.ts';
21
+ import { discordEmojiForTag, stringMeta } from './shared.ts';
22
+ import { summarizeError } from '@pellux/goodvibes-sdk/platform/utils';
23
+
24
+ export async function applyDiscord(
25
+ item: InboundChannelItem,
26
+ tags: string[],
27
+ providers: TaggerProviderConfig,
28
+ credentials: DaemonCredentialStore,
29
+ fetchImpl: typeof fetch,
30
+ ctx: HandlerContext,
31
+ base: ApplyTagsResult,
32
+ ): Promise<ApplyTagsResult> {
33
+ const cfg = providers.discord;
34
+ if (!cfg) return { ...base, reason: 'discord-not-configured' };
35
+ const channelId = stringMeta(item, 'channelId') ?? item.conversationId;
36
+ const messageId = stringMeta(item, 'messageId') ?? item.id;
37
+ if (!channelId || !messageId) return { ...base, reason: 'discord-missing-target' };
38
+ if (tags.length === 0) return { ...base, reason: 'no-tags' };
39
+
40
+ const token = await credentials.resolveConfigSecret(cfg.tokenConfigKey);
41
+ if (!token) return { ...base, reason: 'discord-no-credentials' };
42
+
43
+ // Exact-fidelity path: when the item targets a forum/media-channel thread and
44
+ // a forum-tag mapping resolves at least one tag, apply REAL Discord thread
45
+ // tags (PATCH the thread's applied_tags). A forum post's thread id is the
46
+ // thread's own channel id; accept an explicit metadata.threadId or fall back
47
+ // to channelId for that case.
48
+ const threadId = stringMeta(item, 'threadId') ?? channelId;
49
+ const tagIds = resolveDiscordTagIds(tags, cfg.forumTagIds);
50
+ if (tagIds.length > 0) {
51
+ return applyDiscordThreadTags(item, threadId, tags, tagIds, token, fetchImpl, ctx);
52
+ }
53
+
54
+ // Analog fallback: Discord has no arbitrary per-message tags, so apply a
55
+ // unicode reaction on the source message instead.
56
+ const applied: string[] = [];
57
+ for (const tag of tags) {
58
+ const emoji = encodeURIComponent(discordEmojiForTag(tag));
59
+ const url = `https://discord.com/api/v10/channels/${channelId}/messages/${messageId}/reactions/${emoji}/@me`;
60
+ const response = await fetchImpl(url, {
61
+ method: 'PUT',
62
+ headers: {
63
+ Authorization: `Bot ${token}`,
64
+ 'Content-Length': '0',
65
+ },
66
+ });
67
+ // 204 No Content is the success case for adding a reaction.
68
+ if (response.status !== 204 && response.status !== 200) {
69
+ const detail = await response.text().catch(() => '');
70
+ ctx.logger.warn('triage: discord reaction rejected', { status: response.status });
71
+ throw new HandlerError(
72
+ `Discord reaction HTTP ${response.status}${detail ? `: ${detail.slice(0, 120)}` : ''}`,
73
+ 'TRIAGE_DISCORD_TAG_FAILED',
74
+ 502,
75
+ );
76
+ }
77
+ applied.push(tag);
78
+ }
79
+ return { surface: item.surface, itemId: item.id, appliedTags: applied, skipped: false };
80
+ }
81
+
82
+ /**
83
+ * Map GoodVibes triage tags to configured Discord forum-tag snowflake ids,
84
+ * preserving order and dropping unmapped tags. De-duplicates ids.
85
+ */
86
+ function resolveDiscordTagIds(
87
+ tags: readonly string[],
88
+ forumTagIds: Record<string, string> | undefined,
89
+ ): string[] {
90
+ if (!forumTagIds) return [];
91
+ const ids: string[] = [];
92
+ for (const tag of tags) {
93
+ const id = forumTagIds[tag];
94
+ if (typeof id === 'string' && id.length > 0 && !ids.includes(id)) ids.push(id);
95
+ }
96
+ return ids;
97
+ }
98
+
99
+ /**
100
+ * Apply real Discord thread tags by merging the resolved forum-tag ids into the
101
+ * thread's existing applied_tags via PATCH /channels/{thread.id}. Idempotent:
102
+ * already-present tag ids are kept and not duplicated.
103
+ */
104
+ async function applyDiscordThreadTags(
105
+ item: InboundChannelItem,
106
+ threadId: string,
107
+ tags: readonly string[],
108
+ tagIds: readonly string[],
109
+ token: string,
110
+ fetchImpl: typeof fetch,
111
+ ctx: HandlerContext,
112
+ ): Promise<ApplyTagsResult> {
113
+ const url = `https://discord.com/api/v10/channels/${threadId}`;
114
+ // DATA-LOSS GUARD: we PATCH the thread's full applied_tags array, so we must
115
+ // first read the EXISTING tags and merge. If that read fails (network error
116
+ // OR a non-ok HTTP status), we have no idea what tags are currently on the
117
+ // thread — PATCHing with only our new ids would silently destroy whatever
118
+ // forum tags were already applied. Abort instead of overwriting.
119
+ const existing = await fetchDiscordAppliedTags(url, token, fetchImpl, ctx);
120
+ if (existing === null) {
121
+ throw new HandlerError(
122
+ 'Discord thread tag read failed; aborting to avoid overwriting existing applied_tags.',
123
+ 'TRIAGE_DISCORD_TAG_FAILED',
124
+ 502,
125
+ );
126
+ }
127
+ const merged = [...new Set([...existing, ...tagIds])];
128
+ const response = await fetchImpl(url, {
129
+ method: 'PATCH',
130
+ headers: {
131
+ Authorization: `Bot ${token}`,
132
+ 'Content-Type': 'application/json',
133
+ },
134
+ body: JSON.stringify({ applied_tags: merged }),
135
+ });
136
+ if (response.status !== 200 && response.status !== 204) {
137
+ const detail = await response.text().catch(() => '');
138
+ ctx.logger.warn('triage: discord thread tag rejected', { status: response.status });
139
+ throw new HandlerError(
140
+ `Discord thread tag HTTP ${response.status}${detail ? `: ${detail.slice(0, 120)}` : ''}`,
141
+ 'TRIAGE_DISCORD_TAG_FAILED',
142
+ 502,
143
+ );
144
+ }
145
+ return { surface: item.surface, itemId: item.id, appliedTags: [...tags], skipped: false };
146
+ }
147
+
148
+ /**
149
+ * Read a thread's current applied_tags.
150
+ *
151
+ * Returns:
152
+ * - string[] -> the read SUCCEEDED; the array is the current applied_tags
153
+ * (possibly empty when the thread genuinely has no tags, or
154
+ * when applied_tags is absent/malformed in a 2xx body).
155
+ * - null -> the read FAILED (thrown error OR non-ok HTTP status). The
156
+ * caller MUST NOT proceed with a PATCH in this case, because a
157
+ * failed read means the existing tag set is unknown and a
158
+ * PATCH would overwrite it (data loss).
159
+ */
160
+ async function fetchDiscordAppliedTags(
161
+ url: string,
162
+ token: string,
163
+ fetchImpl: typeof fetch,
164
+ ctx: HandlerContext,
165
+ ): Promise<string[] | null> {
166
+ try {
167
+ const response = await fetchImpl(url, {
168
+ method: 'GET',
169
+ headers: { Authorization: `Bot ${token}` },
170
+ });
171
+ if (!response.ok) {
172
+ ctx.logger.warn('triage: discord thread tag read failed', { status: response.status });
173
+ return null;
174
+ }
175
+ const payload = (await response.json().catch(() => null)) as
176
+ | { applied_tags?: unknown }
177
+ | null;
178
+ const current = payload?.applied_tags;
179
+ if (!Array.isArray(current)) return [];
180
+ return current.filter((t): t is string => typeof t === 'string');
181
+ } catch (error) {
182
+ ctx.logger.warn('triage: discord thread tag read errored', {
183
+ message: summarizeError(error),
184
+ });
185
+ return null;
186
+ }
187
+ }
@@ -0,0 +1,384 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Triage tagger — IMAP provider.
3
+ //
4
+ // Applies a triage label as an IMAP keyword flag (STORE +FLAGS) over a minimal
5
+ // IMAP4rev1-over-TLS client. Credentials are resolved per-apply from the daemon
6
+ // credential store and are NEVER logged or returned. CRLF/control characters in
7
+ // any interpolated command value are rejected (CRLF-injection guard). Transient
8
+ // network failures are retried with bounded exponential backoff; protocol-level
9
+ // NO/BAD rejections are deterministic and never retried.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { connect as tlsConnect } from 'node:tls';
13
+ import type { DaemonCredentialStore } from '../../credentials.ts';
14
+ import type { InboundChannelItem } from '../types.ts';
15
+ import type { ApplyTagsResult, TaggerProviderConfig } from './shared.ts';
16
+ import { imapKeywordForTag } from './shared.ts';
17
+ import { summarizeError } from '@pellux/goodvibes-sdk/platform/utils';
18
+
19
+ export interface ImapStoreArgs {
20
+ host: string;
21
+ port: number;
22
+ user: string;
23
+ password: string;
24
+ mailbox: string;
25
+ uid: string;
26
+ flag: string;
27
+ }
28
+
29
+ export interface ImapRetryOptions {
30
+ /** Total attempts including the first (default 3). Values < 1 disable retry. */
31
+ maxAttempts?: number;
32
+ /** Base backoff in ms for the first retry (default 250). */
33
+ baseDelayMs?: number;
34
+ /** Cap on any single backoff delay in ms (default 2000). */
35
+ maxDelayMs?: number;
36
+ /** Injectable sleep (tests). Defaults to a real timer. */
37
+ sleep?: (ms: number) => Promise<void>;
38
+ }
39
+
40
+ export type ImapStoreFlag = (args: ImapStoreArgs) => Promise<void>;
41
+
42
+ /**
43
+ * The minimal subset of a node:tls TLSSocket that imapStoreFlagOverTls drives.
44
+ * Declaring it explicitly (rather than depending on the full TLSSocket surface)
45
+ * gives the data-pump a precise injection seam: tests can supply an in-memory
46
+ * duplex that exercises the protocol state machine without a real network
47
+ * socket, while the production path passes the real tlsConnect result.
48
+ */
49
+ export interface ImapSocketLike {
50
+ setEncoding(encoding: string): void;
51
+ setTimeout(ms: number, callback: () => void): void;
52
+ write(data: string): void;
53
+ on(event: 'data', listener: (chunk: string) => void): void;
54
+ on(event: 'error', listener: (err: Error) => void): void;
55
+ on(event: 'close', listener: () => void): void;
56
+ destroy(): void;
57
+ }
58
+
59
+ /** Connector seam: opens an ImapSocketLike for the given host/port. */
60
+ export type ImapConnect = (opts: {
61
+ host: string;
62
+ port: number;
63
+ servername: string;
64
+ }) => ImapSocketLike;
65
+
66
+ /** Production connector — a real IMAP4rev1-over-TLS socket via node:tls. */
67
+ export const tlsImapConnect: ImapConnect = (opts) =>
68
+ tlsConnect(opts, () => {
69
+ /* greeting handled in the data pump */
70
+ }) as unknown as ImapSocketLike;
71
+
72
+ export async function applyImap(
73
+ item: InboundChannelItem,
74
+ tags: string[],
75
+ providers: TaggerProviderConfig,
76
+ credentials: DaemonCredentialStore,
77
+ storeFlag: ImapStoreFlag,
78
+ base: ApplyTagsResult,
79
+ ): Promise<ApplyTagsResult> {
80
+ const cfg = providers.imap;
81
+ if (!cfg) return { ...base, reason: 'imap-not-configured' };
82
+ const uid = imapUidFromItem(item);
83
+ if (!uid) return { ...base, reason: 'imap-missing-uid' };
84
+ if (tags.length === 0) return { ...base, reason: 'no-tags' };
85
+
86
+ const password = await credentials.resolveConfigSecret(cfg.passwordConfigKey);
87
+ if (!password) return { ...base, reason: 'imap-no-credentials' };
88
+
89
+ const applied: string[] = [];
90
+ for (const tag of tags) {
91
+ await storeFlag({
92
+ host: cfg.host,
93
+ port: cfg.port ?? 993,
94
+ user: cfg.user,
95
+ password,
96
+ mailbox: cfg.mailbox ?? 'INBOX',
97
+ uid,
98
+ flag: imapKeywordForTag(tag),
99
+ });
100
+ applied.push(tag);
101
+ }
102
+ return { surface: item.surface, itemId: item.id, appliedTags: applied, skipped: false };
103
+ }
104
+
105
+ function imapUidFromItem(item: InboundChannelItem): string | null {
106
+ const meta = item.metadata ?? {};
107
+ const uid = meta.imapUid ?? meta.uid;
108
+ if (typeof uid === 'string' && uid.length > 0) return uid;
109
+ if (typeof uid === 'number' && Number.isFinite(uid)) return String(uid);
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Error subclass carrying whether a failure is transient (worth retrying) or a
115
+ * deterministic protocol rejection (NO/BAD) that must not be retried.
116
+ */
117
+ export class ImapStoreError extends Error {
118
+ readonly transient: boolean;
119
+ constructor(message: string, transient: boolean) {
120
+ super(message);
121
+ this.name = 'ImapStoreError';
122
+ this.transient = transient;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Reject CR, LF, NUL and any other ASCII control character (0x00-0x1F, 0x7F)
128
+ * in a value destined for an IMAP command line. CR/LF are the dangerous ones:
129
+ * an unescaped CRLF would terminate the current command and let an attacker
130
+ * inject a second IMAP command (CRLF injection). IMAP's quoted-string syntax
131
+ * has no escape for these control chars — backslash only escapes `\` and `"` —
132
+ * so the only safe handling is to refuse the value outright.
133
+ */
134
+ function assertImapSafe(value: string, field: string): void {
135
+ // eslint-disable-next-line no-control-regex -- intentional control-char guard
136
+ if (/[\x00-\x1F\x7F]/.test(value)) {
137
+ throw new ImapStoreError(
138
+ `IMAP ${field} contains illegal control characters (possible CRLF injection)`,
139
+ false,
140
+ );
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Wrap a value as an IMAP quoted string. Backslash and double-quote are escaped
146
+ * per RFC 3501; control characters are NOT escapable in the quoted-string
147
+ * grammar, so callers MUST validate with assertImapSafe first. quoteImap
148
+ * re-asserts as defense-in-depth so no future caller can bypass the guard.
149
+ */
150
+ function quoteImap(value: string): string {
151
+ assertImapSafe(value, 'value');
152
+ return `"${value.replace(/([\\"])/g, '\\$1')}"`;
153
+ }
154
+
155
+ // A concrete UID sequence-set: one or more comma-separated single UIDs or
156
+ // numeric ranges (`12`, `3:9`, `1,4,7:9`). RFC 3501 also permits `*` (the
157
+ // largest UID in the mailbox) and ranges to `*`, but a wildcard would let a
158
+ // single value like `1:*` apply the flag to the ENTIRE mailbox — never the
159
+ // intent when tagging one triaged item — so `*` is rejected outright.
160
+ const IMAP_UID_SET = /^[0-9]+(:[0-9]+)?(,[0-9]+(:[0-9]+)?)*$/;
161
+
162
+ // An IMAP flag: an optional leading `\` (system flag, e.g. `\Seen`) followed by
163
+ // atom characters only. The atom grammar excludes SP and the list/quoting
164
+ // specials `(){%*"\` and `]`, so a flag cannot contain a space (which would
165
+ // otherwise inject a second flag atom into the `+FLAGS (...)` list) or close
166
+ // the parenthesised list early.
167
+ // eslint-disable-next-line no-control-regex -- atom grammar excludes controls
168
+ const IMAP_FLAG = /^\\?[^\s(){%*"\\\]\x00-\x1F\x7F]+$/;
169
+
170
+ /**
171
+ * Validate an IMAP UID value as a concrete sequence-set before it is
172
+ * interpolated UNQUOTED into `UID STORE`. assertImapSafe only blocks control
173
+ * chars; a control-char-free wildcard like `1:*` would still pass that guard
174
+ * and mutate the whole mailbox. This is the boundary check that prevents it.
175
+ */
176
+ function assertImapUid(value: string): void {
177
+ if (!IMAP_UID_SET.test(value)) {
178
+ throw new ImapStoreError(
179
+ `IMAP uid is not a valid numeric sequence-set: ${JSON.stringify(value)}`,
180
+ false,
181
+ );
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Validate an IMAP flag against the flag/atom grammar before it is interpolated
187
+ * UNQUOTED into the `+FLAGS (...)` list. assertImapSafe only blocks control
188
+ * chars; a flag containing a space (e.g. `\Seen Junk`) would still pass that
189
+ * guard and inject a second flag atom. This is the boundary check that
190
+ * prevents it — independent of any upstream normalizer.
191
+ */
192
+ function assertImapFlag(value: string): void {
193
+ if (!IMAP_FLAG.test(value)) {
194
+ throw new ImapStoreError(
195
+ `IMAP flag is not a valid flag-keyword atom: ${JSON.stringify(value)}`,
196
+ false,
197
+ );
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Minimal IMAP4rev1 client: connect over TLS, LOGIN, SELECT, UID STORE +FLAGS,
203
+ * LOGOUT. Uses only node:tls (Bun-compatible).
204
+ *
205
+ * Tagged-command sequencing uses an explicit completion flag rather than a line
206
+ * heuristic: the LOGOUT step is tracked by reference, so its tagged OK (or an
207
+ * untagged `* BYE`) cleanly completes the operation and tells the `close`
208
+ * handler the disconnect was expected. Connection/timeout/socket failures are
209
+ * surfaced as transient ImapStoreError; NO/BAD protocol responses as
210
+ * non-transient.
211
+ */
212
+ export function imapStoreFlagOverTls(
213
+ args: ImapStoreArgs,
214
+ connect: ImapConnect = tlsImapConnect,
215
+ ): Promise<void> {
216
+ return new Promise<void>((resolve, reject) => {
217
+ try {
218
+ assertImapSafe(args.user, 'user');
219
+ assertImapSafe(args.password, 'password');
220
+ assertImapSafe(args.mailbox, 'mailbox');
221
+ assertImapSafe(args.uid, 'uid');
222
+ assertImapSafe(args.flag, 'flag');
223
+ // uid and flag are interpolated UNQUOTED below; the control-char guard
224
+ // alone is insufficient, so enforce the structural grammar here too.
225
+ assertImapUid(args.uid);
226
+ assertImapFlag(args.flag);
227
+ } catch (err) {
228
+ reject(
229
+ err instanceof ImapStoreError
230
+ ? err
231
+ : new ImapStoreError(summarizeError(err), false),
232
+ );
233
+ return;
234
+ }
235
+ type Step = { tag: string; isLogout: boolean; resolve: () => void; reject: (e: Error) => void };
236
+
237
+ let done = false;
238
+ let completed = false; // LOGOUT acknowledged (or BYE seen) — close is expected.
239
+ let buffer = '';
240
+ let pending: Step | null = null;
241
+ let counter = 0;
242
+ let greeted = false;
243
+
244
+ const finish = (err?: Error): void => {
245
+ if (done) return;
246
+ done = true;
247
+ try {
248
+ socket.destroy();
249
+ } catch {
250
+ /* ignore */
251
+ }
252
+ if (err) reject(err);
253
+ else resolve();
254
+ };
255
+
256
+ const socket: ImapSocketLike = connect({
257
+ host: args.host,
258
+ port: args.port,
259
+ servername: args.host,
260
+ });
261
+ socket.setEncoding('utf-8');
262
+ socket.setTimeout(20_000, () =>
263
+ finish(new ImapStoreError('IMAP connection timed out', true)),
264
+ );
265
+
266
+ const send = (command: string, isLogout = false): Promise<void> =>
267
+ new Promise<void>((res, rej) => {
268
+ counter += 1;
269
+ const tag = `A${counter}`;
270
+ pending = { tag, isLogout, resolve: res, reject: rej };
271
+ socket.write(`${tag} ${command}\r\n`);
272
+ });
273
+
274
+ const runSequence = async (): Promise<void> => {
275
+ await send(`LOGIN ${quoteImap(args.user)} ${quoteImap(args.password)}`);
276
+ await send(`SELECT ${quoteImap(args.mailbox)}`);
277
+ await send(`UID STORE ${args.uid} +FLAGS (${args.flag})`);
278
+ await send('LOGOUT', true);
279
+ };
280
+
281
+ const handleLine = (line: string): void => {
282
+ if (!greeted) {
283
+ greeted = true;
284
+ if (!/^\* (OK|PREAUTH)/i.test(line)) {
285
+ finish(new ImapStoreError(`IMAP server rejected connection: ${line}`, true));
286
+ return;
287
+ }
288
+ runSequence().catch((err) =>
289
+ finish(
290
+ err instanceof ImapStoreError
291
+ ? err
292
+ : new ImapStoreError(summarizeError(err), false),
293
+ ),
294
+ );
295
+ return;
296
+ }
297
+
298
+ // An untagged BYE during LOGOUT is the server announcing a clean close.
299
+ if (/^\* BYE/i.test(line) && pending?.isLogout) {
300
+ completed = true;
301
+ return;
302
+ }
303
+
304
+ if (!pending) return;
305
+ if (!line.startsWith(`${pending.tag} `)) return; // untagged data line
306
+ const status = line.slice(pending.tag.length + 1);
307
+ const current = pending;
308
+ pending = null;
309
+ if (/^OK/i.test(status)) {
310
+ current.resolve();
311
+ if (current.isLogout) {
312
+ completed = true;
313
+ finish();
314
+ }
315
+ } else {
316
+ // NO/BAD: deterministic protocol rejection — do not retry.
317
+ current.reject(new ImapStoreError(`IMAP command failed: ${status}`, false));
318
+ }
319
+ };
320
+
321
+ socket.on('error', (err) =>
322
+ finish(new ImapStoreError(summarizeError(err), true)),
323
+ );
324
+ socket.on('close', () => {
325
+ if (completed) finish();
326
+ else finish(new ImapStoreError('IMAP connection closed unexpectedly', true));
327
+ });
328
+ socket.on('data', (chunk: string) => {
329
+ buffer += chunk;
330
+ let newlineIdx = buffer.indexOf('\n');
331
+ while (newlineIdx !== -1) {
332
+ const line = buffer.slice(0, newlineIdx).replace(/\r$/, '');
333
+ buffer = buffer.slice(newlineIdx + 1);
334
+ handleLine(line);
335
+ newlineIdx = buffer.indexOf('\n');
336
+ }
337
+ });
338
+ });
339
+ }
340
+
341
+ /** True when an error is worth retrying (network/connection, not protocol). */
342
+ function isTransientImapError(error: unknown): boolean {
343
+ if (error instanceof ImapStoreError) return error.transient;
344
+ const code = (error as { code?: unknown })?.code;
345
+ if (typeof code === 'string') {
346
+ return ['ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN']
347
+ .includes(code);
348
+ }
349
+ return false;
350
+ }
351
+
352
+ const defaultSleep = (ms: number): Promise<void> =>
353
+ new Promise((res) => setTimeout(res, ms));
354
+
355
+ /**
356
+ * Wrap an IMAP store function with bounded exponential-backoff retry on
357
+ * transient failures only. Protocol-level (NO/BAD) errors are surfaced on the
358
+ * first attempt without retry.
359
+ */
360
+ export function makeRetryingImapStoreFlag(
361
+ inner: ImapStoreFlag,
362
+ retry: ImapRetryOptions = {},
363
+ ): ImapStoreFlag {
364
+ const maxAttempts = Math.max(1, retry.maxAttempts ?? 3);
365
+ const baseDelayMs = Math.max(0, retry.baseDelayMs ?? 250);
366
+ const maxDelayMs = Math.max(baseDelayMs, retry.maxDelayMs ?? 2_000);
367
+ const sleep = retry.sleep ?? defaultSleep;
368
+
369
+ return async (args: ImapStoreArgs): Promise<void> => {
370
+ let lastError: unknown;
371
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
372
+ try {
373
+ await inner(args);
374
+ return;
375
+ } catch (error) {
376
+ lastError = error;
377
+ if (attempt >= maxAttempts || !isTransientImapError(error)) throw error;
378
+ const delay = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
379
+ await sleep(delay);
380
+ }
381
+ }
382
+ throw lastError;
383
+ };
384
+ }