@hyperwindmill/caretaker-cli 0.31.0 → 0.32.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.
@@ -10,6 +10,8 @@ import type { ServiceConfig } from '../types.js';
10
10
  export declare const NET_TIMEOUT_MS = 60000;
11
11
  /** An email account with its secrets decrypted and its defaults applied. */
12
12
  export type EmailAccount = {
13
+ /** The service record id. */
14
+ id: string;
13
15
  name: string;
14
16
  from: string;
15
17
  smtpHost: string;
@@ -145,4 +147,22 @@ export declare function fetchInbox(account: EmailAccount, opts?: FetchOptions):
145
147
  refused: number;
146
148
  scanTruncated?: boolean;
147
149
  }>;
150
+ export type TriageEnvelope = {
151
+ uid: number;
152
+ from: string;
153
+ subject: string;
154
+ date: string;
155
+ };
156
+ /** Oldest unseen envelopes the account may read; no bodies, no flag changes. */
157
+ export declare function listUnseenEnvelopes(account: EmailAccount, max: number, signal?: AbortSignal): Promise<{
158
+ envelopes: TriageEnvelope[];
159
+ refused: number;
160
+ scanTruncated: boolean;
161
+ uidValidity: string;
162
+ }>;
163
+ /** One message by UID, or null when it does not exist or its sender is not
164
+ * allowed. `source` is fetched as BODY.PEEK[], so `\Seen` stays untouched. */
165
+ export declare function readMessage(account: EmailAccount, uid: number, signal?: AbortSignal): Promise<InboundMessage | null>;
166
+ /** Mark `uids` seen, unless the mailbox was reset since they were listed. */
167
+ export declare function markSeen(account: EmailAccount, uids: number[], expectedUidValidity: string, signal?: AbortSignal): Promise<'marked' | 'uidvalidity-changed'>;
148
168
  //# sourceMappingURL=email.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,QAAS,CAAC;AAarC,4EAA4E;AAC5E,MAAM,MAAM,YAAY,GAAG;IACzB,IA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AO,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CA6BxG;AAED;+EAC+E;AAC/E,wBAAsB,WAAW,CAC/B,OAAO,EAAE,YAAY,EACrB,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAahC;AAED,6EAA6E;AAC7E,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,YAAY,EACrB,IAAI,EAAE,MAAM,EAAE,EACd,mBAAmB,EAAE,MAAM,EAC3B,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,GAAG,qBAAqB,CAAC,CAO3C"}
package/dist/lib/email.js CHANGED
@@ -94,6 +94,7 @@ export function emailAccounts(services) {
94
94
  return services
95
95
  .filter((s) => s.type === 'email' && s.enabled)
96
96
  .map((s) => ({
97
+ id: s.id,
97
98
  name: s.name,
98
99
  from: (s.smtpFrom || s.imapUser || '').trim(),
99
100
  smtpHost: (s.smtpHost ?? '').trim(),
@@ -154,9 +155,14 @@ export function findAccount(accounts, name) {
154
155
  */
155
156
  export function markdownToHtml(markdown) {
156
157
  const body = marked.parse(markdown, { async: false, gfm: true });
158
+ // Tables: clients strip <style>, so borders go inline; border="1" is for old Outlook.
159
+ const cell = 'border:1px solid #999;padding:6px 10px;text-align:left;vertical-align:top';
160
+ const html = body
161
+ .replace(/<table(?=[\s>])/g, '<table border="1" style="border-collapse:collapse"')
162
+ .replace(/<(th|td)(?=[\s>])/g, `<$1 style="${cell}"`);
157
163
  return ('<div style="font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;' +
158
164
  'font-size:14px;line-height:1.5;color:#1a1a1a;max-width:40em">' +
159
- body +
165
+ html +
160
166
  '</div>');
161
167
  }
162
168
  /** Send one message (plain text, plus an HTML alternative when given).
@@ -193,11 +199,14 @@ export async function sendEmail(account, mail, signal) {
193
199
  }
194
200
  // ─── Inbound ──────────────────────────────────────────────────────────────
195
201
  //
196
- // There is no `email` scheduler strategy and no stored UID cursor: an inbound
197
- // workflow is a `heartbeat` service whose prompt tells the agent to call
198
- // email_fetch, and "already handled" is the IMAP `\Seen` flag — server state,
199
- // shared with the user's own mail client. Two behaviours on one account are two
200
- // heartbeats, which is also how a per-subject triage is expressed.
202
+ // There is no generic `email` scheduler strategy and no stored UID cursor: a
203
+ // generic inbound workflow is a `heartbeat` service whose prompt tells the agent
204
+ // to call email_fetch, and "already handled" is the IMAP `\Seen` flag — server
205
+ // state, shared with the user's own mail client. Two behaviours on one account
206
+ // are two heartbeats. The dedicated `email_triage` service (cli/web/scheduler/)
207
+ // references an account by id and uses the peek-style helpers below
208
+ // (listUnseenEnvelopes / readMessage / markSeen) so it marks mail read only
209
+ // after its report is delivered.
201
210
  /** Hard ceiling on messages per call, whatever the caller asks for. */
202
211
  export const MAX_FETCH = 50;
203
212
  /** How many unread messages we are willing to look at to fill one window.
@@ -235,11 +244,9 @@ export function messageText(parsed) {
235
244
  return turndown.turndown(parsed.html);
236
245
  return '';
237
246
  }
238
- /** Read the oldest matching messages from INBOX. */
239
- export async function fetchInbox(account, opts = {}) {
240
- const limit = clampLimit(opts.limit);
241
- const markSeen = opts.markSeen !== false;
242
- if (opts.signal?.aborted)
247
+ /** Connect, lock INBOX, run `fn`, and always release and log out. */
248
+ async function withInbox(account, signal, fn) {
249
+ if (signal?.aborted)
243
250
  throw new Error('aborted before connecting');
244
251
  const client = new ImapFlow({
245
252
  host: account.imapHost,
@@ -248,7 +255,7 @@ export async function fetchInbox(account, opts = {}) {
248
255
  auth: { user: account.imapUser, pass: account.imapPassword },
249
256
  logger: false,
250
257
  });
251
- const disarm = armAbort(() => client.close(), opts.signal);
258
+ const disarm = armAbort(() => client.close(), signal);
252
259
  try {
253
260
  await client.connect();
254
261
  }
@@ -258,6 +265,36 @@ export async function fetchInbox(account, opts = {}) {
258
265
  }
259
266
  const lock = await client.getMailboxLock('INBOX');
260
267
  try {
268
+ return await fn(client);
269
+ }
270
+ finally {
271
+ disarm();
272
+ lock.release();
273
+ await client.logout().catch(() => client.close());
274
+ }
275
+ }
276
+ /** Build the model-facing message from a parsed source. */
277
+ function toInbound(uid, parsed, internalDate) {
278
+ const { body, truncated } = truncateBody(messageText(parsed));
279
+ return {
280
+ uid,
281
+ from: parsed.from?.text ?? '',
282
+ to: parsed.to?.text ?? '',
283
+ subject: parsed.subject ?? '',
284
+ // The server's INTERNALDATE always exists; a Date header may be absent
285
+ // or malformed, and mailparser then leaves the field undefined. (imapflow
286
+ // types internalDate as string | Date depending on the fetch shape.)
287
+ date: isoDate(parsed.date ?? internalDate),
288
+ body,
289
+ ...(truncated ? { truncated } : {}),
290
+ attachments: (parsed.attachments ?? []).map((a) => a.filename ?? '(unnamed)'),
291
+ };
292
+ }
293
+ /** Read the oldest matching messages from INBOX. */
294
+ export async function fetchInbox(account, opts = {}) {
295
+ const limit = clampLimit(opts.limit);
296
+ const markSeen = opts.markSeen !== false;
297
+ return withInbox(account, opts.signal, async (client) => {
261
298
  // Only the two criteria every server implements the same way. The sender
262
299
  // allowlist is applied below, host-side: IMAP `SEARCH FROM` is substring by
263
300
  // spec but not in practice (GreenMail matches whole addresses only and
@@ -297,21 +334,7 @@ export async function fetchInbox(account, opts = {}) {
297
334
  const msg = await client.fetchOne(String(uid), { source: true, internalDate: true }, { uid: true });
298
335
  if (!msg || !msg.source)
299
336
  continue;
300
- const parsed = await simpleParser(msg.source);
301
- const { body, truncated } = truncateBody(messageText(parsed));
302
- messages.push({
303
- uid,
304
- from: parsed.from?.text ?? '',
305
- to: parsed.to?.text ?? '',
306
- subject: parsed.subject ?? '',
307
- // The server's INTERNALDATE always exists; a Date header may be absent
308
- // or malformed, and mailparser then leaves the field undefined. (imapflow
309
- // types internalDate as string | Date depending on the fetch shape.)
310
- date: isoDate(parsed.date ?? msg.internalDate),
311
- body,
312
- ...(truncated ? { truncated } : {}),
313
- attachments: (parsed.attachments ?? []).map((a) => a.filename ?? '(unnamed)'),
314
- });
337
+ messages.push(toInbound(uid, await simpleParser(msg.source), msg.internalDate));
315
338
  }
316
339
  // Only what the agent actually received is marked read — a refused message
317
340
  // is left untouched for the human.
@@ -319,10 +342,60 @@ export async function fetchInbox(account, opts = {}) {
319
342
  await client.messageFlagsAdd(messages.map((m) => m.uid).join(','), ['\\Seen'], { uid: true });
320
343
  }
321
344
  return { messages, refused, ...(scanTruncated ? { scanTruncated } : {}) };
322
- }
323
- finally {
324
- disarm();
325
- lock.release();
326
- await client.logout().catch(() => client.close());
327
- }
345
+ });
346
+ }
347
+ /** Oldest unseen envelopes the account may read; no bodies, no flag changes. */
348
+ export async function listUnseenEnvelopes(account, max, signal) {
349
+ const limit = clampLimit(max);
350
+ return withInbox(account, signal, async (client) => {
351
+ const uidValidity = String(client.mailbox.uidValidity ?? '');
352
+ const uids = (await client.search({ seen: false }, { uid: true }));
353
+ const envelopes = [];
354
+ let refused = 0;
355
+ if (!uids || uids.length === 0)
356
+ return { envelopes, refused, scanTruncated: false, uidValidity };
357
+ const scanTruncated = uids.length > MAX_SCAN;
358
+ for await (const msg of client.fetch(uids.slice(0, MAX_SCAN).join(','), { envelope: true, uid: true, internalDate: true }, { uid: true })) {
359
+ const from = msg.envelope?.from?.[0]?.address ?? '';
360
+ if (!matchesAllowlist(from, account.allowedSenders)) {
361
+ refused++;
362
+ continue;
363
+ }
364
+ envelopes.push({
365
+ uid: msg.uid,
366
+ from,
367
+ subject: msg.envelope?.subject ?? '',
368
+ date: isoDate(msg.envelope?.date ?? msg.internalDate),
369
+ });
370
+ if (envelopes.length >= limit)
371
+ break;
372
+ }
373
+ return { envelopes, refused, scanTruncated, uidValidity };
374
+ });
375
+ }
376
+ /** One message by UID, or null when it does not exist or its sender is not
377
+ * allowed. `source` is fetched as BODY.PEEK[], so `\Seen` stays untouched. */
378
+ export async function readMessage(account, uid, signal) {
379
+ return withInbox(account, signal, async (client) => {
380
+ const env = await client.fetchOne(String(uid), { envelope: true }, { uid: true });
381
+ if (!env)
382
+ return null;
383
+ if (!matchesAllowlist(env.envelope?.from?.[0]?.address ?? '', account.allowedSenders))
384
+ return null;
385
+ const msg = await client.fetchOne(String(uid), { source: true, internalDate: true }, { uid: true });
386
+ if (!msg || !msg.source)
387
+ return null;
388
+ return toInbound(uid, await simpleParser(msg.source), msg.internalDate);
389
+ });
390
+ }
391
+ /** Mark `uids` seen, unless the mailbox was reset since they were listed. */
392
+ export async function markSeen(account, uids, expectedUidValidity, signal) {
393
+ return withInbox(account, signal, async (client) => {
394
+ const current = String(client.mailbox.uidValidity ?? '');
395
+ if (current !== expectedUidValidity)
396
+ return 'uidvalidity-changed';
397
+ if (uids.length)
398
+ await client.messageFlagsAdd(uids.join(','), ['\\Seen'], { uid: true });
399
+ return 'marked';
400
+ });
328
401
  }
@@ -19849,6 +19849,32 @@ Please report this to https://github.com/markedjs/marked.`, e) {
19849
19849
 
19850
19850
  // src/ServicesTab.tsx
19851
19851
  var import_react14 = __toESM(require_react(), 1);
19852
+
19853
+ // src/services_form_utils.ts
19854
+ function triageAccountOptions(services, agentId) {
19855
+ return services.filter(
19856
+ (s) => s.type === "email" && s.enabled && !!s.imapHost && !!s.smtpHost && (!s.allowedAgents?.length || s.allowedAgents.includes(agentId))
19857
+ );
19858
+ }
19859
+ function splitRecipients(raw) {
19860
+ return (raw || "").split(/[,\n;]/).map((r) => r.trim()).filter(Boolean);
19861
+ }
19862
+ function triageFormError(f, accounts) {
19863
+ if (!f.agentId) return "Please select an agent for this service.";
19864
+ if (f.cron.trim().split(/\s+/).filter(Boolean).length !== 5) {
19865
+ return 'Invalid cron expression. It must contain exactly 5 space-separated fields (e.g. "*/15 * * * *").';
19866
+ }
19867
+ if (!f.accountId) return "Select the email account to triage.";
19868
+ if (!accounts.some((a2) => a2.id === f.accountId)) {
19869
+ return "The selected email account is not available (it must be enabled, have IMAP and SMTP, and be open to the selected agent).";
19870
+ }
19871
+ if (splitRecipients(f.recipients).length === 0) return "Add at least one recipient for the triage report.";
19872
+ const n = Number(f.maxEmails);
19873
+ if (!/^\d+$/.test(f.maxEmails.trim()) || n < 1 || n > 50) return "Max emails must be a whole number between 1 and 50.";
19874
+ return null;
19875
+ }
19876
+
19877
+ // src/ServicesTab.tsx
19852
19878
  var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
19853
19879
  function closeStreamingAssistant(items) {
19854
19880
  const last = items[items.length - 1];
@@ -19934,6 +19960,10 @@ Please report this to https://github.com/markedjs/marked.`, e) {
19934
19960
  const [allowedSenders, setAllowedSenders] = (0, import_react14.useState)("");
19935
19961
  const [allowedRecipients, setAllowedRecipients] = (0, import_react14.useState)("");
19936
19962
  const [allowedAgents, setAllowedAgents] = (0, import_react14.useState)([]);
19963
+ const [triageAccountId, setTriageAccountId] = (0, import_react14.useState)("");
19964
+ const [triageRecipients, setTriageRecipients] = (0, import_react14.useState)("");
19965
+ const [triageMaxEmails, setTriageMaxEmails] = (0, import_react14.useState)("50");
19966
+ const [triageSubjectPrefix, setTriageSubjectPrefix] = (0, import_react14.useState)("");
19937
19967
  const [errorMsg, setErrorMsg] = (0, import_react14.useState)(null);
19938
19968
  const startEdit = (task) => {
19939
19969
  setEditingTask(task);
@@ -19961,6 +19991,10 @@ Please report this to https://github.com/markedjs/marked.`, e) {
19961
19991
  setAllowedSenders(task.allowedSenders || "");
19962
19992
  setAllowedRecipients(task.allowedRecipients || "");
19963
19993
  setAllowedAgents(task.allowedAgents || []);
19994
+ setTriageAccountId(task.triageAccountId || "");
19995
+ setTriageRecipients(task.triageRecipients || "");
19996
+ setTriageMaxEmails(task.triageMaxEmails ? String(task.triageMaxEmails) : "50");
19997
+ setTriageSubjectPrefix(task.triageSubjectPrefix || "");
19964
19998
  setErrorMsg(null);
19965
19999
  };
19966
20000
  const startCreate = () => {
@@ -19989,6 +20023,10 @@ Please report this to https://github.com/markedjs/marked.`, e) {
19989
20023
  setAllowedSenders("");
19990
20024
  setAllowedRecipients("");
19991
20025
  setAllowedAgents([]);
20026
+ setTriageAccountId("");
20027
+ setTriageRecipients("");
20028
+ setTriageMaxEmails("50");
20029
+ setTriageSubjectPrefix("");
19992
20030
  setErrorMsg(null);
19993
20031
  };
19994
20032
  const cancelForm = () => {
@@ -20026,6 +20064,15 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20026
20064
  setErrorMsg('Invalid cron expression. It must contain exactly 5 space-separated fields (e.g. "*/15 * * * *").');
20027
20065
  return;
20028
20066
  }
20067
+ } else if (type === "email_triage") {
20068
+ const err = triageFormError(
20069
+ { agentId, cron: trimmedCron, accountId: triageAccountId, recipients: triageRecipients, maxEmails: triageMaxEmails },
20070
+ triageAccountOptions(tasks, agentId)
20071
+ );
20072
+ if (err) {
20073
+ setErrorMsg(err);
20074
+ return;
20075
+ }
20029
20076
  } else if (type === "telegram") {
20030
20077
  if (!telegramBotToken.trim()) {
20031
20078
  setErrorMsg("Telegram Bot Token is required.");
@@ -20075,6 +20122,12 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20075
20122
  telegramBotToken: telegramBotToken.trim(),
20076
20123
  telegramAllowedChats: telegramAllowedChats.trim()
20077
20124
  } : {},
20125
+ ...type === "email_triage" ? {
20126
+ triageAccountId,
20127
+ triageRecipients: triageRecipients.trim(),
20128
+ triageMaxEmails: Number(triageMaxEmails),
20129
+ triageSubjectPrefix: triageSubjectPrefix.trim()
20130
+ } : {},
20078
20131
  ...type === "email" ? {
20079
20132
  imapHost: imapHost.trim(),
20080
20133
  imapPort: Number(imapPort),
@@ -20200,7 +20253,8 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20200
20253
  children: [
20201
20254
  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "heartbeat", children: "Heartbeat (Scheduled Agent Run)" }),
20202
20255
  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "telegram", children: "Telegram Bot (Poller)" }),
20203
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "email", children: "Email (IMAP credentials)" })
20256
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "email", children: "Email (IMAP credentials)" }),
20257
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "email_triage", children: "Email triage (Scheduled Report)" })
20204
20258
  ]
20205
20259
  }
20206
20260
  )
@@ -20294,6 +20348,134 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20294
20348
  }
20295
20349
  )
20296
20350
  ] })
20351
+ ] }) : type === "email_triage" ? /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [
20352
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20353
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "task-cron", children: "Cron Timing" }),
20354
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20355
+ "input",
20356
+ {
20357
+ id: "task-cron",
20358
+ type: "text",
20359
+ placeholder: "e.g. 0 8 * * * (every morning at 8)",
20360
+ value: cron,
20361
+ onChange: (e) => setCron(e.target.value)
20362
+ }
20363
+ )
20364
+ ] }),
20365
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20366
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "triage-account", children: "Email account" }),
20367
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
20368
+ "select",
20369
+ {
20370
+ id: "triage-account",
20371
+ value: triageAccountId,
20372
+ onChange: (e) => setTriageAccountId(e.target.value),
20373
+ style: {
20374
+ width: "100%",
20375
+ padding: "6px 8px",
20376
+ borderRadius: "var(--radius-sm)",
20377
+ background: "var(--vscode-dropdown-background, #252526)",
20378
+ color: "var(--vscode-dropdown-foreground, #cccccc)",
20379
+ border: "1px solid var(--vscode-dropdown-border, #3c3c3c)",
20380
+ fontSize: "12px",
20381
+ cursor: "pointer"
20382
+ },
20383
+ children: [
20384
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: "", disabled: true, children: "-- Select account --" }),
20385
+ triageAccountOptions(tasks, agentId).map((a2) => /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("option", { value: a2.id, children: a2.name }, a2.id))
20386
+ ]
20387
+ }
20388
+ ),
20389
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "field-hint", style: { fontSize: "11px", opacity: 0.8, marginTop: "4px" }, children: "Only enabled email services with both IMAP and SMTP configured are listed." })
20390
+ ] }),
20391
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20392
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "triage-recipients", children: "Report recipients (one per line)" }),
20393
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20394
+ "textarea",
20395
+ {
20396
+ id: "triage-recipients",
20397
+ placeholder: "you@example.com",
20398
+ value: triageRecipients,
20399
+ onChange: (e) => setTriageRecipients(e.target.value),
20400
+ rows: 3,
20401
+ style: {
20402
+ width: "100%",
20403
+ padding: "8px",
20404
+ borderRadius: "var(--radius-sm)",
20405
+ background: "var(--vscode-input-background, #252526)",
20406
+ color: "var(--vscode-input-foreground, #cccccc)",
20407
+ border: "1px solid var(--vscode-input-border, #3c3c3c)",
20408
+ fontFamily: "inherit",
20409
+ fontSize: "12px",
20410
+ resize: "vertical"
20411
+ }
20412
+ }
20413
+ )
20414
+ ] }),
20415
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20416
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "triage-max", children: "Max emails per run (1-50)" }),
20417
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20418
+ "input",
20419
+ {
20420
+ id: "triage-max",
20421
+ type: "number",
20422
+ min: 1,
20423
+ max: 50,
20424
+ value: triageMaxEmails,
20425
+ onChange: (e) => setTriageMaxEmails(e.target.value)
20426
+ }
20427
+ )
20428
+ ] }),
20429
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20430
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "triage-prefix", children: "Subject prefix (optional)" }),
20431
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20432
+ "input",
20433
+ {
20434
+ id: "triage-prefix",
20435
+ type: "text",
20436
+ placeholder: "[Email Triage]",
20437
+ value: triageSubjectPrefix,
20438
+ onChange: (e) => setTriageSubjectPrefix(e.target.value)
20439
+ }
20440
+ )
20441
+ ] }),
20442
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20443
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "task-dir", children: "Working Directory (Absolute path, optional)" }),
20444
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20445
+ "input",
20446
+ {
20447
+ id: "task-dir",
20448
+ type: "text",
20449
+ placeholder: "e.g. /home/user/project (default: process.cwd())",
20450
+ value: workingDir,
20451
+ onChange: (e) => setWorkingDir(e.target.value)
20452
+ }
20453
+ )
20454
+ ] }),
20455
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20456
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "task-prompt", children: "Extra triage instructions (optional)" }),
20457
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20458
+ "textarea",
20459
+ {
20460
+ id: "task-prompt",
20461
+ placeholder: "e.g. Treat anything from our main client as urgent.",
20462
+ value: prompt,
20463
+ onChange: (e) => setPrompt(e.target.value),
20464
+ rows: 4,
20465
+ style: {
20466
+ width: "100%",
20467
+ padding: "8px",
20468
+ borderRadius: "var(--radius-sm)",
20469
+ background: "var(--vscode-input-background, #252526)",
20470
+ color: "var(--vscode-input-foreground, #cccccc)",
20471
+ border: "1px solid var(--vscode-input-border, #3c3c3c)",
20472
+ fontFamily: "inherit",
20473
+ fontSize: "12px",
20474
+ resize: "vertical"
20475
+ }
20476
+ }
20477
+ )
20478
+ ] })
20297
20479
  ] }) : type === "telegram" ? /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [
20298
20480
  /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "form-group", children: [
20299
20481
  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("label", { htmlFor: "tg-token", children: "Telegram Bot Token" }),
@@ -20639,6 +20821,22 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20639
20821
  task.imapPort,
20640
20822
  task.smtpHost ? ` \xB7 SMTP ${task.smtpHost}:${task.smtpPort}` : " \xB7 sending off",
20641
20823
  task.allowedAgents?.length ? ` \xB7 agents: ${task.allowedAgents.map((id) => agents.find((a2) => a2.id === id)?.name || id).join(", ")}` : " \xB7 any agent"
20824
+ ] }) : task.type === "email_triage" ? /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "settings-card__subtitle", style: { fontSize: "11px", marginTop: "4px" }, children: [
20825
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("strong", { children: "Agent:" }),
20826
+ " ",
20827
+ agentName,
20828
+ " \xB7 ",
20829
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("strong", { children: "Schedule:" }),
20830
+ " ",
20831
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("code", { children: task.cron }),
20832
+ " \xB7 ",
20833
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("strong", { children: "Account:" }),
20834
+ " ",
20835
+ tasks.find((t) => t.id === task.triageAccountId)?.name || "missing",
20836
+ " \xB7",
20837
+ " ",
20838
+ splitRecipients(task.triageRecipients).length,
20839
+ " recipient(s)"
20642
20840
  ] }) : /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [
20643
20841
  /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "settings-card__subtitle", style: { fontSize: "11px", marginTop: "4px" }, children: [
20644
20842
  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("strong", { children: "Agent:" }),
@@ -20657,7 +20855,7 @@ Please report this to https://github.com/markedjs/marked.`, e) {
20657
20855
  ] })
20658
20856
  ] }),
20659
20857
  /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "settings-card__actions", children: [
20660
- task.type === "heartbeat" && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20858
+ (task.type === "heartbeat" || task.type === "email_triage") && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
20661
20859
  "button",
20662
20860
  {
20663
20861
  className: "icon-btn",