@hyperwindmill/caretaker-cli 0.20.0 → 0.21.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 (42) hide show
  1. package/dist/cli/mcp.js +5 -5
  2. package/dist/cli/web/mcp_bridge.d.ts +1 -1
  3. package/dist/cli/web/mcp_bridge.d.ts.map +1 -1
  4. package/dist/cli/web/mcp_bridge.js +23 -7
  5. package/dist/cli/web/scheduler/heartbeat.d.ts +2 -2
  6. package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -1
  7. package/dist/cli/web/scheduler/strategy.d.ts +3 -3
  8. package/dist/cli/web/scheduler/strategy.d.ts.map +1 -1
  9. package/dist/cli/web/scheduler/task_roles.d.ts +0 -4
  10. package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -1
  11. package/dist/cli/web/scheduler/task_roles.js +12 -2
  12. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
  13. package/dist/cli/web/scheduler/task_strategy.js +4 -1
  14. package/dist/cli/web/scheduler/telegram.d.ts.map +1 -1
  15. package/dist/cli/web/scheduler/telegram.js +4 -1
  16. package/dist/cli/web/server.d.ts.map +1 -1
  17. package/dist/cli/web/server.js +10 -4
  18. package/dist/harness/claude_code_runner.d.ts.map +1 -1
  19. package/dist/harness/claude_code_runner.js +5 -1
  20. package/dist/harness/tools/builtin/email_tools.d.ts +5 -0
  21. package/dist/harness/tools/builtin/email_tools.d.ts.map +1 -0
  22. package/dist/harness/tools/builtin/email_tools.js +182 -0
  23. package/dist/harness/tools/builtin/index.d.ts +2 -1
  24. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  25. package/dist/harness/tools/builtin/index.js +7 -1
  26. package/dist/harness/tools/resolve.d.ts.map +1 -1
  27. package/dist/harness/tools/resolve.js +9 -4
  28. package/dist/lib/email.d.ts +132 -0
  29. package/dist/lib/email.d.ts.map +1 -0
  30. package/dist/lib/email.js +306 -0
  31. package/dist/mcp/builtin_server.d.ts +13 -0
  32. package/dist/mcp/builtin_server.d.ts.map +1 -0
  33. package/dist/mcp/builtin_server.js +65 -0
  34. package/dist/store/json.d.ts.map +1 -1
  35. package/dist/store/json.js +6 -0
  36. package/dist/tui/agents.js +36 -14
  37. package/dist/webview/standalone.js +340 -35
  38. package/dist/webview/standalone.js.map +3 -3
  39. package/package.json +8 -3
  40. package/dist/mcp/task_server.d.ts +0 -9
  41. package/dist/mcp/task_server.d.ts.map +0 -1
  42. package/dist/mcp/task_server.js +0 -48
@@ -0,0 +1,132 @@
1
+ import type { ServiceConfig } from '../types.js';
2
+ /**
3
+ * Ceiling on one mail network operation, and the same reasoning as
4
+ * `NET_TIMEOUT_MS` in lib/task_git.ts: an unattended run must not hang forever
5
+ * on a wedged server. The abort also carries `ctx.signal`, so Pause and the
6
+ * task's wall-clock budget reach *inside* an in-flight connection — the loop
7
+ * only checks the signal between turns, and would otherwise sit awaiting this
8
+ * tool call.
9
+ */
10
+ export declare const NET_TIMEOUT_MS = 60000;
11
+ /** An email account with its secrets decrypted and its defaults applied. */
12
+ export type EmailAccount = {
13
+ name: string;
14
+ from: string;
15
+ smtpHost: string;
16
+ smtpPort: number;
17
+ smtpSecure: boolean;
18
+ smtpUser: string;
19
+ smtpPassword: string;
20
+ imapHost: string;
21
+ imapPort: number;
22
+ imapSecure: boolean;
23
+ imapUser: string;
24
+ imapPassword: string;
25
+ /** Outbound: who this account may send to. Enforced by email_send. */
26
+ allowedRecipients: string[];
27
+ /** Inbound: whose mail this account may hand to an agent. Enforced by fetchInbox. */
28
+ allowedSenders: string[];
29
+ /** Agent ids this account is restricted to. Empty = every agent. */
30
+ allowedAgents: string[];
31
+ };
32
+ /** An account can send only if it has somewhere to send through. */
33
+ export declare function canSend(a: EmailAccount): boolean;
34
+ /** …and can be read only if it has a mailbox to read. */
35
+ export declare function canRead(a: EmailAccount): boolean;
36
+ /** Split a comma/newline-separated allowlist into patterns. */
37
+ export declare function parsePatterns(raw: string | undefined): string[];
38
+ /**
39
+ * Does `address` match any of `patterns`? `*` is the only wildcard and matches
40
+ * any run of characters, so `*@example.com` and a bare `*` both work; anything
41
+ * else is compared literally. Case-insensitive.
42
+ *
43
+ * An empty pattern list means "no allowlist configured" and allows everything —
44
+ * the restriction is opt-in, see the design doc.
45
+ */
46
+ export declare function matchesAllowlist(address: string, patterns: string[]): boolean;
47
+ /**
48
+ * Pull the bare address out of a recipient string, so a display-name form
49
+ * ("Ada <ada@example.com>") is checked against the allowlist by its address and
50
+ * not by the whole label.
51
+ */
52
+ export declare function bareAddress(recipient: string): string;
53
+ /** Every enabled `email` service, with defaults applied and secrets revealed.
54
+ * Direction is not filtered here — ask canSend()/canRead(). */
55
+ export declare function emailAccounts(services: ServiceConfig[]): EmailAccount[];
56
+ /**
57
+ * Narrow a list to the accounts one agent may use. A scoped account is removed
58
+ * outright rather than refused later: the agent never sees a mailbox it cannot
59
+ * touch, so it cannot name it, be tricked into naming it, or report that it
60
+ * exists.
61
+ *
62
+ * `agentId` undefined means the caller has no agent identity, and that only
63
+ * happens for callers that already hold full access to CARETAKER_HOME — the
64
+ * `caretaker-cli mcp` stdio server (whose trust boundary IS local process
65
+ * access) and direct in-process calls. Those see everything. Any new surface
66
+ * that executes these tools on behalf of an agent MUST set `ctx.callerAgent`,
67
+ * or it silently opts out of scoping.
68
+ */
69
+ export declare function visibleAccounts(accounts: EmailAccount[], agentId?: string): EmailAccount[];
70
+ /** Configured accounts visible to `agentId`, read from the live config. */
71
+ export declare function listEmailAccounts(agentId?: string): Promise<EmailAccount[]>;
72
+ /** Look an account up by service name, case-insensitively. */
73
+ export declare function findAccount(accounts: EmailAccount[], name: string): EmailAccount | undefined;
74
+ export type OutgoingMail = {
75
+ to: string[];
76
+ cc?: string[];
77
+ bcc?: string[];
78
+ subject: string;
79
+ body: string;
80
+ };
81
+ /** Send one plain-text message. Returns the SMTP message id. */
82
+ export declare function sendEmail(account: EmailAccount, mail: OutgoingMail, signal?: AbortSignal): Promise<string>;
83
+ /** Hard ceiling on messages per call, whatever the caller asks for. */
84
+ export declare const MAX_FETCH = 50;
85
+ /** How many unread messages we are willing to look at to fill one window.
86
+ * Only matters with a sender allowlist: unlisted mail is skipped and left
87
+ * unread, so without a bound a mailbox full of junk would be re-scanned
88
+ * forever. The scan itself is one cheap ENVELOPE fetch, not a download. */
89
+ export declare const MAX_SCAN = 200;
90
+ /** Hard ceiling on the body text handed to the model, per message. */
91
+ export declare const MAX_BODY_CHARS = 8000;
92
+ export type InboundMessage = {
93
+ uid: number;
94
+ from: string;
95
+ to: string;
96
+ subject: string;
97
+ date: string;
98
+ body: string;
99
+ /** Set when the body hit MAX_BODY_CHARS. */
100
+ truncated?: boolean;
101
+ attachments: string[];
102
+ };
103
+ /** ISO-8601 for whatever the parser or the server gave us; '' when unusable. */
104
+ export declare function isoDate(value: Date | string | undefined): string;
105
+ export declare function clampLimit(limit: unknown): number;
106
+ export declare function truncateBody(text: string): {
107
+ body: string;
108
+ truncated: boolean;
109
+ };
110
+ /** Best-effort plain text for a message: the text/plain part, else the HTML converted. */
111
+ export declare function messageText(parsed: {
112
+ text?: string;
113
+ html?: string | false;
114
+ }): string;
115
+ export type FetchOptions = {
116
+ limit?: number;
117
+ /** Unread only (default true) — the whole point of the \Seen convention. */
118
+ unreadOnly?: boolean;
119
+ /** Server-side subject substring filter. */
120
+ subject?: string;
121
+ /** Mark the delivered messages \Seen (default true), so the next run skips them. */
122
+ markSeen?: boolean;
123
+ /** Run-level abort (ctx.signal): closes the connection mid-flight. */
124
+ signal?: AbortSignal;
125
+ };
126
+ /** Read the oldest matching messages from INBOX. */
127
+ export declare function fetchInbox(account: EmailAccount, opts?: FetchOptions): Promise<{
128
+ messages: InboundMessage[];
129
+ refused: number;
130
+ scanTruncated?: boolean;
131
+ }>;
132
+ //# sourceMappingURL=email.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAkBA,OAAO,KAA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GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,CAIhE;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAIjD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAI/E;AAID,0FAA0F;AAC1F,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;CAAE,GAAG,MAAM,CAIpF;AAED,MAAM,MAAM,YAAY,GAAG;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oFAAoF;IACpF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,oDAAoD;AACpD,wBAAsB,UAAU,CAC9B,OAAO,EAAE,YAAY,EACrB,IAAI,GAAE,YAAiB,GACtB,OAAO,CAAC;IAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CA0FnF"}
@@ -0,0 +1,306 @@
1
+ // Email accounts for the agent-facing email tools.
2
+ //
3
+ // An account is a `type: 'email'` entry in the Services collection
4
+ // (`caretaker.json` → `scheduler.tasks`, see store/json.ts). The record holds
5
+ // both halves of a mailbox: IMAP for reading and SMTP for sending, each
6
+ // independently optional — an account with no `smtpHost` cannot send, one with
7
+ // no `imapHost` cannot read. The SMTP credentials default to the IMAP ones —
8
+ // one mailbox, one login, in the common case — and only need their own fields
9
+ // when the provider splits them.
10
+ //
11
+ // This module owns account resolution, the address allowlists, and the two
12
+ // network operations. Everything except sendEmail()/fetchInbox() is pure, which
13
+ // is where the tests live.
14
+ import nodemailer from 'nodemailer';
15
+ import { ImapFlow } from 'imapflow';
16
+ import { simpleParser } from 'mailparser';
17
+ import TurndownService from 'turndown';
18
+ import { loadConfig } from '../store/json.js';
19
+ import { decrypt, isEncrypted } from './encryption.js';
20
+ /**
21
+ * Ceiling on one mail network operation, and the same reasoning as
22
+ * `NET_TIMEOUT_MS` in lib/task_git.ts: an unattended run must not hang forever
23
+ * on a wedged server. The abort also carries `ctx.signal`, so Pause and the
24
+ * task's wall-clock budget reach *inside* an in-flight connection — the loop
25
+ * only checks the signal between turns, and would otherwise sit awaiting this
26
+ * tool call.
27
+ */
28
+ export const NET_TIMEOUT_MS = 60_000;
29
+ /** Arm `close` on abort or timeout; returns the disarm to call in a finally. */
30
+ function armAbort(close, signal) {
31
+ const timer = setTimeout(close, NET_TIMEOUT_MS);
32
+ const onAbort = () => close();
33
+ signal?.addEventListener('abort', onAbort, { once: true });
34
+ return () => {
35
+ clearTimeout(timer);
36
+ signal?.removeEventListener('abort', onAbort);
37
+ };
38
+ }
39
+ /** An account can send only if it has somewhere to send through. */
40
+ export function canSend(a) {
41
+ return !!a.smtpHost;
42
+ }
43
+ /** …and can be read only if it has a mailbox to read. */
44
+ export function canRead(a) {
45
+ return !!a.imapHost;
46
+ }
47
+ function reveal(value) {
48
+ if (!value)
49
+ return '';
50
+ return isEncrypted(value) ? decrypt(value) : value;
51
+ }
52
+ /** Split a comma/newline-separated allowlist into patterns. */
53
+ export function parsePatterns(raw) {
54
+ return (raw ?? '')
55
+ .split(/[,\n;]/)
56
+ .map((p) => p.trim())
57
+ .filter(Boolean);
58
+ }
59
+ /**
60
+ * Does `address` match any of `patterns`? `*` is the only wildcard and matches
61
+ * any run of characters, so `*@example.com` and a bare `*` both work; anything
62
+ * else is compared literally. Case-insensitive.
63
+ *
64
+ * An empty pattern list means "no allowlist configured" and allows everything —
65
+ * the restriction is opt-in, see the design doc.
66
+ */
67
+ export function matchesAllowlist(address, patterns) {
68
+ if (patterns.length === 0)
69
+ return true;
70
+ const addr = address.trim().toLowerCase();
71
+ return patterns.some((pattern) => {
72
+ const rx = new RegExp('^' +
73
+ pattern
74
+ .toLowerCase()
75
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
76
+ .replace(/\\\*/g, '.*') +
77
+ '$');
78
+ return rx.test(addr);
79
+ });
80
+ }
81
+ /**
82
+ * Pull the bare address out of a recipient string, so a display-name form
83
+ * ("Ada <ada@example.com>") is checked against the allowlist by its address and
84
+ * not by the whole label.
85
+ */
86
+ export function bareAddress(recipient) {
87
+ const angled = recipient.match(/<([^>]*)>/);
88
+ return (angled ? angled[1] : recipient).trim();
89
+ }
90
+ /** Every enabled `email` service, with defaults applied and secrets revealed.
91
+ * Direction is not filtered here — ask canSend()/canRead(). */
92
+ export function emailAccounts(services) {
93
+ return services
94
+ .filter((s) => s.type === 'email' && s.enabled)
95
+ .map((s) => ({
96
+ name: s.name,
97
+ from: (s.smtpFrom || s.imapUser || '').trim(),
98
+ smtpHost: (s.smtpHost ?? '').trim(),
99
+ // ponytail: 587 covers plaintext-or-STARTTLS, which is what smtpSecure
100
+ // false means; a 465 account has to say so via the port anyway.
101
+ smtpPort: s.smtpPort || (s.smtpSecure ? 465 : 587),
102
+ smtpSecure: s.smtpSecure ?? false,
103
+ smtpUser: (s.smtpUser || s.imapUser || '').trim(),
104
+ smtpPassword: reveal(s.smtpPassword || s.imapPassword),
105
+ imapHost: (s.imapHost ?? '').trim(),
106
+ imapPort: s.imapPort || (s.imapSecure === false ? 143 : 993),
107
+ imapSecure: s.imapSecure !== false,
108
+ imapUser: (s.imapUser ?? '').trim(),
109
+ imapPassword: reveal(s.imapPassword),
110
+ allowedRecipients: parsePatterns(s.allowedRecipients),
111
+ allowedSenders: parsePatterns(s.allowedSenders),
112
+ allowedAgents: (s.allowedAgents ?? []).filter(Boolean),
113
+ }));
114
+ }
115
+ /**
116
+ * Narrow a list to the accounts one agent may use. A scoped account is removed
117
+ * outright rather than refused later: the agent never sees a mailbox it cannot
118
+ * touch, so it cannot name it, be tricked into naming it, or report that it
119
+ * exists.
120
+ *
121
+ * `agentId` undefined means the caller has no agent identity, and that only
122
+ * happens for callers that already hold full access to CARETAKER_HOME — the
123
+ * `caretaker-cli mcp` stdio server (whose trust boundary IS local process
124
+ * access) and direct in-process calls. Those see everything. Any new surface
125
+ * that executes these tools on behalf of an agent MUST set `ctx.callerAgent`,
126
+ * or it silently opts out of scoping.
127
+ */
128
+ export function visibleAccounts(accounts, agentId) {
129
+ if (!agentId)
130
+ return accounts;
131
+ return accounts.filter((a) => a.allowedAgents.length === 0 || a.allowedAgents.includes(agentId));
132
+ }
133
+ /** Configured accounts visible to `agentId`, read from the live config. */
134
+ export async function listEmailAccounts(agentId) {
135
+ const config = await loadConfig();
136
+ return visibleAccounts(emailAccounts(config.scheduler?.tasks ?? []), agentId);
137
+ }
138
+ /** Look an account up by service name, case-insensitively. */
139
+ export function findAccount(accounts, name) {
140
+ const wanted = name.trim().toLowerCase();
141
+ return accounts.find((a) => a.name.trim().toLowerCase() === wanted);
142
+ }
143
+ /** Send one plain-text message. Returns the SMTP message id. */
144
+ export async function sendEmail(account, mail, signal) {
145
+ if (signal?.aborted)
146
+ throw new Error('aborted before connecting');
147
+ const transport = nodemailer.createTransport({
148
+ host: account.smtpHost,
149
+ port: account.smtpPort,
150
+ secure: account.smtpSecure,
151
+ // A server with auth disabled (the GreenMail fixture) rejects an AUTH
152
+ // command outright, so omit the credentials rather than send empty ones.
153
+ auth: account.smtpUser ? { user: account.smtpUser, pass: account.smtpPassword } : undefined,
154
+ });
155
+ const disarm = armAbort(() => transport.close(), signal);
156
+ try {
157
+ const info = await transport.sendMail({
158
+ from: account.from,
159
+ to: mail.to,
160
+ cc: mail.cc,
161
+ bcc: mail.bcc,
162
+ subject: mail.subject,
163
+ text: mail.body,
164
+ });
165
+ return info.messageId;
166
+ }
167
+ finally {
168
+ disarm();
169
+ transport.close();
170
+ }
171
+ }
172
+ // ─── Inbound ──────────────────────────────────────────────────────────────
173
+ //
174
+ // There is no `email` scheduler strategy and no stored UID cursor: an inbound
175
+ // workflow is a `heartbeat` service whose prompt tells the agent to call
176
+ // email_fetch, and "already handled" is the IMAP `\Seen` flag — server state,
177
+ // shared with the user's own mail client. Two behaviours on one account are two
178
+ // heartbeats, which is also how a per-subject triage is expressed.
179
+ /** Hard ceiling on messages per call, whatever the caller asks for. */
180
+ export const MAX_FETCH = 50;
181
+ /** How many unread messages we are willing to look at to fill one window.
182
+ * Only matters with a sender allowlist: unlisted mail is skipped and left
183
+ * unread, so without a bound a mailbox full of junk would be re-scanned
184
+ * forever. The scan itself is one cheap ENVELOPE fetch, not a download. */
185
+ export const MAX_SCAN = 200;
186
+ /** Hard ceiling on the body text handed to the model, per message. */
187
+ export const MAX_BODY_CHARS = 8000;
188
+ /** ISO-8601 for whatever the parser or the server gave us; '' when unusable. */
189
+ export function isoDate(value) {
190
+ if (!value)
191
+ return '';
192
+ const d = value instanceof Date ? value : new Date(value);
193
+ return Number.isNaN(d.getTime()) ? '' : d.toISOString();
194
+ }
195
+ export function clampLimit(limit) {
196
+ const n = Math.trunc(Number(limit));
197
+ if (!Number.isFinite(n) || n < 1)
198
+ return 10;
199
+ return Math.min(n, MAX_FETCH);
200
+ }
201
+ export function truncateBody(text) {
202
+ const clean = text.replace(/\r\n/g, '\n').trim();
203
+ if (clean.length <= MAX_BODY_CHARS)
204
+ return { body: clean, truncated: false };
205
+ return { body: clean.slice(0, MAX_BODY_CHARS) + '\n[…truncated]', truncated: true };
206
+ }
207
+ const turndown = new TurndownService();
208
+ /** Best-effort plain text for a message: the text/plain part, else the HTML converted. */
209
+ export function messageText(parsed) {
210
+ if (parsed.text?.trim())
211
+ return parsed.text;
212
+ if (typeof parsed.html === 'string' && parsed.html.trim())
213
+ return turndown.turndown(parsed.html);
214
+ return '';
215
+ }
216
+ /** Read the oldest matching messages from INBOX. */
217
+ export async function fetchInbox(account, opts = {}) {
218
+ const limit = clampLimit(opts.limit);
219
+ const markSeen = opts.markSeen !== false;
220
+ if (opts.signal?.aborted)
221
+ throw new Error('aborted before connecting');
222
+ const client = new ImapFlow({
223
+ host: account.imapHost,
224
+ port: account.imapPort,
225
+ secure: account.imapSecure,
226
+ auth: { user: account.imapUser, pass: account.imapPassword },
227
+ logger: false,
228
+ });
229
+ const disarm = armAbort(() => client.close(), opts.signal);
230
+ try {
231
+ await client.connect();
232
+ }
233
+ catch (err) {
234
+ disarm();
235
+ throw err;
236
+ }
237
+ const lock = await client.getMailboxLock('INBOX');
238
+ try {
239
+ // Only the two criteria every server implements the same way. The sender
240
+ // allowlist is applied below, host-side: IMAP `SEARCH FROM` is substring by
241
+ // spec but not in practice (GreenMail matches whole addresses only and
242
+ // errors on a leading `@`), and `OR` is just as uneven — a filter that
243
+ // silently returns nothing on some servers is worse than no filter.
244
+ const criteria = {};
245
+ if (opts.unreadOnly !== false)
246
+ criteria.seen = false;
247
+ if (opts.subject?.trim())
248
+ criteria.subject = opts.subject.trim();
249
+ const uids = (await client.search(Object.keys(criteria).length ? criteria : { all: true }, {
250
+ uid: true,
251
+ }));
252
+ if (!uids || uids.length === 0)
253
+ return { messages: [], refused: 0 };
254
+ // Oldest first: a queue is processed from the front, never sampled.
255
+ const window = uids.slice(0, MAX_SCAN);
256
+ const scanTruncated = uids.length > window.length;
257
+ // One cheap pass over envelopes decides who is allowed, so mail we may not
258
+ // read is never downloaded.
259
+ const allowed = [];
260
+ let refused = 0;
261
+ for await (const msg of client.fetch(window.join(','), { envelope: true, uid: true }, { uid: true })) {
262
+ const address = msg.envelope?.from?.[0]?.address ?? '';
263
+ if (matchesAllowlist(address, account.allowedSenders)) {
264
+ if (allowed.length < limit)
265
+ allowed.push(msg.uid);
266
+ }
267
+ else {
268
+ refused++;
269
+ }
270
+ if (allowed.length >= limit)
271
+ break;
272
+ }
273
+ const messages = [];
274
+ for (const uid of allowed) {
275
+ const msg = await client.fetchOne(String(uid), { source: true, internalDate: true }, { uid: true });
276
+ if (!msg || !msg.source)
277
+ continue;
278
+ const parsed = await simpleParser(msg.source);
279
+ const { body, truncated } = truncateBody(messageText(parsed));
280
+ messages.push({
281
+ uid,
282
+ from: parsed.from?.text ?? '',
283
+ to: parsed.to?.text ?? '',
284
+ subject: parsed.subject ?? '',
285
+ // The server's INTERNALDATE always exists; a Date header may be absent
286
+ // or malformed, and mailparser then leaves the field undefined. (imapflow
287
+ // types internalDate as string | Date depending on the fetch shape.)
288
+ date: isoDate(parsed.date ?? msg.internalDate),
289
+ body,
290
+ ...(truncated ? { truncated } : {}),
291
+ attachments: (parsed.attachments ?? []).map((a) => a.filename ?? '(unnamed)'),
292
+ });
293
+ }
294
+ // Only what the agent actually received is marked read — a refused message
295
+ // is left untouched for the human.
296
+ if (markSeen && messages.length) {
297
+ await client.messageFlagsAdd(messages.map((m) => m.uid).join(','), ['\\Seen'], { uid: true });
298
+ }
299
+ return { messages, refused, ...(scanTruncated ? { scanTruncated } : {}) };
300
+ }
301
+ finally {
302
+ disarm();
303
+ lock.release();
304
+ await client.logout().catch(() => client.close());
305
+ }
306
+ }
@@ -0,0 +1,13 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import type { Tool } from '../harness/tools/index.js';
3
+ import type { AgentConfig } from '../types.js';
4
+ export declare const TASK_PREFIX = "mcp__task__";
5
+ export declare const EMAIL_PREFIX = "mcp__email__";
6
+ export declare function builtinMcpTools(): Tool[];
7
+ export declare function buildBuiltinMcpServer(info?: {
8
+ name: string;
9
+ version: string;
10
+ }, opts?: {
11
+ callerAgent?: AgentConfig;
12
+ }): Server;
13
+ //# sourceMappingURL=builtin_server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtin_server.d.ts","sourceRoot":"","sources":["../../src/mcp/builtin_server.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAGnE,OAAO,KAAK,EAAE,IAAI,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,eAAO,MAAM,WAAW,gBAAgB,CAAC;AACzC,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAQ3C,wBAAgB,eAAe,IAAI,IAAI,EAAE,CAExC;AAED,wBAAgB,qBAAqB,CACnC,IAAI,GAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAiD,EACtF,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAO,GACvC,MAAM,CAoCR"}
@@ -0,0 +1,65 @@
1
+ // Shared builder: wraps the built-in `mcp__<ns>__*` registry tools as an MCP
2
+ // Server. Used by BOTH the per-task HTTP bridge (cli/web/mcp_bridge.ts) and the
3
+ // general stdio subcommand (cli/mcp.ts) so this surface has one definition and
4
+ // one wrapping. Two namespaces today — `task` (drive the autonomous task state
5
+ // machine) and `email` (send mail through a configured account); a new tool in
6
+ // either is picked up by both consumers through the prefix filter, never a
7
+ // second allowlist.
8
+ //
9
+ // The tools are context-free (they take task_id / account by argument), so a
10
+ // stub ToolContext is sufficient — except for the caller's identity, which the
11
+ // email tools use to scope which accounts exist for this agent. The HTTP bridge
12
+ // passes it (resolved from the per-run token); the stdio server does not have
13
+ // one and is unscoped by design, its trust boundary being local process access
14
+ // to CARETAKER_HOME.
15
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
+ import { tools as registry } from '../harness/tools/instance.js';
18
+ export const TASK_PREFIX = 'mcp__task__';
19
+ export const EMAIL_PREFIX = 'mcp__email__';
20
+ const SERVED_PREFIXES = [TASK_PREFIX, EMAIL_PREFIX];
21
+ /** `mcp__task__task_complete` → `task_complete`, `mcp__email__email_send` → `email_send`. */
22
+ function externalName(name) {
23
+ return name.replace(/^mcp__[a-z]+__/, '');
24
+ }
25
+ export function builtinMcpTools() {
26
+ return registry.list().filter((t) => SERVED_PREFIXES.some((p) => t.name.startsWith(p)));
27
+ }
28
+ export function buildBuiltinMcpServer(info = { name: 'caretaker-task', version: '0.0.0' }, opts = {}) {
29
+ const server = new Server(info, { capabilities: { tools: {} } });
30
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
31
+ tools: builtinMcpTools().map((t) => ({
32
+ name: externalName(t.name),
33
+ description: t.description,
34
+ inputSchema: t.parameters,
35
+ })),
36
+ }));
37
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
38
+ const tool = builtinMcpTools().find((t) => externalName(t.name) === req.params.name);
39
+ if (!tool) {
40
+ return {
41
+ content: [{ type: 'text', text: `Error: unknown tool "${req.params.name}"` }],
42
+ isError: true,
43
+ };
44
+ }
45
+ // ponytail: the task tools ignore ctx entirely; the email tools read only
46
+ // callerAgent. A stub covers the rest.
47
+ const ctx = {
48
+ workingDir: process.cwd(),
49
+ signal: new AbortController().signal,
50
+ readPaths: new Set(),
51
+ callerAgent: opts.callerAgent,
52
+ };
53
+ try {
54
+ const result = await tool.execute(req.params.arguments ?? {}, ctx);
55
+ return { content: [{ type: 'text', text: result.content }] };
56
+ }
57
+ catch (err) {
58
+ return {
59
+ content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }],
60
+ isError: true,
61
+ };
62
+ }
63
+ });
64
+ return server;
65
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/store/json.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAM7F,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAI3D,wBAAgB,OAAO,IAAI,MAAM,CAEhC;AACD,wBAAgB,UAAU,IAAI,MAAM,CAEnC;AACD,wBAAgB,UAAU,IAAI,MAAM,CAEnC;AACD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AAM,aAAa,EAAE,eAG3B,CAAC;AAqDF,wBAAsB,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC,CAE3D;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BlE;AAED,wBAAsB,UAAU,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,CAEzD;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhE;AAED,wBAAsB,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,CASxD;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAElE;AAMD,wBAAsB,cAAc,IAAI,OAAO,CAAC,cAAc,CAAC,CAO9D;AAED,wBAAsB,cAAc,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAExE;AAID;;;GAGG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAO5E"}
@@ -90,6 +90,12 @@ export async function saveConfig(c) {
90
90
  task.telegramBotToken = encrypt(task.telegramBotToken);
91
91
  }
92
92
  }
93
+ if (task.type === 'email' && task.imapPassword && !isEncrypted(task.imapPassword)) {
94
+ task.imapPassword = encrypt(task.imapPassword);
95
+ }
96
+ if (task.type === 'email' && task.smtpPassword && !isEncrypted(task.smtpPassword)) {
97
+ task.smtpPassword = encrypt(task.smtpPassword);
98
+ }
93
99
  }
94
100
  }
95
101
  for (const project of c.projects || []) {
@@ -252,6 +252,26 @@ const CLAUDE_CODE_PERMISSION_MODES = [
252
252
  'dontAsk',
253
253
  'plan',
254
254
  ];
255
+ const NAMESPACE_DESCRIPTIONS = {
256
+ mcp__task__: 'Manage autonomous tasks & checklists',
257
+ mcp__email__: 'List the configured email accounts and send mail',
258
+ };
259
+ /** The picker's tool list: one synthetic entry per `mcp__<ns>__` namespace in
260
+ * place of its individual tools, everything else as-is. */
261
+ function namespacedToolList(tools) {
262
+ const namespaces = [
263
+ ...new Set(tools.map((t) => /^mcp__[a-z]+__/.exec(t.name)?.[0]).filter((p) => !!p)),
264
+ ];
265
+ return [
266
+ ...tools.filter((t) => !namespaces.some((p) => t.name.startsWith(p))),
267
+ ...namespaces.map((p) => ({
268
+ name: `${p}*`,
269
+ description: `${NAMESPACE_DESCRIPTIONS[p] ?? p} (enables all ${p}* tools)`,
270
+ parameters: { type: 'object', properties: {} },
271
+ execute: async () => ({ content: '' }),
272
+ })),
273
+ ];
274
+ }
255
275
  // Computes the step sequence for a given form flavor, so claude-code's
256
276
  // skip-tools/plugins/maxTurns + insert-permissionMode branching lives in one
257
277
  // place instead of scattered across every transition.
@@ -283,12 +303,22 @@ function AgentForm({ providers, existingNames, initial, onSave, onCancel, }) {
283
303
  const [systemPrompt, setSystemPrompt] = useState(initial?.systemPrompt ?? '');
284
304
  const [permissionMode, setPermissionMode] = useState(initial?.permissionMode ?? '');
285
305
  const [strictMcp, setStrictMcp] = useState(initial?.strictMcp ?? false);
306
+ // The picker offers one entry per `mcp__<ns>__` namespace (task, email, …),
307
+ // not the individual tools, so a stored per-tool selection is collapsed onto
308
+ // the wildcard. resolveAgentTools expands it back at run time.
286
309
  const normalizeTools = (tools) => {
287
- const hasTaskTools = tools.some((t) => t.startsWith('mcp__task__'));
288
- if (hasTaskTools) {
289
- return [...tools.filter((t) => !t.startsWith('mcp__task__')), 'mcp__task__*'];
290
- }
291
- return tools;
310
+ const wildcards = new Set();
311
+ const rest = tools.filter((t) => {
312
+ const ns = /^mcp__[a-z]+__/.exec(t);
313
+ if (!ns || t.endsWith('*'))
314
+ return !ns;
315
+ wildcards.add(`${ns[0]}*`);
316
+ return false;
317
+ });
318
+ for (const t of tools)
319
+ if (t.endsWith('*') && t.startsWith('mcp__'))
320
+ wildcards.add(t);
321
+ return [...rest, ...wildcards];
292
322
  };
293
323
  const [allowedTools, setAllowedTools] = useState(normalizeTools(initial?.allowedTools ?? []));
294
324
  const [confirmTools, setConfirmTools] = useState(normalizeTools(initial?.confirmTools ?? []));
@@ -387,15 +417,7 @@ function AgentForm({ providers, existingNames, initial, onSave, onCancel, }) {
387
417
  setModel(id);
388
418
  setError(null);
389
419
  setStep(nextAfter('model'));
390
- } })) : ['name', 'provider'].includes(step) ? (_jsx(Text, { dimColor: true, children: "(pending)" })) : (_jsx(Text, { children: model }))] }), _jsxs(Box, { children: [_jsx(Text, { children: "prompt: " }), managed ? (_jsxs(Text, { children: [_jsxs(Text, { children: [(systemPrompt || '(empty)').slice(0, 80), systemPrompt.length > 80 ? '…' : ''] }), _jsx(Text, { dimColor: true, children: ' (managed by plugin)' })] })) : step === 'systemPrompt' ? (_jsx(TextInput, { value: systemPrompt, onChange: setSystemPrompt, onSubmit: advance, placeholder: isEdit ? '(enter to keep current)' : '(optional system prompt)' })) : ['name', 'provider', 'model'].includes(step) ? (_jsx(Text, { dimColor: true, children: "(pending)" })) : (_jsx(Text, { children: systemPrompt || '(empty)' }))] }), !isClaudeCode && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "tools:" }), step === 'tools' ? (_jsx(ToolPicker, { tools: [
391
- ...toolRegistry.list().filter((t) => !t.name.startsWith('mcp__task__')),
392
- {
393
- name: 'mcp__task__*',
394
- description: 'Manage autonomous tasks & checklists (enables all mcp__task__* tools)',
395
- parameters: { type: 'object', properties: {} },
396
- execute: async () => ({ content: '' }),
397
- },
398
- ], allowed: allowedTools, confirm: confirmTools, onChange: (a, c) => {
420
+ } })) : ['name', 'provider'].includes(step) ? (_jsx(Text, { dimColor: true, children: "(pending)" })) : (_jsx(Text, { children: model }))] }), _jsxs(Box, { children: [_jsx(Text, { children: "prompt: " }), managed ? (_jsxs(Text, { children: [_jsxs(Text, { children: [(systemPrompt || '(empty)').slice(0, 80), systemPrompt.length > 80 ? '…' : ''] }), _jsx(Text, { dimColor: true, children: ' (managed by plugin)' })] })) : step === 'systemPrompt' ? (_jsx(TextInput, { value: systemPrompt, onChange: setSystemPrompt, onSubmit: advance, placeholder: isEdit ? '(enter to keep current)' : '(optional system prompt)' })) : ['name', 'provider', 'model'].includes(step) ? (_jsx(Text, { dimColor: true, children: "(pending)" })) : (_jsx(Text, { children: systemPrompt || '(empty)' }))] }), !isClaudeCode && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "tools:" }), step === 'tools' ? (_jsx(ToolPicker, { tools: namespacedToolList(toolRegistry.list()), allowed: allowedTools, confirm: confirmTools, onChange: (a, c) => {
399
421
  setAllowedTools(a);
400
422
  setConfirmTools(c);
401
423
  }, onSubmit: advance })) : ['name', 'provider', 'model', 'systemPrompt'].includes(step) ? (_jsx(Text, { dimColor: true, children: " (pending)" })) : (_jsx(Text, { children: ` ${allowedTools.length === 0 ? '(none)' : formatToolsForDetail(allowedTools, confirmTools)}` }))] })), !isClaudeCode && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "plugins:" }), step === 'plugins' ? (_jsx(PluginPicker, { plugins: discoveredPlugins, value: activePlugins, onChange: setActivePlugins, onSubmit: advance })) : ['name', 'provider', 'model', 'systemPrompt', 'tools'].includes(step) ? (_jsx(Text, { dimColor: true, children: " (pending)" })) : (_jsx(Text, { children: ` ${activePlugins.length === 0 ? '(none)' : activePlugins.join(', ')}` }))] })), _jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { children: "mcp:" }), step === 'mcpServers' ? (_jsx(McpPicker, { servers: mcpServers, value: activeMcp, onChange: setActiveMcp, onSubmit: advance })) : ['name', 'provider', 'model', 'systemPrompt', 'tools', 'plugins'].includes(step) ? (_jsx(Text, { dimColor: true, children: " (pending)" })) : (_jsx(Text, { children: ` ${activeMcp.length === 0